Defending Pre-trained Language Models from Adversarial Word Substitution Without Performance Sacrifice
Paper · 2021 · Rongzhou Bao, Jiayi Wang and Hai Zhao
Summary
A sentiment classifier can change its verdict on a review after a few words are replaced with near synonyms, even when a reader would still give the review the same label. Spelling and grammar checks offer little help when the replacements are valid words and the edited sentence reads naturally. Bao, Wang and Zhao study how to protect classifiers built with language pretraining against this kind of deliberate substitution while keeping their accuracy on ordinary text. They call their defense Anomaly Detection with Frequency-Aware Randomization, or ADFAR.
ADFAR gives a shared text encoder two jobs. One classification head predicts the label required by the task, such as the sentiment of a review. The other judges whether the input resembles an adversarial example. When the detector judges an input ordinary, the system uses the task prediction from that pass. When the detector flags an input, ADFAR makes a randomized rewrite and classifies the resulting text. The rewrite gives priority to rare words as candidates for replacement and favors common near synonyms as alternatives. During training, the task head learns from original, adversarial and randomized text, while the detector learns to distinguish original examples from adversarial ones before the rewrite.
In the main BERT comparison with TextFooler, ADFAR raises test accuracy after attack from 16.9 to 66.0 on MR movie reviews, from 39.8 to 75.6 on SST2 sentiment, from 12.4 to 89.2 on IMDB reviews, and from 11.3 to 67.8 on MNLI sentence pairs. On the same datasets, clean test accuracy rises on MR and IMDB and falls on SST2 and MNLI. ADFAR ties SAFER on attacked SST2 and leads the other defenses in the comparison on the remaining attacked test sets. On MR, it takes 18.1ms per example on the reported hardware, compared with 15.7ms for plain BERT, 27.6ms for SAFER and 38.9ms for DISP.
The ablations show why the detector matters. Rewriting every input yields stronger attacked accuracy than the complete system on the two datasets used for that comparison. It also reduces clean accuracy. Adding the detector recovers clean accuracy while giving up some of the gain under attack. Further tests show improvements with other word-substitution procedures and other encoders. The evidence supports a practical tradeoff for the conditions tested. The quality of the routing decision and the kinds of substitutions seen in evaluation determine how far the result carries.
Deep dive: Defending Pre-trained Language Models from Adversarial Word Substitution Without Performance Sacrifice
ADFAR detects suspicious word substitutions and selectively rewrites text to improve classification accuracy under attack. · about 35 minutes to read
The problem and its context
A small edit can change the classification
A task label can be stable even when the words used to convey it change. A movie review may retain its positive or negative judgment when a writer trades one adjective for a near synonym. A pair of sentences may retain the same semantic relationship after a similar edit. The paper studies cases where an edit of this kind changes the classifier's decision in spite of the intention to preserve the label. That gap between what the text means for the task and how the classifier responds to it creates an opportunity for adversarial word substitution.
In the paper's framing, an adversarial example is an intentionally modified input that induces an erroneous prediction. The word intentionally distinguishes the construction of the example from an ordinary revision. The requirement that the edit preserve the relevant meaning distinguishes a successful adversarial example from a new input that genuinely deserves a different label. A change in a classifier's answer can be entirely appropriate if the replacement alters the sentiment or the relationship between two sentences. The challenge is to obtain a wrong change in the decision from an edit that a reader would regard as preserving the task label.
The authors situate word substitution among several kinds of textual manipulation. Earlier work considered misspellings, edits that insert or remove phrases, and paraphrases that change the form of a sentence more broadly. Misspellings can sometimes be handled by robust word recognition. The synonym substitutions studied here can pass that kind of check because they can be well formed at the level of both spelling and grammar. The resulting defense problem is closer to recognizing an unusual lexical choice in context than correcting an invalid string. Robust word recognition and syntactically controlled paraphrasing illustrate two of the neighboring problems the authors discuss.
This distinction also helps explain why a defense can itself harm accuracy. Rewriting an ordinary review changes evidence available to the classifier. A close lexical neighbor can carry a different shade of approval, intensity, or register. Even when a person would retain the original label, the classifier may rely on the original expression. An intervention designed to disrupt deliberate edits is therefore also an intervention on useful input. The authors treat the preservation of ordinary classification as a design constraint alongside accuracy under attack.
Why synonym substitutions are hard to handle
The paper describes earlier substitution procedures as making two decisions. They identify words whose replacement might affect the classifier and choose alternatives intended to preserve the meaning. Several cited approaches use heuristics informed by the target classifier's predictions. This makes the distribution of edits partly a property of the classifier being evaluated. A defense exposed to a fixed set of examples during training can later face examples chosen in response to its own behavior. The main evaluation procedure in the paper comes from the study that introduced TextFooler.
A replacement procedure also needs a source of plausible alternatives. The cited work includes vector representations that let a system rank words by similarity and approaches that use contextual predictions to find substitutions that read naturally. These methods make different choices about what counts as a plausible neighbor. Similarity between word vectors offers a way to compare vocabulary items, while a contextual prediction can use the particular sentence in which a word occurs. Both address a central difficulty of textual robustness. The set of edits worth considering depends on language and meaning, and plausible alternatives can have different implications in different sentences. GloVe is among the vector resources the paper mentions, and BAE is among the approaches that use contextual predictions.
The distinction between a plausible replacement and a label-preserving replacement matters on both sides of the experiment. Attack examples are intended to preserve the correct class so that a changed decision counts as an error. Defensive rewrites are also intended to preserve that class so that reclassification remains useful. Neither intention follows automatically from lexical similarity. This leaves an empirical question for the paper. Can a rewrite procedure disturb the particular word choices associated with the attack frequently enough to help, while introducing sufficiently few damaging edits of its own?
What earlier defenses offered
Adversarial training addresses the problem by including modified examples in the data used to train the classifier. A classifier that sees both an original example and a deliberately edited version can learn to associate a wider range of expressions with the same label. The authors describe a limitation of that approach on its own. Training examples form a fixed collection, whereas the heuristic procedures used in evaluation can choose their substitutions in response to the target. Exposure to known examples can improve the classifier's response without covering all the inputs that a later procedure may produce.
Another line of work tries to establish robustness for a specified set of possible edits. The paper discusses interval bound propagation, which bounds the effect of permitted perturbations so a worst-case claim can be made within that set. According to the authors, the methods they discuss impose strong restrictions on the allowed substitutions and depend on architectural assumptions that make adaptation to pretrained encoders difficult. The important distinction for reading the paper is between a guarantee over a defined set of inputs and an accuracy measurement obtained from specific evaluation procedures. The cited work on certified robustness to adversarial word substitutions belongs to the former line.
The authors select DISP and SAFER as their main defense baselines because both can be applied to the kind of classifier they evaluate. DISP identifies suspicious words and attempts to recover the original terms. This gives the defense a location and a proposed repair, with separate pretrained components carrying out those jobs. SAFER uses randomized synonym replacement to form multiple versions of an input and averages the classifier's outputs for those versions. Its method also supplies a robustness guarantee under its smoothing setup. These baselines therefore put computational effort in different places. DISP spends it on locating and restoring specific words. SAFER spends it on evaluating a collection of rewritten inputs.
The randomization idea came with a problem specific to text. The paper points to earlier defensive randomization in computer vision and explains that discrete words cannot be treated like continuously varying image values. Replacing a word entails selecting a vocabulary item with its own meaning, and the difference between two candidates cannot be judged by the size of a numerical change alone. SAFER showed how random synonym replacement could be used to smooth a text classifier. ADFAR takes random substitution in a different direction by bounding its use through a learned decision about each input and by biasing the choice of words and replacements with frequency.
The authors draw the frequency idea from earlier work reporting that adversarial substitutions often exchange a word for a less common synonym and that classifiers tend to be more robust to frequent words. This observation supplies a direction for rewriting. A rare word becomes a candidate for change, and a common near synonym becomes an attractive replacement. It supplies a cue about distributions across examples. A legitimate review can contain rare words, and a deliberate substitution can involve familiar ones. The paper's architecture addresses this mismatch by assigning the decision to intervene to a contextual detector and using frequency to guide the intervention itself.
The method, step by step
Follow an input through the defense
ADFAR is built around text classification, in which a system assigns a label to a piece of text or, in the inference task studied here, to a pair of texts. It starts from a pretrained encoder. The encoder turns the input into contextual vectors, which represent tokens in relation to the surrounding text. A task head reads an aggregate vector and predicts a class, such as positive or negative sentiment. The authors add a detection head that reads the same vector and predicts whether the input looks like an adversarial example.
The first pass therefore produces two answers about the original input. The task answer addresses what the text says for the downstream task. The detection answer addresses whether the input resembles the adversarial text used in training. A prediction of negative sentiment and a prediction that the review is ordinary are compatible. So are negative sentiment and a prediction that the review has been attacked. The detector changes how ADFAR reaches the final task decision, while the task head still supplies that decision.
If the detector judges the input ordinary, the first task prediction becomes the final one. If it judges the input adversarial, the defense goes back to the original text and makes a randomized version. It runs that version through the same encoder and takes the new task prediction as final. ADFAR uses the second task output directly on this branch. The original prediction serves the branch that accepts the input as ordinary.
How ADFAR classifies an input
The steps in order.
The placement of the detector accounts for much of the architecture's simplicity. It needs a representation of the whole input, already available to the task classifier. It can issue its decision without identifying individual altered words. That is enough for routing because the rewrite procedure makes its own selection of words. A detector trained to answer whether a review looks suspicious is therefore useful even when it cannot explain which part of the review caused that judgment.
There are two decisions about suspiciousness in this pipeline, with different inputs and outputs. At the input level the learned head looks at a contextual representation and decides whether a rewrite is warranted. Within the rewrite, a dictionary count helps choose words to consider. Low frequency at the word level and a positive detection at the text level are distinct events. The method would behave differently if any rare word automatically sent an input to the rewrite branch.
Choose the words to consider
The rewrite begins with an unchanged copy of the input. It looks up word frequencies in the dictionary from the FrequencyWords repository. Words below a chosen threshold receive priority for substitution. If the rare-word candidates leave room under the intended substitution budget, the method fills the available places by drawing other words at random. It then filters stop words out of the candidate set. The budget is therefore best read as a target for the initial selection. Filtering can remove selected words before any replacement is made.
The method records the input and initializes its randomized copy as follows.
X = {w₁, w₂, …, wₙ}
Here X is the input sentence and wᵢ denotes its word at position i. The subscripts 1 and n mark the beginning and end of the indexed words, n is the sentence length, and the ellipsis stands for the intervening words. Braces follow the paper's presentation, with the indices retaining the ordering needed for replacement.
Xᵣₐₙ𝒹 ← X
Xᵣₐₙ𝒹 is the working text in which the replacements will be made. X is the original input, and the left arrow means that the working text starts as a copy of it.
nᵣₐᵣₑ = |Wᵣₐᵣₑ|
Wᵣₐᵣₑ is the collection of candidate words whose dictionary frequency is below the threshold fₜₕᵣₑₛ. The vertical bars give its size, and nᵣₐᵣₑ is that count.
|Wᵣₐₙ𝒹| = n × r − nᵣₐᵣₑ
Wᵣₐₙ𝒹 is the collection drawn from words outside Wᵣₐᵣₑ. Its intended size is the sentence length n multiplied by the target substitution proportion r, minus the count of rare candidates nᵣₐᵣₑ. The vertical bars again denote the size of the collection.
Wₛᵤᵦ ← Wᵣₐᵣₑ ∪ Wᵣₐₙ𝒹
Wₛᵤᵦ is the initial collection of substitution candidates. The left arrow assigns it the union, written ∪, of the rare candidates Wᵣₐᵣₑ and the randomly selected candidates Wᵣₐₙ𝒹. The paper gives the intended size of this collection before stop-word filtering.
|Wₛᵤᵦ| = n × r
The vertical bars count the candidates in Wₛᵤᵦ. The sentence length n and the target proportion r determine the intended count. The description leaves the rounding convention implicit and gives no explicit rule for the case where the rare candidates already exceed the target count.
This selection rule combines directed and undirected changes. The frequency cue concentrates effort on the phenomenon highlighted in the introduction. The random draw gives the rewrite scope to alter other words, including in an input with few rare candidates. On its own, the rule identifies words that could be edited. The choice of replacement involves a separate comparison among vocabulary entries.
Find a close, common replacement
ADFAR uses word embeddings designed to help identify synonyms. An embedding represents a word as a vector, giving the procedure quantities it can compare across vocabulary items. The paper uses cosine similarity, which measures alignment between vectors. For a candidate word, the procedure compares its embedding with the embeddings of vocabulary words and ranks those words by similarity. This first ranking is intended to keep the replacement close in meaning.
CosSim(Emb(wᵢ), Emb(w))
CosSim is the cosine-similarity operation. Emb maps a word to its embedding, wᵢ is the selected word at input position i, and w is a word in the embedding vocabulary. The arguments are the two vectors being compared. A higher score places the vocabulary item closer to the input word in the similarity ranking.
The paper calls the first shortlist S. It contains the top nₛ items by similarity. From S, the procedure forms a second shortlist, Sբᵣₑᵩ in the pseudocode's frequency notation, containing the nբ most frequent entries. In the reported setup the similarity shortlist has nₛ = 20, and the frequency shortlist has nբ = 10. The order of the criteria matters. A word earns consideration through similarity before its frequency can make it a preferred alternative.
The prose description presents the random replacement as a draw from the selected close, high-frequency alternatives. The pseudocode constructs the frequency-filtered shortlist but names the initial shortlist in the final draw. The two readings give different sampling pools. The intended frequency-aware procedure follows the prose description, and the paper includes an experiment specifically comparing frequency filtering in shortlist construction. The report leaves the discrepancy between that description and the final pseudocode line unresolved.
The paper writes the replacement as an update to the working copy.
Xᵣₐₙ𝒹 ← Replace(Xᵣₐₙ𝒹, wᵢ, wₛ)
Replace substitutes the sampled word wₛ for the selected occurrence wᵢ in the working text Xᵣₐₙ𝒹. The left arrow assigns the updated text back to the working copy. After the selected replacements have been processed, this copy is the randomized input.
The authors set the dictionary threshold fₜₕᵣₑₛ to 200. By their count, 5.5k out of 50k words in that dictionary have frequencies below the threshold. This is a count of dictionary entries classified as rare. The prevalence of those entries in reviews or sentence pairs can differ from their share of the vocabulary. The threshold and the substitution ratio therefore play different roles. The threshold determines which words receive priority, and the ratio determines how much of an input is eligible for initial selection.
During training the substitution ratio is 25%. At inference it is 30%. The authors choose the lower value for training to limit noise in the augmented examples. In the inference branch, the higher value makes the rewrite more extensive once the detector has indicated that intervention is warranted. The shortlist construction is intended to work the same way in both settings. An encoder that learns to classify training rewrites is thus exposed to the same type of edits it may see in the flagged branch, at a different target edit rate.
Construct the training data
ADFAR starts with the original labeled training examples. It uses a heuristic word-substitution procedure to produce adversarial examples from them. The reported training uses TextFooler. The authors combine the original and adversarial examples into what they call the adversarial training set. This collection already contains both classes needed for detection, with original text supplying ordinary examples and the generated text supplying adversarial examples.
The authors then apply frequency-aware randomization to that combined collection. Accordingly, randomized examples can descend from original inputs as well as adversarial ones. The resulting copies are added to the first collection. This gives the task classifier examples of the input conditions it must handle. It sees ordinary text, the output of deliberate substitution, and text that has passed through the defense's rewrite. The paper draws on adversarial training for the first expansion and on data augmentation for text classification for the second.
The two heads use different portions of this data. The task head trains on the full collection, including the randomized copies. Its supervision concerns the original task label across these variations. The detection head trains on the collection before randomization, where its target records whether an input is original or adversarial. That division follows the order of decisions at inference. The detector sees the text before any intervention, while the task head may be asked to predict from either branch.
It helps to follow an original review and its edited counterpart through the two objectives. For sentiment classification, the adversarial counterpart is meant to carry the same review label as the original. Deliberate edits produced the counterpart, so the two examples carry different labels for detection. A randomized copy is useful for the sentiment objective because the task head may later need to read such a rewrite. The detection objective concerns the original and adversarial examples at the point where the decision to rewrite would be made. Training on different versions of the data gives each head supervision appropriate to its input.
This is also why adversarial training and rewrite augmentation are distinct parts of the design. The first exposes the task head to the substitutions that create the problem. The second exposes it to the text that the defense itself creates. A system trained only on the first collection has experience with deliberate substitutes, but the full ADFAR task head additionally learns from its own type of randomized preprocessing. Because the changes are sampled, the training examples instantiate the rewrite procedure without defining a guaranteed equivalent form for each sentence.
Share the encoder and train the two heads
The paper uses pretrained contextual encoders and adapts them to the two objectives through fine-tuning. The encoder uses self-attention to build contextual representations. Self-attention lets an input position draw information from other positions in the sequence, so the vector at that position depends on the surrounding text. This matters for the detection head because it receives evidence from the whole sequence, including combinations of words that could look different from their individual dictionary frequencies. The architecture relies on transformer attention.
{h₀, …, hₘ}
h₀ through hₘ are the encoder's contextual vectors. The subscripts index them, with 0 marking the aggregate representation and m marking the final indexed position. The dots stand for intervening vectors. The paper places the aggregate vector in a real-valued space of width H.
h₀ ∈ ℝᴴ
h₀ is the vector read by both heads. The membership symbol ∈ places it in ℝᴴ, the space of vectors with H real-valued coordinates. H is the width of that representation.
Each head applies dropout, a linear transformation with a bias, and a softmax. Dropout is the training operation that suppresses sampled parts of a representation. The linear transformation produces scores for the classes, and softmax turns those scores into probabilities across the available classes. The heads use different weights, so the shared representation can support different decisions. The probability notation below uses p for predictions and t for targets throughout, since the paper's displayed probability and loss equations use the marks on y in inconsistent roles.
p꜀(· | X) = softmax(W꜀ · dropout(h₀) + b꜀)
p꜀(· | X) is the distribution over task classes for input X. The dot in its argument marks the possible classes, and the vertical bar means the probabilities are conditional on X. The subscript c identifies the classification head. W꜀ is its weight matrix, the centered dot on the right denotes multiplication by that matrix, and b꜀ is its bias vector. dropout(h₀) is the aggregate representation after dropout, and softmax converts the resulting class scores to probabilities.
p𝒹(· | X) = softmax(W𝒹 · dropout(h₀) + b𝒹)
p𝒹(· | X) is the distribution over the detection classes for input X. The dot in the argument ranges over those classes and the vertical bar again indicates conditioning on the input. The subscript d identifies detection. W𝒹 and b𝒹 are the detector's own weight matrix and bias vector. The dot between W𝒹 and dropout(h₀) denotes matrix multiplication. h₀, dropout and softmax have the same roles as for the task head. The paper encodes an adversarial example as class 1 and an ordinary example as class 0.
The paper describes the objectives as cross-entropy losses. Cross-entropy penalizes a head for assigning low probability to the target class. Its displayed expressions have the binary form, which fits the detection label and the binary sentiment tasks. Read the task expression as the paper's illustration of that objective. The experimental report also includes MNLI, for which the task head is described more generally through its softmax over task classes.
loss꜀ = −[t꜀ × log(p꜀) + (1 − t꜀) × log(1 − p꜀)]
loss꜀ is the task classification loss in binary form. t꜀ is the target indicator for the positive class and p꜀ is the probability assigned to that class by the task head. The corresponding negative-class indicator and probability are 1 − t꜀ and 1 − p꜀. log is the logarithm, × is multiplication, and the leading minus sign makes the expression a penalty. The brackets enclose the terms for the two classes.
loss𝒹 = −[t𝒹 × log(p𝒹) + (1 − t𝒹) × log(1 − p𝒹)]
loss𝒹 is the detection loss. t𝒹 is the attack-status target and p𝒹 is the predicted probability of the adversarial class. The complements with 1 give the ordinary-class indicator and probability. As in the task loss, log denotes a logarithm, × denotes multiplication, and the minus sign turns the bracketed expression into a penalty.
Loss = loss꜀ + loss𝒹
Loss is the combined objective. loss꜀ is the cross-entropy for the classification head, loss𝒹 is the cross-entropy for the detection head, and the plus sign adds them with no separate weighting factor in the displayed objective. Their training data have the different scopes described above.
The practical effect of sharing is that both objectives can shape the representation used on the first pass. The backbone must support the task decision and carry enough information for the detector to distinguish the two kinds of input it sees during training. At inference, the flagged branch uses this same backbone with a different text. The paper reports a PyTorch implementation, with AdamW as the optimizer, a learning rate of 3e-5, a batch size of 16 and 5 training epochs. The authors release the ADFAR code through the LilyNLP repository.
Experiments and results
Tasks, test conditions and comparisons
The sentiment experiments span several lengths of movie-review text. MR is a sentence-level binary classification task. The paper uses 90% of MR for training and 10% for testing, following the TextFooler setup. The dataset statistics give 9K training examples, 1K test examples and an average length of 20 words. The movie-review data come from the work cited on sentiment categorization and rating scales.
SST2 uses phrase-level binary sentiment labels. The dataset statistics give 67K training examples, 1.8K test examples and an average length of 20 words. This setting ties the task to sentiment judgments at a finer textual scale than the document-level experiment. The cited dataset work is the Sentiment Treebank.
IMDB uses document-level movie reviews with binary sentiment labels. The paper lists 25K examples in training and 25K in testing, with an average length of 215 words. The input can therefore contain much more text than the average MR or SST2 example. The cited source is the study on word vectors for sentiment analysis.
MNLI extends the evaluation to natural language inference. Here the classifier assigns a relationship to a pair of sentences based on their meanings. This tests whether the defense helps when a decision depends on a relation between texts as opposed to the overall sentiment of a single review. The benchmark covers genres such as transcribed speech, popular fiction and government reports. The paper's dataset statistics list 433K training examples and 10K test examples for MNLI.
The authors report two task metrics. Original accuracy is the percentage of ordinary test inputs whose task labels are predicted correctly. After-attack accuracy is the percentage classified correctly under the adversarial word-substitution evaluation. Higher values are desirable for both. The original measure includes whatever the complete defense does to ordinary inputs, including rerouting any that the detector flags. The after-attack measure describes the final task outcome. It is distinct from the fraction of adversarial inputs identified by the detector.
The main comparison uses BERT BASE for the underlying encoder and TextFooler for the attack. The baselines include plain BERT, BERT with adversarial training, and the DISP and SAFER defenses built around BERT. Plain BERT indicates how the encoder performs without a substitution defense. Adversarial training tests the effect of exposing the classifier to edited examples. DISP and SAFER represent the more elaborate prior approaches described above. The paper uses their published implementations with modifications required for the evaluation under heuristic attacks. It averages the main accuracy results over five runs because randomization can cause variation between runs.
Results with TextFooler
On the MR test set, plain BERT has original accuracy of 86.2. Adversarial training, DISP and SAFER record original accuracy of 85.6, 82.0 and 79.0, respectively. ADFAR records 86.6. The post-attack comparison is especially clear on this dataset. All the defenses improve on plain BERT, and ADFAR has the highest reported accuracy.
BERT defenses on the MR test set under TextFooler
ADFAR retains the highest classification accuracy after attack.
The numbers
| System or setting | accuracy % |
|---|---|
| BERT | 16.9 |
| BERT with adversarial training | 34.6 |
| BERT with DISP | 42.2 |
| BERT with SAFER | 55.4 |
| BERT with ADFAR (this paper) | 66.0 |
The MR comparison gives an example of the problem that motivated the detector. A method can recover more correct predictions in the attacked test condition while giving up some correct predictions in the ordinary test condition. The earlier defense results show that tradeoff on MR. In this comparison, ADFAR leads the after-attack column and has slightly higher original accuracy than plain BERT. The paper's ablations investigate whether the filtering decision helps explain that pairing.
On SST2, clean test accuracy is 93.1 for BERT and 92.4 for ADFAR in the main comparison. BERT with adversarial training gives 92.6, DISP gives 91.6 and SAFER gives 91.3. Under TextFooler, plain BERT records 39.8 after-attack accuracy, adversarial training records 48.8, and DISP records 70.4. SAFER and ADFAR both reach 75.6. The tie matters for interpreting the paper's headline claim. ADFAR matches the strongest baseline on the attacked split in this setting and has the higher original accuracy of the tied defenses.
On IMDB, original test accuracy is 92.4 for BERT and 92.8 for ADFAR. Adversarial training records 92.2 on ordinary inputs, DISP 91.7 and SAFER 91.3. Under TextFooler, the corresponding after-attack results are 12.4 for plain BERT, 34.2 for adversarial training, 82.0 for DISP, 88.1 for SAFER and 89.2 for ADFAR. IMDB is the longest-input sentiment dataset in the paper. The ADFAR result establishes an improvement for that document-level evaluation alongside the improvements on shorter text. It is also a setting where the best earlier defenses already recover much of the attacked accuracy.
MNLI presents a different balance. Plain BERT has original test accuracy of 84.0. ADFAR reaches 82.6, adversarial training 82.3, SAFER 82.1 and DISP 76.3. ADFAR leads the tested defenses on ordinary MNLI inputs, while plain BERT leads the full set of systems on that metric. Under TextFooler the ranking changes, with ADFAR recording the highest after-attack score.
BERT defenses on the MNLI test set under TextFooler
ADFAR has the highest after-attack accuracy on the sentence-pair task.
The numbers
| System or setting | accuracy % |
|---|---|
| BERT | 11.3 |
| BERT with adversarial training | 33.4 |
| BERT with DISP | 35.1 |
| BERT with SAFER | 54.7 |
| BERT with ADFAR (this paper) | 67.8 |
These results give substance to the authors' qualification that ordinary accuracy is preserved in general. The direction of the change relative to plain BERT depends on the dataset. MR and IMDB show higher point estimates with ADFAR. SST2 and MNLI show lower ones. For a reader comparing the defenses, the result of interest is the pairing of each attacked score with its ordinary score on the same dataset. Reporting the attacked score by itself would hide the ordinary-performance cost on MNLI. Reporting only ordinary accuracy would miss the principal benefit there.
Inference time and parameter counts
The efficiency measurement is for a single MR example, averaged on one NVIDIA RTX3090. Plain BERT BASE takes 15.7ms, corresponding to 100% of the reference time. BERT with DISP takes 38.9ms, or 247%. BERT with SAFER takes 27.6ms, or 176%. BERT with ADFAR takes 18.1ms, or 115%. ADFAR is the fastest of the timed defenses. Plain BERT still has the shortest mean time in the comparison.
The reported parameter count is 110M for plain BERT, 330M with DISP, 110M with SAFER and 110M with ADFAR. The equal reported counts for ADFAR and plain BERT are at the precision used in the paper. ADFAR adds a classification head within the shared architecture. SAFER's count illustrates a separate point about compute. A defense can reuse the same parameters and still take longer because it evaluates multiple versions of an input.
The timing fits the execution paths of the different systems. DISP uses additional pretrained components to identify and recover suspicious tokens. SAFER combines predictions over perturbed alternatives. ADFAR already has a task prediction when the detector makes its decision. Only the flagged branch needs the rewrite and another pass. The reported mean puts a measured cost on that design for MR. In another mix of inputs, the proportion routed to the second pass would influence the mean.
Results with other substitution procedures
ADFAR's training uses TextFooler examples, so the authors also test whether the improvement extends to two other procedures, PWWS and GENETIC. They implement these additional evaluations using TextAttack. The two procedures represent different heuristic approaches within word substitution. The comparison asks whether the full defense remains beneficial when the edited test inputs come from a procedure different from the one used to construct its training examples. The earlier works are PWWS and GENETIC.
On the MR test set, BERT's after-attack accuracy is 34.2 with PWWS and 21.3 with GENETIC. ADFAR reaches 74.2 and 70.4, respectively. In the same comparison, the original MR accuracy is 86.2 for BERT and 86.6 for ADFAR. All three tested substitution procedures, including TextFooler, therefore give a higher after-attack result with the defense on MR. The level of accuracy still varies across procedures.
On SST2, PWWS gives after-attack test accuracy of 54.3 for plain BERT and 80.5 for ADFAR. GENETIC gives 38.7 and 72.2, respectively. The TextFooler entries in this comparison are 39.8 for BERT and 73.8 for ADFAR. The original SST2 results alongside them are 93.1 and 92.3. The separate main comparison reports 75.6 after attack and 92.4 on original SST2 inputs for ADFAR. The paper gives no explanation for the different SST2 entries. Each pair belongs with the other results from its own comparison.
The evidence here concerns transfer across the tested evaluation procedures. A defense trained with examples from one procedure still improves accuracy when the edited text comes from the other two. These trials compare the complete system to plain BERT. The results therefore describe what transfers for the combined training, detection and rewriting pipeline. The paper does not break out detector precision or recall for the additional procedures in this experiment.
Results with other encoders
The authors also test whether the defense depends on BERT. They add ADFAR to RoBERTa BASE and ELECTRA BASE, with MR and SST2 as the benchmarks. The two encoders have different pretraining designs. The paper describes RoBERTa in terms of revised pretraining choices and a larger corpus, and ELECTRA in terms of a discriminator-based architecture. These comparisons hold the idea of the defense fixed while changing the encoder underneath it. RoBERTa
On MR, RoBERTa gives original accuracy of 88.3 and after-attack accuracy of 30.4. With ADFAR the respective figures are 87.2 and 71.0. On SST2, original accuracy is 93.4 without the defense and 93.2 with it. After attack the figures are 37.4 and 77.6. The improvement on attacked inputs is accompanied by lower original point estimates on both test sets.
ELECTRA gives original and after-attack accuracy of 90.1 and 33.6 on MR. With ADFAR it gives 90.4 and 71.2. On SST2, ELECTRA's original accuracy is 94.2 and its after-attack accuracy is 40.4. With ADFAR those results are 95.0 and 83.0. Both original point estimates rise in these ELECTRA comparisons. With the RoBERTa results alongside them, the repeated finding is an improvement under attack across the tested encoders. The direction of the change on ordinary text remains specific to the encoder and dataset.
What the ablations show
Rewriting supplies robustness and routing protects clean accuracy
The component study uses BERT BASE, TextFooler and the MR and SST2 test sets. The table adds components in stages. It begins with plain BERT, follows with adversarial training, adds frequency-aware randomization, and then adds anomaly detection to complete the defense. The scores are averages over five runs. This progression reveals how each addition changes the two task metrics within the particular stack of components that precedes it.
On MR, adversarial training changes after-attack accuracy from 16.9 to 34.6 and original accuracy from 86.2 to 85.6. Adding frequency-aware randomization yields 72.8 after attack and 85.0 on ordinary inputs. Adding the detector produces 66.0 after attack and 86.6 on ordinary inputs. The move to rewriting produces the largest visible rise in attacked accuracy in this sequence. The addition of detection moves both results in the direction expected for selective rewriting. The system achieves better clean accuracy, and the attacked score is lower than it is with the always-rewrite setting.
ADFAR component ablation on original SST2 test accuracy
Adding anomaly detection recovers much of the clean accuracy lost when rewriting is applied broadly.
The numbers
| System or setting | accuracy % |
|---|---|
| BERT | 93.1 |
| Add adversarial training | 92.6 |
| Add frequency-aware randomization | 90.6 |
| Add anomaly detection, full ADFAR (this paper) | 92.3 |
On SST2, after-attack accuracy in the same ablation sequence starts at 39.8 for BERT, reaches 48.8 with adversarial training, then reaches 82.6 when frequency-aware randomization is added. The complete defense with anomaly detection gives 73.8. The attack and original scores tell complementary stories. The rewrite has a strong protective effect when applied broadly. The detector provides a way to retain more of the ordinary prediction behavior at the cost of allowing some inputs to bypass a potentially helpful transformation.
Those scores address different design questions. If the purpose of a comparison is to test whether the rewrite can mitigate these attacks, the broad-rewrite condition is revealing. If the purpose is to choose a system for input whose origin is unknown, the original scores are relevant as well. The full framework is designed for the latter problem. Its detector has value because genuine inputs will arrive alongside any deliberately altered ones, and a strategy that always edits both kinds can harm correct predictions.
The results are evidence about components as used in this sequence. The change labeled frequency-aware randomization occurs after adversarial training, and the detector is assessed on top of the rewrite machinery. The table therefore establishes their incremental effects in that order. The sweeps over rewrite settings give more targeted comparisons of individual choices inside the randomization procedure.
What the detector recognizes
The authors compare ADFAR's detector with the detector used by DISP. The comparison requires adapting DISP's token predictions to a sentence-level decision. An input is counted as adversarial if DISP marks at least one token as perturbed. ADFAR directly predicts at the input level. The paper describes sampling 500 ordinary inputs and 500 adversarial inputs from the test data for the MR and SST2 detection evaluation.
Precision measures how many flagged inputs are actually adversarial. Recall measures how many adversarial inputs are flagged. F₁ combines precision and recall into a single reported measure. These metrics describe the detection decision before any rewrite. A classifier may still make a correct task prediction on an unflagged adversarial input, and a flagged input may still be classified incorrectly after rewriting. Anomaly detection is an intermediate decision with consequences for task accuracy, and its metrics measure a different outcome.
On MR, ADFAR's detector has reported precision of 90.1, recall of 84.0 and F₁ of 86.9. DISP has reported precision of 68.0, recall of 92.0 and F₁ of 73.2. On SST2, ADFAR has precision of 88.0, recall of 90.0 and F₁ of 88.9. DISP has precision of 59.5, recall of 94.2 and F₁ of 72.9. In both comparisons, ADFAR has higher precision and higher reported F₁. DISP has higher recall. The paper reports these F₁ values alongside the precision and recall entries without giving an aggregation procedure that would let a reader reconstruct them.
The precision and recall tradeoff is relevant to a gate that decides whether to alter an input. A false positive sends ordinary text through a rewrite, with a possible cost to the downstream prediction. A false negative lets an adversarial input take the direct path, foregoing any help the rewrite might have provided. The detector comparison suggests that ADFAR is more selective at the reported operating point. It catches a smaller share of the adversarial inputs than the adapted DISP detector and has fewer ordinary examples among its flagged inputs in the sampled evaluation.
The authors take the detection results as evidence that the heuristic adversarial substitutions they study leave recognizable patterns. That interpretation is consistent with a useful detector trained to tell generated examples from original text. The experiment identifies the performance of the learned decision as a whole. It does not isolate which contextual or lexical cues the head uses. In particular, the frequency rule controls the later rewrite, while the detector operates on the shared encoder's representation. Its performance cannot be attributed to a dictionary threshold alone.
How much to rewrite at inference
The first inference sweep varies the target proportion of words selected for substitution. To reduce the influence of other design choices, the authors train BERT on the original training data and hold the similarity shortlist size at 20. They first vary the substitution ratio from 5% to 50% without the frequency-aware selection rule. As the ratio rises, original accuracy decreases. After-attack accuracy rises and peaks at 30%.
The authors then add frequency-aware selection with a threshold of 200. The broad trends are similar, with the frequency-guided condition achieving stronger original and after-attack accuracy overall. The highest after-attack accuracy in that comparison occurs at 30% with frequency-aware selection. This supports the chosen inference ratio within the examined range and setup. The reported peak also shows why increasing the number of substitutions indefinitely would be a poor reading of the authors' rationale. Extra edits can eventually change the evidence the task head needs.
This sweep addresses a narrower question than the component ablation. The ablation considers whether different parts of the whole defense help. The ratio sweep measures what happens when the extent of an inference rewrite changes under controlled settings. Its use of a classifier trained on original examples helps isolate the effect of the transformation, and the peak comes from that comparison. The measured effect in the full framework additionally depends on its augmented training and its routing decisions.
Why the shortlist is filtered by frequency
A second inference sweep examines the size of the initial similarity shortlist. The authors fix the substitution ratio at 30%, use BERT trained on the original data, and vary the size of the shortlist from 5 to 50. They compare a condition without frequency filtering to a condition that keeps the most frequent part of the similarity shortlist.
nբ = 50% × nₛ
nₛ is the number of candidates in the initial shortlist ranked by similarity. nբ is the number retained after ranking that shortlist by frequency. The multiplication by 50% says that the frequency-based shortlist in this sweep keeps half the initial candidates.
With frequency filtering, the paper reports that both original and after-attack accuracy peak at an initial shortlist size of 20. It also reports higher overall accuracy with filtering than without it. The comparison supports the idea that frequency provides information even after the candidates have been screened for similarity. Given a set of plausible neighbors, restricting the draw to common ones can improve the behavior of the rewrite in the tested setup.
There is a practical difference between the two inference sweeps. In the first, frequency determines which input words receive priority for change. In the second, it determines which of the similar vocabulary words remain eligible as replacements. An input-word frequency threshold can direct the intervention at rare words, while a shortlist filter can direct the outcome toward common ones. The chosen rewrite joins both operations, and the sweeps give separate evidence for where each contributes.
How much to rewrite during training
The final sweep changes the substitution ratio used to generate augmented training data. The authors keep shortlist construction aligned with the inference setup, using an initial similarity shortlist of 20 and retaining the most frequent 50%. They vary the training substitution ratio from 5% to 50% and report the strongest original and after-attack accuracy at 25%.
The resulting choice of a lower ratio in training than at inference reflects the different uses of rewritten text. A training rewrite becomes one of the examples from which the task head learns what predicts the label. Heavy rewriting can add noise to that supervision. An inference rewrite is applied to an input already judged suspicious, where changing enough of the text can help counter the deliberate substitutions. The sweeps support different settings for those two jobs under the reported conditions. They also make clear that the numerical choices come from empirical comparisons of alternatives.
Limitations
Limits the authors identify
The authors motivate ADFAR around adversarial word substitution. They describe misspellings, phrase edits and paraphrases as other forms of textual manipulation, each posing a different problem. Their defense and evaluations center on substitutions made by heuristic procedures. The conclusion about detectability refers to examples made by the procedures they study. That scope matters because the detector learns from a specific distinction in the training data, while the rewriter assumes that lexical replacements are a useful form of intervention.
The authors also identify an intrinsic cost of randomization. Applying it to every input can lower accuracy on ordinary text, and making training rewrites too extensive can introduce noise. Their design addresses these concerns through a detector and through different ratios for training and inference. The ablation shows that the tradeoff remains visible after those choices. The full system gives up some attacked accuracy relative to the broadly applied rewrite in exchange for stronger original accuracy. The authors' claim of preserving ordinary performance is best read across the measured comparisons, which show both increases and decreases in clean accuracy.
The paper reports empirical resistance to named attack procedures. Its discussion of interval bounds and smoothing gives context for what a formal guarantee would require, while ADFAR's evidence consists of measured outcomes under its evaluation setups. Those outcomes establish how frequently the tested systems retain the correct label in those conditions. A guarantee against arbitrary label-preserving substitution would be a different result from the one demonstrated.
Limits visible in the evaluation
Transfer across PWWS, GENETIC and TextFooler is useful evidence within a family of word-substitution procedures. It leaves open how the defense would respond to a procedure built specifically around its anomaly head and stochastic rewrite. The paper does not report a separate adaptive evaluation designed to target those two components together. A procedure could also occupy a different part of the substitution space, where the tendency towards rare synonyms is weaker. The measured transfer gives a basis for expecting some reuse of the defense, while its breadth remains bounded by the comparisons.
The detector's evaluation is based on sampled ordinary and adversarial inputs from two sentiment test sets. Its precision describes that evaluation mixture. In a setting where deliberate inputs are much less common, the proportion of flagged examples that are genuine attacks can differ even if the detector behaves similarly within each class. This also affects cost. Every ordinary example that is flagged incurs a rewrite and another classification pass, so prevalence and routing behavior matter to both latency and ordinary accuracy. The paper's timing result is an average for MR on the stated hardware, with scope determined by that dataset and evaluation.
The datasets cover several text lengths and one sentence-pair task. All of the sentiment benchmarks concern movie reviews, and the broadest encoder and attack comparisons are carried out on MR and SST2. MNLI establishes that the framework can improve results on the tested inference benchmark, but the detailed detector and ablation results come from sentiment data. The study therefore gives better evidence about the internal tradeoffs on those review datasets than about how those tradeoffs generalize across tasks.
Meaning preservation is another boundary of the evidence. ADFAR uses lexical similarity and corpus frequency to prefer common near synonyms. Neither signal directly measures whether the replacement preserves the intended sense at a particular occurrence. The detector's decision to trigger the rewrite likewise says nothing about the semantic safety of each subsequent edit. The reported tests establish final classification accuracy. They do not separately measure how often the defensive rewrite preserves each original sentence's meaning. This distinction matters most where a small nuance is the reason an input belongs to its class.
Several reporting details limit how precisely the experiments can be reconstructed or compared. The randomization pseudocode gives a target candidate count without specifying rounding or how excess rare candidates are handled. It also names a different pool for the final draw than the one implied by the frequency-filtering explanation. Those choices affect the realized rewrite, especially where the number of selectable words is small. The main and later result tables also give different original and after-attack SST2 scores for BERT with ADFAR under TextFooler. Keeping the scores attached to their respective comparisons avoids assuming a reason for the difference.
Finally, the run averages describe typical accuracy in the reported experiments. The main tables give point estimates with no associated dispersion. Small differences, including changes in ordinary accuracy, are therefore best read as the reported direction and magnitude in those experiments. The strongest conclusion is the recurring improvement in attacked accuracy across the tested datasets and encoders, accompanied by a dataset-dependent effect on ordinary predictions and a measured inference cost.
What came after
No subsequent study is documented as building on ADFAR. The paper itself closes by pointing to research on robustness in pretrained classifiers. It leaves a specific question open for that work. When substitutions change, how well does a detector trained on earlier examples still identify the inputs that would benefit from rewriting? The reported tests answer that question for several heuristic procedures at the level of final accuracy. The ablations show why the detector and the rewrite would need to be examined together when extending the evaluation.
Cite
Cite as Rongzhou Bao, Jiayi Wang and Hai Zhao. 2021. Defending Pre-trained Language Models from Adversarial Word Substitution Without Performance Sacrifice. Findings of the Association for Computational Linguistics: ACL-IJCNLP 2021.
@inproceedings{bao2021defending,
title = {{Defending Pre-trained Language Models from Adversarial Word Substitution Without Performance Sacrifice}},
author = {Rongzhou Bao, Jiayi Wang and Hai Zhao},
booktitle = {Findings of the Association for Computational Linguistics: ACL-IJCNLP 2021},
year = {2021},
doi = {10.18653/v1/2021.findings-acl.287},
url = {https://doi.org/10.18653/v1/2021.findings-acl.287}
}This page in Markdown https://md.research.elamur.ai/free/en/papers/bao-2021-defending-pre-trained-language-models/