BERT-ATTACK: Adversarial Attack Against BERT Using BERT
Paper · 2020 · Linyang Li, Ruotian Ma, Qipeng Guo et al.
Summary
A classifier can give the right answer to a movie review and then reverse its judgment after a small change that leaves the reviewer’s opinion recognizable. BERT-Attack studies how often that kind of failure can be induced in text classification and natural language inference, where the task is to judge the relationship between a premise and a hypothesis. The challenge is to find wording that changes the classifier’s answer while preserving the human reading. Text offers no direct equivalent of nudging a pixel value. Each edit chooses a discrete word or fragment, and a plausible substitute in one sentence can sound unnatural or change the meaning in another.
The authors make two separate judgments about an input. They estimate which words matter to the classifier by temporarily replacing each word with a mask and observing the score for the correct label. They use pretrained BERT to propose replacements that fit the original wording and its surroundings. The original word stays visible during proposal generation, which allows BERT to suggest alternatives for every position in the same pass. The search tests candidates at influential positions and can carry forward a change that weakens the correct answer as it moves to another word. A separate procedure handles words represented by several fragments, scoring possible combinations by perplexity. The target classifier supplies output scores throughout. The method needs no access to its weights or gradients.
Across the benchmarks, the authors frequently leave fine-tuned BERT with lower accuracy than competing attacks do, while changing fewer words and using fewer classifier queries. On MNLI matched premises, BERT-Attack leaves the classifier at 11.9% accuracy, changes 7.9% of words, and uses an average of 44 queries per sample. TextFooler leaves it at 25.3% accuracy with 26.5% of words changed and 152 queries. The paper also reports successful tests against recurrent classifiers and BERT-large. On IMDB, the full method takes 16.0 seconds per sample, compared with 42.4 for TextFooler. The authors publish the implementation.
Human judgments put the quality claim in perspective. On IMDB and MNLI, edited texts receive grammar and meaning scores close to those of the originals, but readers are less accurate on the edited examples, especially on MNLI. Contextual plausibility helps produce readable edits and still leaves room for changes that affect the task itself. The authors also use examples generated from the MNLI training set for additional fine-tuning. The resulting classifier retains similar accuracy on clean text and is harder to fool in the reported evaluation, giving the generated examples a second role as training data.
Deep dive: BERT-ATTACK: Adversarial Attack Against BERT Using BERT
BERT-Attack uses BERT to test how small, context-sensitive word changes affect text classification and natural language inference. · about 33 minutes to read
The problem and its context
When a small edit ought to leave the answer alone
An adversarial example starts with an ordinary input and changes it so that a system makes an error. The test has force when the expected answer survives the change. If a review still conveys dislike, a classifier’s switch to a positive verdict reveals sensitivity that ordinary test accuracy leaves hidden. If the edit actually makes the reviewer sound approving, the same switch could be the appropriate response. For the authors, producing a wrong prediction and protecting the original reading are therefore parts of the same problem. Fluency matters too, since conspicuously broken language offers limited evidence about how a classifier handles the range of ways people naturally write.
Earlier research on images supplied the broad objective. A perturbation should remain small while making an incorrect prediction more likely. Image values are continuous, so a gradient can indicate how to move those values in a direction that makes the prediction less reliable. The paper traces this way of thinking to work including Explaining and Harnessing Adversarial Examples. Text presents a different choice at the point of editing. Even if a numerical representation admits a small move, the resulting point need not correspond to a word that can appear in the sentence. A replacement has to be selected from discrete possibilities, and its size as a textual change says little by itself about its size as a change in meaning.
There is a search problem even once the edits are restricted to word substitution. Choices about which positions to edit interact with choices about what to put there. An alternative that looks promising on its own can have a different effect after another word is changed. Changing fewer positions generally gives the editor a better chance of preserving the original, but the number of changes cannot settle whether the relevant meaning survived. A single replacement can alter a review’s polarity or the logical relationship between two sentences. The challenge is to spend effort on words that can expose a fragile decision while finding usable alternatives at those positions.
How earlier approaches chose replacements
The authors describe previous methods that modify characters, substitute words, and insert or delete phrases. Each intervention changes what a successful example can reveal. A character-level edit can test sensitivity to the surface form of a word. A word-level edit can test whether a system treats ordinary alternative wording consistently. The paper’s discussion of phrase insertion and deletion emphasizes the difficulty of keeping the result natural and faithful to the original. It also cites manually constructed examples in inference and reading comprehension, where people design changes to expose a particular weakness. Such examples illustrate the value of careful editing, although the paper’s own objective is to generate examples automatically across tasks.
Among automatic word-level methods, one source of candidates was a synonym resource. Work on probability-weighted word saliency is an example the paper places in this tradition. A lexical resource can supply many reasonable alternatives, but its entries are usually attached to words rather than to specific occurrences of those words. The actual sentence determines which sense is in use and whether a particular alternative has the right grammatical and pragmatic fit. A list of candidates gathered in advance leaves those judgments to additional rules or checks.
Another source was proximity in a space of word embeddings, numerical representations of words. The authors discuss systems that use resources such as GloVe and systems that use embeddings adjusted to reflect lexical relationships. A nearby vector gives a candidate some claim to relevance, but the same neighborhood is available when the source word appears in a different context. The paper associates this approach with work including TextBugger and Black-box Generation of Adversarial Text Sequences. The authors’ concern is that relatedness in the embedding space leaves both grammatical fit and the meaning of the edited sentence to be established.
The genetic attack of Alzantot and colleagues uses nearby words as possible edits and adds a language score to assess proposed changes. The scoring stage can screen out poor proposals, but the approach still has to generate candidates and revisit their quality during the search. The paper treats those repeated evaluations as part of the computational cost. Generating Natural Language Adversarial Examples.
TextFooler, another central comparison, combines an embedding-based source of alternatives with checks such as part of speech and sentence-level similarity. A part-of-speech check asks whether a replacement can serve the same grammatical role. A similarity check asks whether the original and edited texts have close representations. They address different risks. Two nouns can refer to very different things, and a text that looks similar overall can have a locally awkward substitution. The authors regard TextFooler as a strong baseline while questioning how much work it takes to propose candidates without context and then check their suitability. TextFooler.
Why BERT has two roles
A masked language model learns to predict text using surrounding words. The authors saw that ability as a way to make context part of the proposal itself. A word can have many broadly related alternatives, yet only some fit the specific sentence. If context informs the original candidate list, the generator can spend more of its effort considering words that already have a reasonable chance of fitting. The paper also highlights the information available in the source word itself. Its identity can guide the search toward the intended subject or sense even when several other words would complete the sentence fluently.
Fine-tuned BERT is also a target. Its score answers a task question such as whether a review is positive. Pretrained BERT’s output answers a lexical question about which tokens are plausible in a particular position. These outputs serve different purposes even when they come from the same family of networks. The division also makes it possible to test the approach on other classifiers. The generator can remain in place while the target changes, provided the target exposes the scores the search uses.
The authors frame the resulting evaluation as black-box because the target’s internal parameters and gradients are outside the search. Here, the box exposes a real-valued score for the correct class. Access to that score makes it possible to notice that a change has weakened the original decision before the winning label changes. This puts scores, the original task label, and the ability to submit altered inputs at the center of the experimental setup.
The method, step by step
Separate the choice of position from the choice of wording
The procedure begins with a labeled example. Consider a review that the classifier initially assigns to the correct sentiment category. The authors first ask how the score for that category changes when a word’s identity is hidden. A large drop makes the word a promising place to look for a small disruptive edit. This inquiry concerns the target classifier and the particular input. A word that ranks high in one review can rank differently in another.
The authors then use the pretrained generator to propose new wording. Here the original text remains visible, including the word that might be replaced. The generator provides alternatives at the positions occupied by words or parts of words. The target classifier determines what happens when a proposed edit is actually made. Until a change causes a wrong prediction, the search can retain a substitute that reduces the original class score and continue with another position.
How BERT-Attack constructs an edited example
The steps in order.
Measure the response to a missing word
The paper represents the input as an ordered sequence of words. This word-level view is useful because the experimental budget and the reported perturbation percentage are about changes to words. The generator later uses a finer representation that may split one word across several positions. At the importance stage, the question is what happens when the classifier sees the input with a particular word replaced by the special mask symbol.
I(wᵢ) = oᵧ(S) − oᵧ(S ∖ wᵢ)
Here, S is the original sequence, wᵢ is its word at position i, and y is the correct class supplied with the example. The function oᵧ gives the target’s logit for that class, a score before conversion to a probability. The expression S ∖ wᵢ means the sequence in which the occurrence at position i has been replaced by [MASK]. The surrounding words stay where they were. The minus sign makes I(wᵢ) the decrease in the correct-class score under that intervention. The score is negative if masking the word increases that logit.
The reference score comes from the original input. Each masked comparison starts again from that same input, so masking one position has no accumulated effect on the measurement at another. Once the scores have been collected, the authors sort the words in descending order and call the resulting list L. They restrict attention to a fraction of the highest-ranked words, denoted by ε in the method description. The idea is to concentrate the search and keep the eventual perturbation small. This budget on positions is conceptually distinct from the budget on proposals at a position.
The score answers a particular question about the target’s response to a missing word. Its appeal is that the question can be asked through the ordinary prediction interface. It does not require estimating how every possible replacement would behave before deciding where to look. The interpretation of the score has a limit, though. It reflects the intervention of replacing an occurrence with [MASK], and that artificial input can have effects beyond suppressing the usual meaning of the word. A high rank is evidence that a position is worth investigating under the paper’s search, instead of a complete explanation of the classifier’s prediction.
Keep the original word visible to the generator
Masking serves the importance stage because the authors want to measure what is lost when the word disappears. At the proposal stage, the original word is part of the information the generator needs. The paper illustrates the distinction with a sentence about liking a cat. A gap at the animal’s position can take a word for a dog just as fluently. Leaving the animal name visible lets the generator condition on that source wording as well as the surrounding sentence. The intended benefit is a candidate list more closely connected to what the input actually says.
This design also changes the cost of generating proposals. The intact sequence can be processed together, yielding predictions at all token positions. A procedure that inserted a separate mask for each requested position would have to present different input sequences to the generator. The authors make particular use of the fact that BERT’s output offers a ranking at each position. Predictions beyond the most likely token can contain useful alternatives even when the intact source strongly favors itself.
P = M(H)
Here, H is the original sequence after BERT’s subword tokenization, and M is the pretrained BERT used to generate alternatives. The symbol P denotes its prediction output for the token positions in H. At each position the search retains the K most highly ranked predictions, with K set as a hyper-parameter. In the algorithm, P also refers to these retained lists, and Pⱼ denotes the list at token position j. The alignment between the input words and H tells the search which list, or which group of lists, belongs to a given word in L.
There is an important distinction between reusing the prediction lists and reusing target scores. The lists come from the original text. The target must still evaluate the trial text with its proposed substitution. As the search keeps edits, the trial text can differ from the original sequence the generator saw. The gain is that the initial lexical proposals are available without rebuilding their context after every candidate. The corresponding assumption is that alternatives generated from the original wording remain useful as the search progresses.
Treat single-token and split words differently
When an input word corresponds to a single token, the search begins with that token’s candidate list. The authors describe filtering with a stop-word resource from NLTK. For sentiment tasks they also use lexical information to exclude antonyms, because a word that makes sense in a context can express the opposite judgment. This is a particularly direct threat to the evaluation. In sentiment classification, replacing a word by its opposite can make the classifier’s new answer legitimate. The additional filter addresses part of the problem even when BERT’s local prediction considers both terms plausible.
A word split across tokens needs a different procedure. A plausible replacement for an initial fragment and a plausible replacement for a later fragment need not form a plausible word together. The authors combine the proposed fragments and reverse the tokenization to obtain possible lexical substitutes. This preserves the word as the unit of the edited text even though the alternatives are proposed at a finer level.
Kᵗ
Here, K is the number of retained predictions available per fragment, and t is the number of fragment positions being combined in the paper’s count. Raising K to the power t gives the number of combinations when each of those positions has K choices. The printed indices for the fragment sequence and the dimensions used in the count are uneven. The role of the exponent is to count the positions that actually contribute choices. The growth with the length of the split word explains why this case calls for a way to reduce the resulting list before trying whole examples on the target.
The authors rank the reconstructed candidates by perplexity, a measure of how readily the generator predicts the combination. Lower perplexity indicates a more plausible combination under the scoring procedure. They use BERT’s masked prediction component for this step and retain the leading combinations for further consideration. The initial lists at all positions come from the same pass over the original text. Scoring combinations of fragments is additional work within the split-word branch. This distinction matters when interpreting the claim that BERT-Attack avoids repeated language scoring of every complete trial sentence.
Use the target’s scores to decide what to keep
At a ranked word, the search attempts replacements from the available filtered list. A change that already produces the wrong class can end the search. If the class remains correct, the authors use changes in the correct-class logit to decide whether a replacement has made progress. A useful change can be carried forward while the search examines another word. This makes it possible for several edits to have a cumulative effect even if none immediately changes the winning class.
argmaxᵧ′ oᵧ′(S′) ≠ Y
Here, S′ is the trial sequence after a proposed replacement, and y′ ranges over the task’s possible classes. For each such class, oᵧ′(S′) is the target’s logit on that trial. The argmax returns the class whose logit is highest. Y is the gold label in the algorithm, and ≠ is the test that the predicted class differs from it. This notation spells out the comparison intended by the paper’s pseudocode, which uses the same score notation for the ranking and the prediction check.
oᵧ(S′) < oᵧ(S_adv)
Here, y again denotes the correct label, S′ is the trial text, and S_adv is the edited text the search has retained so far. The function oᵧ evaluates the target’s score for y, and the less-than sign tests whether the trial has reduced that score relative to the retained state. The comparison can matter while both texts still receive the same predicted class. If the search exhausts its allowed positions without a successful example, the algorithm reports failure.
The word order is established before the replacement search. The candidate lists are also prepared from the original input. Within that structure the search makes local decisions about whether a substitution is useful. It does not examine every possible combination of edits or prove that the returned example uses the fewest possible changes. Its design trades an exhaustive search for a way to exploit two kinds of information that are available at relatively low cost. The classifier identifies sensitivity to a position, and the pretrained generator supplies alternatives appropriate enough to consider.
What is learned and what is supplied
The main procedure uses a pretrained BERT to generate alternatives. The target classifiers have already been trained for their respective tasks before the robustness test begins. The method section does not introduce a separate supervised training stage for a new proposal generator. Instead, the original example supplies the context, the labeled task data supplies the correct class, and the target’s scores guide the search for that example. When the authors later test adversarial training, they generate examples from the training split and use them in an additional fine-tuning stage. That is an experiment with the output of BERT-Attack, distinct from producing the edits in the first place.
The evaluation also uses an automatic similarity measure and describes filtering less similar examples by a threshold. The authors’ efficiency discussion distinguishes BERT-Attack from methods that run an auxiliary language scorer on each trial sentence. The procedure described in the algorithm gives clear roles to proposal generation, candidate filtering, and target evaluation. The paper gives less detail about when the sentence-level threshold is applied relative to those operations. The authors make the implementation available under the name BERT-Attack.
Experiments and results
Tasks, splits, and comparison methods
The evaluation covers review polarity, news classification, and inference between pairs of texts. Yelp provides reviews processed into a polarity task. IMDB uses movie reviews for the same broad kind of prediction, with longer text on average than Yelp. These datasets let the authors ask whether a small number of changes can alter the predicted sentiment of a passage whose opinion is expressed across many words.
The paper also tests AG’s News, where the possible categories are World, Sports, Business, and Science. FAKE is a document classification task built from data from the Kaggle Fake News Challenge. Topic and fake-news classification put different demands on the edited text from polarity prediction. For instance, the replacement of a word used as a topical cue needs to preserve the subject of the article if the original category is to remain appropriate. The same count of word changes can therefore represent quite different interventions across the tasks.
In the inference experiments, the classifier receives a premise and a hypothesis and predicts entailment, neutrality, or contradiction. Entailment means that the hypothesis follows from the premise. Contradiction means that the statements conflict in the reading relevant to the task. A neutral relation leaves the hypothesis open. SNLI supplies labeled examples of these relationships. Stanford Natural Language Inference.
MNLI extends the setting across varied genres, including speech transcripts, fiction, and government material. Its matched evaluation uses domains represented during training, while the mismatched evaluation uses domains outside that matched set. An edit in an inference example is evaluated through the relationship between the sentences. The authors report results for editing the hypothesis and the premise separately. The distinction matters because the two sides differ in length and because a substitution in either sentence can change what the pair implies. Multi-Genre Natural Language Inference.
Following earlier work, the authors describe evaluating on 1k randomly selected test examples per task, using the same splits as the prior comparisons. The genetic attack uses a subset of 50 examples for FAKE and IMDB. The primary targets are BERT systems fine-tuned on the tasks. The authors compare BERT-Attack with TextFooler and the genetic attack, and run additional experiments against targets with other architectures. The smaller genetic-attack subsets matter when reading side-by-side results for those datasets, since the evaluated examples can affect both the measured accuracy and the observed cost.
What each metric measures
Original accuracy records how often the classifier gives the correct answer on clean examples. Attacked accuracy records the same kind of correctness after applying an attack. The paper discusses success rate as the corresponding measure from the attacker’s perspective. The tables frequently express the result as attacked accuracy, so smaller values indicate that a larger share of predictions are wrong in the evaluated condition. Clean accuracy provides context for those values, especially when the targets differ.
Perturbation percentage describes how much of the input changed at the word level. A comparable fraction can mean more substitutions in a long passage than in a short one. A small fraction is evidence of a limited edit at the surface level. Whether it also preserves the correct answer depends on what those words contribute. That is why the paper gives semantic similarity and human judgments their own roles.
The query count describes access to the target, measured per sample. It includes the practical cost of needing target outputs during the experiment. A method can generate candidates quickly and still spend many queries checking them. Runtime is broader because it also reflects work done away from the classifier, such as generating or processing proposals. The two measurements help explain whether an efficiency gain comes from fewer evaluations of the target, from less work around each evaluation, or from both.
The automatic measure of semantic similarity compares the original and edited texts using a sentence encoder. The authors describe a similarity threshold to screen out texts that diverge too far by that measure. The score reflects how close the two texts are in the encoder’s representation. Human judgments complement it in cases where a small local change may matter more to the task than it does to the text’s overall representation. Universal Sentence Encoder.
The strongest comparisons depend on which sentence is edited
The MNLI matched premise comparison shows how several metrics can point in the same direction. Clean accuracy for the fine-tuned BERT target is 85.1%. When the premise is edited, BERT-Attack leaves it at 11.9% accuracy and TextFooler leaves it at 25.3%. BERT-Attack also uses a smaller edit share, 7.9% of words, compared with 26.5% for TextFooler. It takes 44 queries per example in the table, whereas TextFooler takes 152. The reported semantic similarity scores for these premises are 0.68 and 0.65, respectively. Each of those numbers concerns changes to the premise with the hypothesis held fixed.
Attacked accuracy on MNLI matched premises
The classifier retains less accuracy after BERT-Attack edits the premise.
The numbers
| System or setting | accuracy % |
|---|---|
| TextFooler | 25.3 |
| BERT-Attack (this paper) | 11.9 |
For hypotheses in the same matched split, BERT-Attack leaves 7.9% accuracy against TextFooler’s 9.6%. The difference in residual accuracy is less pronounced than in the premise comparison, but the costs still differ. The reported word-change rates are 8.8% and 15.2%, and the query counts are 19 and 78. Automatic similarity favors TextFooler slightly in this condition, at 0.57 compared with 0.55 for BERT-Attack. The results give separate reasons to value an attack. The hardest condition for the classifier, the smallest edit share, and the best measured preservation need not all identify the same method under every setup.
On MNLI mismatched premises, BERT-Attack leaves 13.7% accuracy and TextFooler leaves 22.9%. The word-change rates are 7.1% and 24.7%, and the query counts are 43 and 162. For mismatched hypotheses, the attacked accuracies are 7 and 8.3, respectively, as written in the results table. BERT-Attack uses 24 queries in that condition, compared with 86 for TextFooler. The premise results give the clearer accuracy advantage over TextFooler on both MNLI splits. The hypothesis results also show that a method can attain lower residual accuracy with substantially fewer queries even when the resulting accuracies are fairly close.
SNLI provides a qualification to the overall comparison. With hypotheses edited, BERT-Attack leaves 7.4% accuracy and TextFooler leaves 4.0%. TextFooler is the stronger attack by that metric in this setting. BERT-Attack uses 16 queries per sample there, compared with 60 for TextFooler, and changes 12.4% of words, compared with 18.5%. On SNLI premises, the attacked accuracies go the other way, at 16.1% for BERT-Attack and 20.8% for TextFooler. Results across the two sides make it worthwhile to keep the table’s hypothesis and premise entries distinct. An overall characterization of the paper’s results can otherwise hide a comparison in which the baseline succeeds more frequently or in which the cost of that success differs.
On Yelp, the ablation table also reports the full method’s text-classification result directly. Attacked accuracy is 5.1%, the word-change rate is 4.1%, and automatic similarity is 0.77. The fixed-K IMDB experiment gives attacked accuracy of 11.4% from an original accuracy of 90.9%. The authors interpret the review results as evidence that a small number of lexical changes can strongly affect predictions in relatively long inputs. What the measurements directly establish is that the edits found by the search often succeed. The conclusion that the classifier habitually bases its decision on a few words is an interpretation of that behavior.
Speed and tests on other classifiers
IMDB is the task used in the explicit runtime comparison. The default implementation includes handling for words split into pieces. A variant skips those words. The full system takes 16.0 seconds per sample and the variant takes 14.2. TextFooler takes 42.4 seconds per sample, and the genetic attack takes 2582.0 seconds per sample. The authors characterize their method as roughly 3 times as fast as TextFooler in this comparison. The runtime with split-word handling is the appropriate figure when the added coverage is part of the tested method.
Runtime per IMDB sample by attack method
BERT-Attack takes less time than either baseline, including when split words are eligible for edits.
The numbers
| System or setting | seconds per sample |
|---|---|
| Genetic attack | 2582.0 |
| TextFooler | 42.4 |
| BERT-Attack with split-word handling (this paper) | 16.0 |
| BERT-Attack without split-word handling | 14.2 |
The additional targets put the same proposal mechanism against recurrent classifiers and fine-tuned BERT-large. On Yelp, Word-LSTM has clean accuracy of 96.0 and attacked accuracy of 1.1, with 4.7% of words perturbed. BERT-large on Yelp has clean accuracy of 97.9 and attacked accuracy of 8.2, with 4.1% of words perturbed. On MNLI matched, BERT-large goes from clean accuracy of 86.4 to attacked accuracy of 13.2 in the reported comparison, with 7.4% of words changed. The paper also includes ESIM as an inference target. These runs establish that access to the task scores can support a fresh search against targets outside the main fine-tuned BERT setup. They address a different question from transferring an already edited text between targets.
What the human readers observed
The authors draw human-evaluation samples from IMDB and MNLI and describe selecting 100 examples of original and adversarial material for each task. Three annotators see original and edited texts in a shuffled mixture. They judge grammar on a 1–5 scale, and the evaluation reports mean semantic and grammar ratings. For task predictions, the majority of the annotators determines the human label. In combination, these judgments test readability, preservation of meaning, and the ability to recover the task answer.
On IMDB, human label accuracy is 0.91 for original texts and 0.85 for edited texts. The semantic ratings are 4.1 and 3.9, and grammar ratings are 3.9 and 3.7. The changes in reader judgments are relatively modest in this evaluation. The authors’ qualitative examples include reviews where the overall expression of approval or dislike remains recognizable even though the classifier changes its sentiment prediction.
On MNLI, human accuracy is 0.90 on originals and 0.70 on adversarial examples. The semantic ratings are 3.9 and 3.7, and grammar ratings are 4.0 and 3.6. The authors point to lexical overlap in the original premise and hypothesis as one reason an edit can make the relationship harder to judge. The examples include a change from an existential description of rooms with balconies to a description that attributes balconies to many rooms, while the hypothesis continues to speak about all rooms. The edit is small and readable, yet it touches the quantity the inference concerns. The aggregate human results make clear that preserving broadly similar wording and preserving an easily recognizable task answer can come apart.
What the ablations show
The order of positions affects the outcome
The authors compare their descending importance order with a random order and with an order that puts the least important words first. The experiment uses MNLI matched and changes the order in which positions are visited. The key question is whether the score from masking tells the search where edits will be productive. If any order worked equally well, the extra scoring for importance would have weak support from this comparison.
Attacked accuracy by word order on MNLI matched
Visiting the highest-ranked words first leaves the classifier with the lowest accuracy.
The numbers
| System or setting | accuracy % |
|---|---|
| Random order | 20.2 |
| Least important first | 27.2 |
| Most important first (this paper) | 7.9 |
The importance-first condition also has the smallest fraction of words changed, at 8.8%. The random order uses 12.2%, and the least-important-first order uses 15.0%. The reported similarity scores are 0.68 for the importance order and 0.60 for each of the alternatives. In this experiment the ordering improves the eventual accuracy result while reducing how much of the input the search alters. That combination supports the authors’ practical claim that it is valuable to try sensitive positions early.
The reverse order is especially informative because it uses the same importance signal while giving priority to the positions the signal rates lowest. Its weaker result shows that the direction of the ranking matters. The random order supplies a comparison without that directional preference. Together, they support the use of masking as a search heuristic in the evaluated setting. They leave open whether other measurements of position sensitivity could do better and whether the same positions would be important under a different family of interventions.
The candidate pool controls both coverage and effort
The paper varies K, the number of retained predictions per position. As the pool grows, the authors report a higher attack rate. A wider list can include alternatives that the generator regards as less likely but that still fit well enough and produce a stronger change in the classifier’s output. This experiment tests a different part of the method from word ordering. The ranking determines where the search looks, while K determines how much lexical variation it considers when it gets there.
The authors anticipated that considering more candidates might trade away semantic similarity. They report that similarity as measured by the sentence encoder drops by less than 2% across the candidate-size experiment. That finding concerns the automatic measure in the studied range. A stable aggregate similarity score allows particular substitutions to change meaning, and the authors acknowledge that contextual predictions can include irrelevant words and antonyms. The candidate-pool result therefore provides evidence that the extra options remain useful under the reported evaluation, with human and task-level preservation still separate questions.
A second test compares a fixed K with a confidence threshold that cuts off low-scoring predictions. On IMDB, clean accuracy is 90.9 in both conditions. Attacked accuracy is 11.4 with fixed K and 12.4 with the threshold. The authors report fewer queries with the threshold and interpret that outcome as evidence that some low-scoring proposals can be skipped. The reported direction is a tradeoff. The threshold saves target access and leaves the classifier somewhat more accurate. The paper does not supply clear query totals for that comparison, so the magnitude of the saving cannot be assessed from the reported numbers.
Split words add useful choices
The sub-word ablation compares the full method with a version that skips words split into multiple tokens. On Yelp, the full method leaves 5.1% attacked accuracy, changes 4.1% of words, and has semantic similarity of 0.77. Skipping split words leaves 7.1% attacked accuracy, changes 4.3%, and gives similarity of 0.74. On MNLI, the full condition in this comparison has attacked accuracy of 11.9%, a perturbation rate of 7.9%, and similarity of 0.68. Its counterpart without split-word handling has 14.7% attacked accuracy, 9.3% perturbation, and similarity of 0.63.
The skip condition narrows the set of editable positions. If an influential word is represented by several tokens, the restricted procedure must look elsewhere even when the ranking has identified that word as promising. The results fit the explanation that access to such positions can help the search succeed with fewer changes elsewhere. The comparison tests the split-word branch as a whole. It leaves the contributions of reconstructing combinations and ranking them by perplexity unmeasured as separate design decisions.
The runtime figures supply a complementary observation. The IMDB variant that skips split words is faster than the full system. The effectiveness comparison, meanwhile, reports the benefit of covering split words on Yelp and MNLI. These are slightly different pieces of evidence because the paper measures the time on IMDB and illustrates the accuracy and similarity effects with other tasks. They establish that the branch has a computational cost and that it can improve the quality of the search in the reported settings.
How much context is available
The authors argue that contextual proposals have less to work with in an extremely short sequence. MNLI provides a natural setting for investigating the idea because the premise and the hypothesis are separately editable. For the matched split, the paper reports average lengths of 11 for hypotheses and 21 for premises. For the mismatched split, the corresponding lengths are 12 and 22. The authors favor premises for examples of contextual editing and suggest pairing BERT-Attack with word-level synonym strategies where the input gives the generator little surrounding text.
The main results offer evidence about editing each side of a pair, although they do not isolate context length experimentally. A premise and a hypothesis play different roles in the task. They can differ in wording, in which facts they introduce, and in how the classifier uses their overlap. The larger improvement over TextFooler on MNLI premises is consistent with the authors’ account of richer context. It does not establish that length alone produces the difference. A comparison that varied the amount of context around otherwise equivalent edits would address that narrower question.
Fresh searches, transfer, and adversarial training
For transfer, the authors generate examples against a source classifier, then use those same texts to evaluate a different classifier. This differs from the experiments where every target receives a dedicated search. BERT-base serves as the proposal generator across the transfer comparisons, so a different target can change which suggestions are accepted even when the mechanism proposing them is shared. A successful transfer suggests that the selected changes expose a weakness shared by more than one classifier.
The transfer table uses attacked accuracy to report how the tested classifier performs on material generated against another one. The pattern the authors emphasize is stronger transfer in their inference evaluation and weaker transfer on text classification. This is evidence about the source and destination systems in those runs. When a fresh search succeeds against a recurrent model and against BERT, both systems have exhibited sensitivity to some set of contextual edits. Whether the very same edited text causes both to fail is the additional issue that transfer measures.
The training experiment asks whether the same kind of examples can help a target learn. The authors generate adversarial examples from the MNLI training data, fine-tune with the resulting material, and test on the evaluation data used before. On MNLI matched, original accuracy is 85.1 for the earlier target and 84.6 after adversarial training. Attacked accuracy rises from 7.9 to 23.1, and the attack’s word-change rate rises from 8.8% to 10.5%. Here higher attacked accuracy is favorable for the classifier, since the question has shifted from how effective the attack is to how well the target withstands it.
Taken together, those measures show that the trained target retains close to its earlier clean accuracy and that the reported attack becomes harder. The rise in the amount of editing matters because it shows a cost to finding perturbations as well as a change in the accuracy outcome. The experiment provides evidence for using generated examples as additional training material in this setting. Because the training examples and the evaluation method are connected, it also leaves open how much the benefit would extend to a different kind of perturbation.
Limitations
Limits the authors identify
The authors identify semantic drift as a remaining problem. A generator that predicts a word from its surroundings can favor words that belong to the same topic or that fit the same grammatical slot. Antonyms often meet those conditions. A word can also fit the local sentence while being unrelated to what the author intended at that position. The sentiment-specific antonym filter addresses a recognizable class of errors. The paper’s conclusion still treats better semantic alignment between source and substitute as an open problem for the generator.
The authors also flag extremely short inputs. Context is one of the chief sources of information for choosing alternatives, and very short text offers little evidence for resolving ambiguity or deciding which neighboring words matter. Their suggestion of combining contextual generation with word-level synonym strategies is a proposed response. The paper does not report an experiment demonstrating how well that combination works on short text.
The authors explain that natural language inference poses a special difficulty for human evaluation because the premise and hypothesis often share words. Editing one of those shared cues can make it harder for a reader to assign the original relationship. This difficulty is visible even though the edited examples can remain grammatical. The paper’s own human results consequently support a narrower reading of preservation than the selected qualitative examples might suggest by themselves.
Limits visible in the experimental setup
The test requires access to logits or an equivalent score interface. The importance ranking uses differences between scores, and the incremental search uses score changes even when the predicted class stays the same. An interface that supplies only a hard label offers less information than this procedure uses. The input label is also known in the benchmark setting. The results establish what the experiments achieve given that access and supervision, leaving label-only settings and cases with unknown ground truth outside the evaluation.
Masking is an intervention designed by the experimenter. A large logit change shows that the target responds strongly to the altered sentence, but the mask can create an unusual piece of input as well as removing the identity of the source word. A small response can also occur when several cues reinforce one another, even if the individual word is meaningful to the reading. The ranking ablation establishes the value of the score for selecting positions with this procedure. It supplies limited evidence about how the system represents the original sentence internally.
The search can stop at the first available successful edit and can keep edits that lower the correct-class score as it proceeds. Its proposals and initial importance scores come from the original text. These choices favor practical search cost. They also mean that the perturbation percentages are empirical properties of the edits found by this search. There is no guarantee that a successful example is the closest possible one, or that failure shows that all small meaning-preserving alternatives would leave the classifier’s prediction unchanged.
The automatic similarity threshold adds a useful quality signal, but sentence-level resemblance can survive a change to the truth conditions of an inference pair. A quantified expression can affect entailment even if the rest of the vocabulary is identical. The human results provide an additional check, with a clear decline in MNLI label accuracy alongside fairly close mean semantic ratings. The experiment reports group-level judgments on IMDB and MNLI. It does not establish that every counted success retains its original gold label, and comparable human judgments are absent for the other reported tasks.
The efficiency claims are likewise tied to the experimental conditions. Query counts depend partly on input length and which edits are eligible, while runtime includes the costs of both the target and the proposal machinery. The full runtime comparison concerns IMDB, and the genetic baseline uses smaller subsets in two of the classification settings. Neither the cost of the split-word branch on other task distributions nor timings for other target interfaces can be inferred from that experiment alone. The paper also gives less detail about the placement of the semantic similarity threshold than about the use of BERT to generate proposals. This limits what can be concluded about the runtime contribution of filtering.
Finally, the robustness improvement after training is measured on MNLI matched under the authors’ evaluation, and transfer is tested among a particular set of classifiers. These are separate kinds of evidence. The training experiment shows resistance to the evaluated perturbation procedure after exposure to generated training examples. The transfer experiment shows that some already edited inputs remain effective when the classifier is changed. Neither experiment measures resistance to every meaning-preserving rewrite, robustness to every other attack family, or generalization of the training result across all the paper’s tasks.
What came after
From an individual attack to a reusable evaluation
BERT-Attack is cited by later work that treats adversarial text as part of a larger evaluation or training procedure. TextAttack frames adversarial attacks, data augmentation, and adversarial training as related uses of generated text. That scope connects directly to two roles found in BERT-Attack. An edited input can expose a failure at evaluation time, and edited training examples can give a classifier practice with variations on the original task. The framework’s stated remit is broader than the comparison of one contextual generator with earlier word-substitution attacks. The citation establishes the connection to that line of work, while its title identifies these three uses without specifying which parts of BERT-Attack it adopts. TextAttack.
Contextualized Perturbation for Textual Adversarial Attack takes up the question closest to BERT-Attack’s proposal stage. Given the broad range of changes one could make to a text, the surrounding words can shape which alternatives deserve consideration. This connection is about the definition of a plausible perturbation. It is distinct from the choice to rank positions by a mask-induced score change. The later paper explicitly makes contextualized perturbation its subject, although its citation and title alone leave the details of its relationship to BERT-Attack’s scoring and search undecided. Contextualized Perturbation.
TextFlint places robustness evaluation in a unified multilingual toolkit. Its scope raises a question left open by the English benchmarks in BERT-Attack. A test can have the same purpose across languages while requiring different judgments about what counts as a fluent edit or a stable task label. The later Arabic paper makes the language-specific case more direct by putting BERT-based synonym substitutions at the center of Arabic text classification examples. The Ukrainian paper names the relation between precision and perturbation in a study of synonym attacks. These titles describe distinct extensions of the robustness question. They supply no basis for assuming that the same candidate filters, tokenization behavior, or quantitative results carry over from the original experiments. TextFlint, Arabic Synonym BERT-based Adversarial Examples, Precision vs. Perturbation.
From changes in labels to changes in other kinds of outputs
MiCE addresses explanation through minimal contrastive editing. The connection is the use of a small modification to investigate a decision. In BERT-Attack, a small edit that changes a classification can expose fragility. In the explanatory framing named by MiCE, the contrast between two related texts is itself the means of investigating a prediction. The two purposes make different demands on interpretation. A change that is revealing as a contrast can raise the question of whether it ought to affect the task, whereas an adversarial classification example is informative precisely when the answer should survive. MiCE.
Work on textual interfaces takes the robustness question beyond a fixed classification label. The study of text-to-SQL robustness names synonym substitution as the intervention and text-to-SQL as the setting. A substitution there raises a question about whether alternative wording still leads to the intended query. PromptRobust focuses on adversarial prompts in evaluations of large language models. A changed prompt makes the wording of the instruction part of the robustness test. GSM-Plus puts the evaluation in mathematical problem solving, where the system has to produce a solution. The citation links and titles establish the scope of these later evaluations. They do not establish that each one uses the masking ranker, intact-input BERT proposals, or the same notion of a successful edit. Robustness of Text-to-SQL Models against Synonym Substitution, PromptRobust, GSM-Plus.
A later robustness survey explicitly brings measurement and improvement together, the same broad pairing illustrated by BERT-Attack’s attack evaluations and its adversarial training experiment. Across the citing works, the protected behavior varies with the task, from retaining a sentiment label to interpreting an instruction or solving a problem. The common question is which input changes should leave that behavior stable. BERT-Attack supplies a concrete answer for its experiments by searching for locally plausible word changes and then measuring classifier accuracy, edit size, and preservation separately. The later titles show how widely the question was taken up, while the evidence for each answer remains specific to that work’s task and evaluation. Measure and Improve Robustness in NLP Models.
Institutions
Fields, topics and concepts
Shelves 4The field of science this work belongs to (OpenAlex fields).Computer Science · 19,503 worksArtificial Intelligence · 18,805 worksArts and Humanities · 17,959 worksLanguage and Linguistics · 17,789 works
Appears in
Mentioned in articles aboutShanghai
Cite
Cite as Linyang Li, Ruotian Ma, Qipeng Guo, Xiangyang Xue and Xipeng Qiu. 2020. BERT-ATTACK: Adversarial Attack Against BERT Using BERT. Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP).
@inproceedings{li2020bert,
title = {{BERT-ATTACK: Adversarial Attack Against BERT Using BERT}},
author = {Linyang Li, Ruotian Ma, Qipeng Guo, Xiangyang Xue and Xipeng Qiu},
booktitle = {Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)},
year = {2020},
doi = {10.18653/v1/2020.emnlp-main.500},
url = {https://doi.org/10.18653/v1/2020.emnlp-main.500}
}References
- Moustafa Alzantot, Yash Sharma, Ahmed Elgohary, Bo-Jhang Ho, Mani B. Srivastava, and Kai-Wei Chang. 2018. Generating natural language adversarial examples. CoRR, abs/1804.07998.
- Samuel R Bowman, Gabor Angeli, Christopher Potts, and Christopher D Manning. 2015. A large annotated corpus for learning natural language inference. arXiv preprint arXiv:1508.05326.
- Daniel Cer, Yinfei Yang, Sheng-yi Kong, Nan Hua, Nicole Limtiaco, Rhomni St John, Noah Constant, Mario Guajardo-Cespedes, Steve Yuan, Chris Tar, et al. 2018. Universal sentence encoder. arXiv preprint arXiv:1803.11175.
- Anirban Chakraborty, Manaar Alam, Vishal Dey, Anupam Chattopadhyay, and Debdeep Mukhopadhyay. 2018. Adversarial attacks and defences: A survey. arXiv preprint arXiv:1810.00069. — arXiv:1810.00069 OpenAlex ↗ · Scholar ↗
- Jacob Devlin, Ming-Wei Chang, Kenton Lee, and Kristina Toutanova. 2018. BERT: pre-training of deep bidirectional transformers for language understanding. CoRR, abs/1810.04805.
- Ji Gao, Jack Lanchantin, Mary Lou Soffa, and Yanjun Qi. 2018. Black-box generation of adversarial text sequences to evade deep learning classifiers. In 2018 IEEE Security and Privacy Workshops (SPW), pages 50–56.
- Max Glockner, Vered Shwartz, and Yoav Goldberg. 2018. Breaking nli systems with sentences that require simple lexical inferences. arXiv preprint arXiv:1805.02266.
- Ian J Goodfellow, Jonathon Shlens, and Christian Szegedy. 2014. Explaining and harnessing adversarial examples. arXiv preprint arXiv:1412.6572.
- Robin Jia and Percy Liang. 2017. Adversarial examples for evaluating reading comprehension systems. arXiv preprint arXiv:1707.07328.
- Di Jin, Zhijing Jin, Joey Tianyi Zhou, and Peter Szolovits. 2019. Is BERT really robust? natural language attack on text classification and entailment. CoRR, abs/1907.11932.
- Alexey Kurakin, Ian Goodfellow, and Samy Bengio. 2016. Adversarial examples in the physical world. arXiv preprint arXiv:1607.02533. — arXiv:1607.02533 OpenAlex ↗ · Scholar ↗
- Qi Lei, Lingfei Wu, Pin-Yu Chen, Alexandros G Dimakis, Inderjit S Dhillon, and Michael Witbrock. 2019. Discrete adversarial attacks and submodular optimization with applications to text classification. Systems and Machine Learning (SysML). OpenAlex ↗ · Scholar ↗
- Jinfeng Li, Shouling Ji, Tianyu Du, Bo Li, and Ting Wang. 2018. Textbugger: Generating adversarial text against real-world applications. arXiv preprint arXiv:1812.05271.
- Bin Liang, Hongcheng Li, Miaoqiang Su, Pan Bian, Xirong Li, and Wenchang Shi. 2017. Deep text classification can be fooled. arXiv preprint arXiv:1704.08006. — arXiv:1704.08006 OpenAlex ↗ · Scholar ↗
- Takeru Miyato, Shin ichi Maeda, Masanori Koyama, and Shin Ishii. 2017. Virtual adversarial training: A regularization method for supervised and semi-supervised learning. volume 41, pages 1979–1993. OpenAlex ↗ · Scholar ↗
- Danish Pruthi, Bhuwan Dhingra, and Zachary C Lipton. 2019. Combating adversarial misspellings with robust word recognition. arXiv preprint arXiv:1905.11268.
- Shuhuai Ren, Yihe Deng, Kun He, and Wanxiang Che. 2019. Generating natural language adversarial examples through probability weighted word saliency. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 1085–1097.
- Eric Wallace, Shi Feng, Nikhil Kandpal, Matt Gardner, and Sameer Singh. 2019. Universal adversarial triggers for attacking and analyzing NLP. Empirical Methods in Natural Language Processing. OpenAlex ↗ · Scholar ↗
- Adina Williams, Nikita Nangia, and Samuel Bowman. 2018. A broad-coverage challenge corpus for sentence understanding through inference. In Proceedings of the Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 1112–1122.
- Puyudi Yang, Jianbo Chen, Cho-Jui Hsieh, Jane-Ling Wang, and Michael I Jordan. 2018. Greedy attack and gumbel attack: Generating adversarial examples for discrete data. arXiv preprint arXiv:1805.12316. — arXiv:1805.12316 OpenAlex ↗ · Scholar ↗
- Yuan Zang, Fanchao Qi, Chenghao Yang, Zhiyuan Liu, Meng Zhang, Qun Liu, and Maosong Sun. 2020. Word-level textual adversarial attacking as combinatorial optimization. In Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics, pages 6066–6080.
- Xiang Zhang, Junbo Zhao, and Yann LeCun. 2015. Character-level convolutional networks for text classification. In Advances in neural information processing systems, pages 649–657.
- Wangchunshu Zhou, Tao Ge, Ke Xu, Furu Wei, and Ming Zhou. 2019. BERT-based lexical substitution. In Proceedings of the 57th Annual Meeting of the Association for Computational Linguistics, pages 3368–3373, Florence, Italy. Association for Computational Linguistics. OpenAlex ↗ · Scholar ↗
- Nikola Mrkšić, Diarmuid O Séaghdha, Blaise Thomson, Milica Gašić, Lina Rojas-Barahona, Pei-Hao Su, David Vandyke, Tsung-Hsien Wen, and Steve Young. 2016. Counter-fitting word vectors to linguistic constraints. arXiv preprint arXiv:1603.00892. OpenAlex ↗ · Scholar ↗
- Anh Nguyen, Jason Yosinski, and Jeff Clune. 2015. Deep neural networks are easily fooled: High confidence predictions for unrecognizable images. In Proceedings of the IEEE conference on computer vision and pattern recognition, pages 427–436. OpenAlex ↗ · Scholar ↗
- Jeffrey Pennington, Richard Socher, and Christopher Manning. 2014. Glove: Global vectors for word representation. In Proceedings of the conference on empirical methods in natural language processing, pages 1532–1543.
This page in Markdown https://md.research.elamur.ai/free/en/papers/li-2020-bert-attack-adversarial-attack-against/