Fooling the Textual Fooler via Randomizing Latent Representations (2024)

Abstract: Despite outstanding performance in a variety of Natural Language Processing (NLP) tasks, recent studies have revealed that NLP models are vulnerable to adversarial attacks that slightly perturb the input to cause the models to misbehave. Several attacks can even compromise the model without requiring access to the model architecture or model parameters (i.e., a black-box setting), and thus are detrimental to existing NLP applications. To perform these attacks, the adversary queries the victim model many times to determine the most important parts in an input text and transform. In this work, we propose a lightweight and attack-agnostic defense whose main goal is to perplex the process of generating an adversarial example in these query-based black-box attacks; that is to fool the textual fooler. This defense, named AdvFooler, works by randomizing the latent representation of the input at inference time. Different from existing defenses, AdvFooler does not necessitate additional computational overhead during training nor does it rely on assumptions about the potential adversarial perturbation set while having a negligible impact on the model’s accuracy. Our theoretical and empirical analyses highlight the significance of robustness resulting from confusing the adversary via randomizing the latent space, as well as the impact of randomization on clean accuracy. Finally, we empirically demonstrate near state-of-the-art robustness of AdvFooler against representative adversarial attacks on two benchmark datasets. Code for AdvFooler is available at: https: //github.com/mail-research/ AdvFooler-text-defender

text: Findings of the Association for Computational Linguistics ACL 2024, pages 14403–14421 August 11-16, 2024 ©2024 Association for Computational Linguistics
Despite outstanding performance in a variety of Natural Language Processing (NLP) tasks, recent studies have revealed that NLP models are vulnerable to adversarial attacks that slightly perturb the input to cause the models to misbehave. Several attacks can even compromise the model without requiring access to the model architecture or model parameters (i.e., a black-box setting), and thus are detrimental to existing NLP applications. To perform these attacks, the adversary queries the victim model many times to determine the most important parts in an input text and transform. In this work, we propose a lightweight and attack-agnostic defense whose main goal is to perplex the process of generating an adversarial example in these query-based black-box attacks; that is to fool the textual fooler. This defense, named AdvFooler, works by randomizing the latent representation of the input at inference time. Different from existing defenses, AdvFooler does not necessitate additional computational overhead during training nor does it rely on assumptions about the potential adversarial perturbation set while having a negligible impact on the model’s accuracy. Our theoretical and empirical analyses highlight the significance of robustness resulting from confusing the adversary via randomizing the latent space, as well as the impact of randomization on clean accuracy. Finally, we empirically demonstrate near state-of-the-art robustness of AdvFooler against representative adversarial attacks on two benchmark datasets. Code for AdvFooler is available at: https: //github.com/mail-research/ AdvFooler-text-defender

heading: 1 Introduction
text: In the last decade, deep neural networks have achieved impressive performance in the Natural
*The work was done prior to joining Amazon.
Language Processing (NLP) domain. Several deep NLP models have reached state-of-the-art results in several NLP tasks (Devlin et al., 2019) using models such as Recurrent Neural Networks, Transformers, and Pretrained Language Models (PrLMs). However, several works (Iyyer et al., 2018) also reveal that deep NLP models can be fooled by the creation of adversarial examples (Jin et al., 2020). Adversarial examples are synthetically perturbed inputs that are optimized to increase the errors between the predictions of the model and the true labels while being imperceptible to human evaluators (Jin et al., 2020; Iyyer et al., 2018). These developments have sparked concerns about the security and robustness of deep neural networks deployed in NLP applications.
To generate adversarial examples, adversarial attack methods manipulate different aspects of the input sentence, from introducing character errors such as typos or visually similar characters (Gao et al., 2018a; Eger et al., 2019) and replacing words without significantly changing the original semantic in the perturbed inputs (Jin et al., 2020; Li et al., 2020) to recreating sentences with similar meanings using paraphrasing (Iyyer et al., 2018; Qi et al., 2021). Among these methods, black-box adversarial attacks (Alzantot et al., 2018) are some of the most widely studied and effective adversarial approaches. These methods query the victim model multiple times to find the corresponding adversarial perturbations of important words of an input text.
In response to the adversarial threat and to enhance the robustness of NLP models, numerous defenses against textual adversarial attacks have been developed (Zhu et al., 2020; Si et al., 2021; Wang et al., 2021; Ye et al., 2020; Shi et al., 2020a; Xu et al., 2020). The most popular approaches are adversarial training (Zhu et al., 2020; Dong et al., 2021; Madry et al., 2018), which augments the training data with adversarial examples using an additional optimization step, and randomized
14403
smoothing (Ye et al., 2020; Zeng et al., 2023), which replaces the model with its stochastic ensemble based on random perturbations of the input; both of these approaches require training modifications and additional non-trivial training computation (e.g., for adversarial training). Due to the discrete nature of texts, to create adversarial inputs, these defenses also substitute input words with adversarial words sampled from predefined perturbation sets constructed based on the potential attacks instead of gradient-based optimization. This substitution process also aims to preserve the original input semantics. Nonetheless, assuming knowledge of the potential attacks is often unrealistic and impractical.
In this paper, we propose a lightweight, attackagnostic defensive method that can increase the robustness of NLP models against textual adversarial attacks. Our defense, called AdvFooler, randomizes the latent representation of the input at test time to fool the adversary throughout their attack, which typically involves iteratively sampling of discrete perturbations to generate an adversarial sample. Being a test-time defense with negligible computational overhead, AdvFooler also does not incur any training-time computation. Furthermore, as AdvFooler operates within the latent space of the model, it remains agnostic of the perturbation sets associated with potential attacks. While there are some randomization defenses in NLP (Ye et al., 2020; Zeng et al., 2023), they rely on randomized smoothing with necessary modifications to the model’s training to reduce the variance in the model’s outputs caused by randomizing the input or embedding space. The advantages of AdvFooler over the other defenses are shown in Table 1. Our contributions can be summarized as follows:
• We propose a lightweight, attack-agnostic, and pluggable defensive method that hinders the attacker’s ability to optimize for adversarial perturbations leading to adversarial examples. Consequently, the attack success rate is significantly decreased, making the model more robust against adversarial attacks.
• We provide important theoretical and empirical analyses showing the impact of randomizing latent representations on perplexing the attack process of the adversary.
• We extensively evaluate AdvFooler through experiments on various benchmark datasets and rep-

heading: 2 Background

heading: 2.1 Adversarial attacks in NLP
text: Adversarial attacks in NLP can be divided into two categories, depending on what information the attacker has on the victim model. These categories are white-box attacks (Ebrahimi et al., 2018; Cheng et al., 2020) - those that require access to the model’s architecture and its parameters - and black-box attacks (Li et al., 2020; Jin et al., 2020; Li et al., 2018) - those that rely only querying the model for its output. Since the model user rarely shares the underlying model’s architecture of their NLP service, let alone their model’s parameters, white-box attacks have extremely limited practicality, compared to black-box attacks. In the paper, we will focus on the black-box, query-based attack setting, as it is a more realistic scenario in practice and is commonly studied in similar works (Zeng et al., 2023; Nguyen Minh and Luu, 2022; Zhang et al., 2022). Note that, there are also black-box, transfer-based attacks, which, however, still require knowledge of the model architecture for the attack to be effective (Yuan et al., 2021; Li et al., 2021a). Black-box Query-based Attack. Given the text classification task, a model f : Rd → R|C| maps an input x ∈ Rd to a logit vector of dimension |C|, where C is the set of label. The goal of textual adversarial attacks is to search for adversarial examples on which the model makes incorrect predictions. Specifically, given an input sentence x, a corresponding adversarial example x′ can be
crafted to satisfy the following objective:
argmax c f(xadv) ̸= argmax c f(x) s.t. d(xadv − x) ≤ σ (1)
where d(xadv − x) is the perceptual distance between x and xadv, and σ is the maximum acceptable distance. For example, d can measure the number of perturbed words between the original and adversarial input (Gao et al., 2018b). Another popular distance is the semantic dissimilarity between a pair of texts (Iyyer et al., 2018; Li et al., 2020), defined as the cosine distance between the extracted embedding vectors of the inputs from Universal Sentence Encoder (USE) (Cer et al., 2018).
Solving the objective in Eq. (1) is equivalent to searching for perceptually valid perturbations that flip the prediction of the victim model. However, this is a challenging task due to the considerably large search space for textual data. Specifically, the works in (Mrkšić et al., 2016; Li et al., 2018) demonstrate that perturbing random words in the sentence fails to effectively fool the model with a reasonable number of queries. To accelerate the search procedure, existing attacks locate important parts of the sentence, e.g., word (Li et al., 2018; Jin et al., 2020; Li et al., 2020) or group of words (Chen et al., 2021; Lei et al., 2022), to perturb.
Among textual adversarial attacks, adversarial word substitution is one of the most widely studied approaches. These attacks create an adversarial example of an input text x by first identifying the most important words in x and then replacing those words with synonyms from their corresponding synonym sets to cause the victim model to misbehave while aiming to preserve the original semantic meaning. The synonym sets can be created using word embedding models (Mrkšić et al., 2016; Pennington et al., 2014) or using the predictions of a PrLMs given the input sentence (Li et al., 2020). One important feature of these attacks is that both of the aforementioned steps require querying the victim model many times to determine which words are important or which synonyms maximize the model’s prediction errors. In the first step, the adversary queries the model to calculate the importance score of each word in x and select the most potential locations (with the highest importance scores) for later perturbations. To find the substituting synonyms that maximize the model’s prediction error, the attacks can either perform a greedy search (Li et al., 2020; Jin et al.,
2020; Li et al., 2018) or combinatorial optimization algorithm (Zang et al., 2020; Alzantot et al., 2018). Chen et al. (2021) extend this principle to multi-granularity by determining important constituents in the syntactic tree that maximizes the decrease in confidence score when being paraphrased. Similarly, this step involves a sequence of queries on the victim model. By introducing randomization to the latent representations of queries, our defensive mechanism disrupts the adversary’s ability to estimate important words (or paraphrases), making their synonym-substituting process significantly harder during the attack.

heading: 2.2 Adversarial defense methods
text: To defend against textual adversarial attacks, several defenses (Wang et al., 2022) have been developed. The goal of an adversarial defense is to improve the robustness of the victim model; that is to achieve good performance on both clean and adversarial examples. Existing adversarial defenses can be divided into two categories: certified (Ye et al., 2020; Zeng et al., 2023; Jia et al., 2019) and empirical (Zhu et al., 2020; Wang et al., 2021; Dong et al., 2021; Li and Qiu, 2020; Zhou et al., 2021; Miyato et al., 2017).
First introduced in Goodfellow et al. (2014), adversarial training is the most often studied empirical defense method. It provides additional regularization to the model and improves the model’s robustness when training it with adversarial samples. Several subsequent works study adversarial training for NLP tasks with adversarial examples created on the input space (Ren et al., 2019; Li et al., 2020; Jin et al., 2020). Some adversarial training works improve the model’s robustness by introducing adversarial perturbations in the embedding space (Zhu et al., 2020), or by incorporating inductive bias to prevent the model from learning spurious correlations (Wang et al., 2021; Madry et al., 2018), as well as methods that increase diversity of ensembled models, leading to globally better robustness (Pang et al., 2019). These methods effectively improve the model’s robustness without significant compromise to its clean accuracy.
In contrast to the empirical methods, certified defenses can provably guarantee model robustness even under sophisticated attackers. One popular certified-defense approach is randomized smoothing (Ye et al., 2020; Zeng et al., 2023), which constructs a set of stochastic ensembles from the input
and leverages their statistical properties to provably guarantee robustness. Differential Privacy (DP) defenses such as (Lecuyer et al., 2019) are similar to SAFER and RanMASK, achieving certified robustness through the use of DP framework. Note that RanMASK and DP-defenses incur high training overhead. In contrast, Interval Bound Propagation (IBP) methods (Shi et al., 2020b; Jia et al., 2019; Huang et al., 2019) utilizes axis-aligned bounds to confine adversarial examples. Despite their effectiveness and ability to certify robustness, both approaches rely on access to the synonym sets of potential attacks. Randomized-smoothing methods also modify the training phase to reduce the variance of the outputs of the ensemble. Due to the ensemble, they incur significant computational overhead in the inference phase. In contrast, our defense is lightweight and attack-agnostic, and can better control the variance of the outputs by randomizing the latent representations, instead of via randomization in the input space. A summary of the characteristics of AdvFooler and the existing defenses is shown in Table 1.

heading: 3 Methodology

heading: 3.1 Randomized latent-space defense against adversarial word substitution
text: Algorithm 1 AdvFooler Input: a model f , an input sentence x, scale ν. Output: output logit l.
1: z0 = Emb(x) 2: for layer l in {1...L} of model f do 3: ϵ ∼ N (0, νI) 4: zi+1 = hl(zi + ϵ) 5: end for 6: return: zL
Since the adversary relies on querying the victim model multiple times to find adversarial examples, receiving inconsistent feedback from the model can make it significantly harder for the adversary to find the optimal adversarial perturbations. To fool such an adversary, we introduce stochasticity to the model by randomizing the latent representation of an input x. Formally, for hl as the l−th layer of the model, we sample an independent noise vector ϵ, which is added to hl(x) as input to the next layer of the model. Without loss of generality, ϵ is sampled from a Gaussian distribution N (0,Σ) with Σ as a diagonal covariance matrix, or N (0, νI), ν ∈ R. The detailed algorithm is presented in Algorithm 1.
Note that, instead of randomizing the latent representation, the defender can directly randomize the textual input; however, this approach makes it significantly harder to control the corresponding change in the prediction, or to maintain an acceptable level of the model’s performance when applying the defense.
Let fAdvFooler be the proposed randomized model corresponding to the original f . When the variance of injected noise is low, we can assume that small noise slightly changes the output logits but does not shift the prediction of the model.

heading: 3.2 Effect of randomizing latent representations on adversarial attacks
text: In textual adversarial attacks, the adversary first determines important parts in a sentence x = {w0, . . . , wl} to reduce the search space by using the importance score, which is defined as the difference in the confidence:
Ix̃ = fy(x)− fy(x̃), (2)
where fy is the logit returned by the model f w.r.t ground-truth label y and x̃ is the perturbed sentence. For example, Li et al. (2018) and Jin et al. (2020) remove a word wi in the sentence x, while Li et al. (2020) replace wi by the token MASK to obtain x̃ = {w0, . . . , wi−1,MASK,wi+1, . . . , wl}. On the other hand, phrase-level attacks transform x by paraphrasing constituents extracted from the syntactic tree (Chen et al., 2021) or masking them out (Lei et al., 2022). The adversary then selects perturbations with the highest scores. Intuitively, this process emulates estimating the gradient of the importance score in the discrete space.
When introducing randomness to the latent space, the model output is changed. Such changes can mislead the attacker to select ineffective perturbations. For example, the attacker may instead select “less important” words (i.e., those that have lower original importance scores before randomization) to perturb, thus reducing the attack’s success probability (Mrkšić et al., 2016; Li et al., 2018).
Theorem 3.1. If a random vector v ∼ N (0, νI) where ν is small is added to the hidden layer h of the model f which can be decomposed into f = g ◦ h, the new important score Inewx̃ is a random variable that follows Gaussian distribution N (Ix̃, ν(∥∇h(x)gy(h(x))∥2 + ∥∇h(x̃)gy(h(x̃))∥2)).
Theorem 3.1 (proof is in the Supplementary) states that randomly perturbing the hidden presentation leads to a randomized important score. When ν is high, the randomized importance scores have high variance, which can cause the attack to select the wrong important words or phrases.

heading: 3.3 Effect of randomizing latent representations on clean accuracy
text: If randomization induces substantial fluctuation in the model’s output, there is a possibility that the model might predict a wrong label, resulting in a decrease in clean accuracy. Randomized defenses such as SAFER (Ye et al., 2020) and RanMASK (Zeng et al., 2023) introduce randomness to the model in the input space (i.e., randomizing the input tokens). While they are also effective against textual adversarial attacks, the input space of NLP models is discrete. Perturbing discrete inputs can lead to significant changes in the model’s outputs (a fact that we will empirically prove in the next section), which results in a different model’s prediction. To mitigate this problem, existing randomized input defenses rely on randomized smoothing: train the model with perturbed input and apply ensemble at inference to reduce the variance in the model’s output. Nevertheless, these approaches are computationally expensive and require access to the training phase. Conversely, by randomizing the latent representations, AdvFooler induces a significantly smaller variance in the model’s output. Furthermore, AdvFooler gives the defender flexibility to select the suitable induced variance without requiring access to the training process. Specifically, given a pretrained classification model and a small clean test set, the defender can select the noise scale ν at which the variance causes the clean accuracy drops by a chosen percentage (e.g., in our experiments, it is 1%).

heading: 3.4 Empirical analysis
text: In this section, we empirically study the effect on the model’s performance and attack process of various randomized defenses, including AdvFooler. Empirical effect on model’s performance. We compute the differences in cross-entropy losses between those of the randomized model and those of the base model for each sample in the AGNEWS test dataset, which expresses how the predictions vary, under different randomization approaches. Figure 1 shows the loss changes in SAFER, RanMASK, and AdvFooler. As we can observe, in SAFER and RanMASK, perturbing the input to-
kens induces a higher variance in the loss compared to AdvFooler. Consequently, both of these methods lead to significant drops in the model’s performance without adversarial training and ensemble. Empirical effect on fooling the attacks. To demonstrate that AdvFooler can fool the adversary into selecting non-important words, we calculate the important score of each word for multiple samples from the AGNEWS dataset. The important words before and after applying AdvFooler are presented in Figure 2. As we can observe, AdvFooler causes the attack to select different important words, many of which are originally unimportant. Specifically, in the first sentence, the token “Airlines” is the most important. After adding random noise to the latent representation, AdvFooler changes the important score for each token enough to mislead the adversary into thinking a different token (“Yesterday” token) is the most important token. A similar phenomenon can be seen in the second sentence, where the important scores change significantly, and unimportant tokens become important ones after randomization. Note that, these experiments use the random noise scale ν that in-
duces at most 1% clean performance drop.

heading: 4 Experiments

heading: 4.1 Experimental setup
text: Evaluation Metrics. We evaluate the defenses using four metrics: Clean accuracy (Clean%), Accuracy under attack (AuA%), Attack success rate (ASR%), Average number of queries (#Query). Clean% measures the defense’s impact on the clean performance. Both AuA% and ASR% measure the model’s robustness under attack. #Query is the averaged number of queries used by the adversary to find adversarial examples; the higher #Query is, the more difficult the attack is. Datasets and Model Architectures. We evaluate the defenses on two benchmark datasets: AG-News Corpus (AGNEWS) (Zhang et al., 2015) and Internet Movie Database (IMDB) (Maas et al., 2011). To assess the generality of AdvFooler on model architectures, we evaluate it on two state-of-the-art, pre-trained language models: BERTbase (Devlin et al., 2019) and RoBERTabase (Liu et al., 2020). More details are provided in the Appendix. Adversarial Attacks and Parameters. We choose the following widely used and state-ofthe-art adversarial attacks to evaluate our defense: TextFooler (Jin et al., 2020), TextBugger (Li et al., 2018), and BERT-Attack (Li et al., 2020). Both TextFooler and BERT-Attack rely on the important scores to identify important words and replace them with the corresponding synonyms; TextFooler uses word embeddings from (Mrkšić et al., 2016) for synonym generations, while BERT-Attack uses pretrained BERT to generate the synonyms. In addition to replacing words, TextBugger also introduces
word augmentation - perturbing the characters in words.
Baseline Defenses. We compare AdvFooler against various types of defense methods. For empirical defenses, we select Adversarial Sparse Convex Combination (ASCC) (Dong et al., 2021), InfoBERT (Wang et al., 2021), FreeLB (Zhu et al., 2020), and Textual Manifold Defense (TMD) (Nguyen Minh and Luu, 2022). ASCC and FreeLB improve the model’s robustness by employing adversarial training; FreeLB introduces adversarial perturbations to word embeddings, while ASCC generates adversarial examples from a convex hull spanned by word substitution. InfoBERT incorporates information theory to refine both local and global features. Textual Manifold Defense reduces the effects of the adversarial examples by projecting the embeddings of input sentences to an approximated embedding manifold. For certified defenses, we evaluate on RanMASK (Zeng et al., 2023) and SAFER (Ye et al., 2020), which construct a set of randomly perturbed inputs using token masking and synonym substitution, respectively. Then, they leverage the statistical properties of the predicted output to achieve better model robustness.
Implementation Details. For a fair evaluation, we follow the implementation guidelines for evaluating adversarial attacks and defenses in Li et al. (2021b): (1) the maximum percentage of modified words ρmax for AGNEWS and IMDB are 0.3 and 0.1, respectively, (2) the maximum number of candidate replacement words Kmax is set to 50, (3) the maximum percentage of modified words ρmax for AGNEWS and IMDB must be 0.3 and
0.1, respectively, and (4) the maximum number of queries to the victim model is Qmax = Kmax ∗ L, where L is the length of, or the number of tokens in, the input sentence. Clean% is calculated on the entire test set from each dataset, while the robustness metrics AuA%, ASR%, and #Query are computed on 1,000 randomly chosen samples from the test set. All attacks are based on TextAttack implementation (Morris et al., 2020).

heading: 4.2 Defense performance
text: We report the defense performance on AGNEWS in Table 2. As we can observe in this table, on the base model BERT, AdvFooler outperforms all adversarial training techniques (ASCC, FreeLB, and InfoBERT) and the randomized smoothing method, SAFER. AdvFooler is consistently in the top-3 robust defenses; the robustness of AdvFooler and TMD are within 1-2% of each other, while they are generally both lower than the robustness of another randomized-smoothing defense, RanMASK. However, the clean accuracy in RanMASK drops significantly, approximately 4%, while the clean accuracy in AdvFooler is guaranteed to be within 1% of the base model. Note that, all of the evaluated textual defenses require access to the training data. On the base model RoBERTa, AdvFooler similarly achieves a top-3 performance.
For IMDB’s results in Table 3, we can observe similar robustness results. TMD’s performance is observed to be consistently better with RoBERTabase. AdvFooler is effective against the attacks and achieves comparable results to the best defenses (SAFER and TMD).
In summary, AdvFooler achieves competitive robustness to the state-of-the-art defenses; however, AdvFooler has significantly lower training and inference overhead compared to TMD, RandMASK, and SAFER and does not have access to the training data. Difficulty of Adversarial Attacks against AdvFooler. For all the considered adversarial attacks, the number of queries to locate important words (the first step) of an input text is the same with or without the defenses. Thus, the higher number of queries in an experiment is a result of a more difficult synonym-replacement phase. This also explains considerably smaller average numbers of queries for the baseline (without any defense) in Tables 2 and 3, compared to the protected models.
We can observe, in Tables 2 and 3, that the average numbers of queries for the adversarial attacks to be successful against AdvFooler are significantly higher than those in all the defenses except TMD in a few cases. The results demonstrate the effectiveness of fooling the attacks in AdvFooler. As explained in Section 3, randomizing the important scores just enough makes the adversary select a different set of important words, which leads to a more challenging synonym-replacement process with a significantly higher number of queries. AdvFooler with other attacks. In the Supplementary, we provide additional experiments evaluating AdvFooler against other types of attacks, including black-box hard-label (Appendix 4.7) and white-box attacks (Appendix C.5), even though they do not align with the threat model studied in this work and several related works (Nguyen Minh and Luu,
2022; Zhang et al., 2022; Zeng et al., 2023; Li et al., 2023) to AdvFooler. The results show that AdvFooler is still effective in defending against these attacks, further highlighting the versatility of AdvFooler.

heading: 4.3 Robustness from randomizing different latent spaces
text: In this section, we study the model’s robustness when randomizing different layers of the model. For comparison, Specifically, we randomize only the first, middle, and last layers and all layers of the model. The model’s robustness against TextFooler is reported in Figure 3. As we can observe, randomizing the early layer of the model is more effective than randomizing the later layers of the model. More importantly, adding noise to all the layers leads to a significantly higher accuracy under attack and a higher average number of queries.

heading: 4.4 Trade-off between clean accuracy and robustness
text: As discussed in Section 3, our approach allows the defender to flexibly trade-off between the clean accuracy (or variance in the output logits) and the model’s robustness, a feature that is challenging to perform in other defenses. In AdvFooler, this is
accomplished via tuning the noise scale ν. A large ν value leads to both a large variance of the model’s output, which can lead to a lower clean accuracy, and a high chance of fooling the adversarial attacks.
We report the model’s clean accuracy and robustness when varying the value of ν in Figure 4. As we can observe, increasing ν generally increases the model’s robustness against all the evaluated attacks while the clean accuracy only slightly changes. However, when ν reaches a certain value, the clean accuracy begins to decrease, at which point the robustness of the model also decreases. The plot also shows that the noise scale when both accuracy under attack and clean accuracy start to decrease would also be the noise scale that makes the model more robust to all types of attack. This suggests that, in practice, the defender selects as large ν value as possible for a certain small drop of clean accuracy. For example, in our experiments, we select the ν value at which the clean accuracy drops by at most 1% using the test set.

heading: 4.5 AdvFooler with adversarially trained models
text: As discussed previously, AdvFooler can be used to improve the robustness of any existing pretrained model; i.e., AdvFooler is a pluggable defense. In fact, AdvFooler can also be combined with other types of defenses to provide another layer of protection and further improve the model’s robustness. In this section, we study the effectiveness of AdvFooler in conjunction with adversarial training methods, including FreeLB and InfoBERT.
Table 4 shows the defense performance before and after applying AdvFooler on adversarially trained models using FreeLB and InfoBERT. We can observe that AdvFooler significantly improves the robustness of the adversarially trained models, with up to 20% improved accuracy under attack
in some experiments. While AdvFooler can also be combined with other defensive mechanisms, we leave these to future works.

heading: 4.6 Inference time analysis
text: In this experiment, we study the computational overhead that each defense introduces at inference time. We use the IMDB test set and record the inference runtime of the BERT model under different defenses. The results are shown in Table 5. From the result, we can see that AdvFooler introduces very little computational overhead compared to most other defenses. Randomized-smoothing methods, such as RanMask and SAFER, incur significant overhead to the inference phase. TMD also adds non-trivial inference overhead (33.3%); as acknowledged by the authors, the main bottleneck of TMD is its high computational overhead of the on-manifold projection (Nguyen Minh and Luu, 2022). Only adversarial training methods, such as ASCC and FreeLB, do not introduce additional overhead during inference time. Most importantly, AdvFooler is the only method that has consistently high robustness and a negligible inference overhead (2.6%).

heading: 4.7 AdvFooler’s performance on hard-label attacks.
text: In some cases, the adversary can choose to ignore the output logits and only rely on the hard-label output of the model, as seen in Maheshwary et al. (2021). The so-called hard-label attacks first ini-
tialize a sample that flips the prediction, move it toward the original input until it passes through the decision boundary, then select the sample at the previous step as adversarial example. However, since AdvFooler is a randomized model, it might sometimes return labels that are different from the model without noise for the attack queries. Therefore, it can fool the attack to go a bit further, and the sample found by the attack turns out to be non-adversarial. In this section, we study the performance of AdvFooler against this hard-label attack. In this experiment, we ran these attacks against the base model and AdvFooler. The attack may accidentally flag a chosen perturbation as an adversarial example although this sample may be mispredicted due to the added noise in our defense; in other words, the selected sample is not a true adversarial example since, under a different random noise, the model prediction may still be correct. To avoid such a situation and fairly evaluate the performance of AdvFooler , for each “supposedly adversarial example” generated by the attack, we feed it to the model 5 times and record the model’s predictions; the model’s prediction used for performance evaluation is the prediction occurred most. As we can observe from Table 6, hard-label attack struggles to find consistent Adversarial Examples the bigger the noise being inserted into the model.

heading: 5 Conclusion
text: In this work, we proposed a lightweight, attackagnostic defense, AdvFooler, that can improve the robustness of NLP models against textual adversarial attacks. Different from existing defenses, AdvFooler does not incur any training overhead nor relies on assumptions of the potential attacks. The main idea of AdvFooler is to mislead wordlevel perturbation-based adversary into selecting unimportant words by randomizing the latent space of the model, resulting in a significantly more challenging synonym-replacement process. We then provide both theoretical and empirical analyses to explain how AdvFooler fools the adversary, as well as its effect on the model’s accuracy. Our extensive experiments validate that AdvFooler improves the robustness of NLP models against multiple state-ofthe-art textual adversarial attacks on two datasets. Finally, being a pluggable defense, AdvFooler can also be combined with existing defenses, such as adversarial training, to further protect the NLP models against these threats.
Limitations
Although AdvFooler is a lightweight, pluggable, and effective defense, there are some limitations that can be improved. Our analysis and empirical evaluation focus on black-box query-based attacks. We do not include black-box attacks that utilize the transferability from a surrogate to a target model, even though our threat model does not make any assumptions about the network architecture or the training dataset. We also do not consider an adaptive attacker, who makes multiple queries to estimate the importance of each word or phrase (i.e., Ix̃). The expected value of Ix̃ calculated by this adaptive attacker against AdvFooler (i.e., w.r.t model fAdvFooler) will be similar to that of the original importance score without the defense (i.e, w.r.t model f ). Evaluating AdvFooler against this adaptive attack in conjunction with existing word-level perturbation-based attacks could be an interesting study. Similarly, besides adversarially-trained approaches, it would also be interesting to study the robustness of the combination of AdvFooler and other types of defenses. Finally, for different model architectures, randomizing different latent layers could yield different effects on the robustness. This would be interesting to boost the effectiveness of AdvFooler for specific models. We leave these to future works.
Ethics Statement
The rapid integration of NLP models in various domains and applications has brought significant transformations to our daily lives. Unfortunately, most NLP models face significant vulnerability to textual adversarial attacks, undermining confidence in their deployment and usage. Among the existing textual adversarial attacks, word-level perturbationbased attacks pose a severe threat to the model users since these attacks are the most effective and do not require access to the model architectures or their trained parameters.
To address the risks of these attacks, our work proposes a lightweight, attack-agnostic defense for existing NLP models. Our detailed theoretical and empirical analyses show the defense’s comparable performance to the existing state-of-the-art defenses across a wide range of NLP models, textual adversarial attacks, and benchmark datasets. However, our defense does not necessitate any additional computational overhead at both training and inference time and can be used with any existing
pretrained models. In summary, the proposed defense can improve the adversarial robustness of existing NLP models against word-level perturbationbased attacks, thereby bolstering user confidence in their utilization for real-world applications.

heading: A Proof of Section
text: Theorem 3.1. If a random vector v ∼ N (0, νI) where ν is small is added to the hidden layer h of the model f which can be decomposed into f = g ◦ h, the new important score Inewx̃ is a random variable that follows Gaussian distribution N (Ix̃, ν(∥∇h(x)gy(h(x))∥2 + ∥∇h(x̃)gy(h(x̃))∥2)).
Proof. When v is small, we have the first-order approximation of the model with noise
fAdvFooler(x) = g(h(x) + v)
≈ f(x) +∇h(x)g(h(x))v.
In this case, since each application samples a different noise vector, the new important score becomes
Inewx̃ ≈ fy(x) +∇h(x)gy(h(x))v1 − fy(x̃) −∇h(x̃)gy(h(x̃))v2 = Ix̃ + v3
where
v1, v2 ∼ N (0, νI), v3 ∼ N (0, ν(∥∇h(x)gy(h(x))∥2
+ ∥∇h(x̃)gy(h(x̃))∥2)).

heading: B Additional Implementation Details
text: B.1 Dataset
We evaluate AdvFooler on two benchmark datasets: AG-News Corpus (AGNEWS) (Zhang et al., 2015) and Internet Movie Database (IMDB) (Maas et al., 2011). AGNEWS is a classification dataset of news articles created from the AG’s corpus*. It contains 120,000 training samples and 7,600 test samples where a sample belongs to one of four classes: World, Sports, Business, and Sci/Tech. IMDB is a binary sentiment classification dataset of reviews extracted from the IMDB website. This dataset contains 50,000 samples and is split equally into the training and test sets. For IMDB, we use the original dataset † from Maas et al. (2011).
*http://groups.di.unipi.it/~gulli/AG_ corpus_of_news_articles.html
†https://ai.stanford.edu/~amaas/data/ sentiment/
For AGNEWS, we use the datasets from HuggingFace Datasets (Lhoest et al., 2021). Similar to (Nguyen Minh and Luu, 2022), we also set the model’s max sequence lengths for IMDB and AGNEWS to be 256 and 128, respectively based on their average sample length.
B.2 Models
We conduct experiments on two state-of-the-art, pre-trained language models: BERTbase (Devlin et al., 2019) and RoBERTabase (Liu et al., 2020). BERT is a Transformer-based language model that outperforms other models in various benchmarks at the time of its release and is widely used for text classification tasks. RoBERTa is a variant of BERT with an improved training process and performance.
B.3 Training Hyperparameters
For the NLP models, we employ the pretrained models from HuggingFace Transformer (Wolf et al., 2020) and finetune them for another ten epochs. We use grid search from 1e-5 to 1e-3 to find the optimal learning rate for each model on the respective dataset. The optimally fine-tuned models are used for the robustness evaluation.

heading: C Additional Experiment
text: C.1 AdvFooler on varying model layers
In this experiment, we study the performance of AdvFooler when randomization is applied at various latent layers of the model. The accuracy and robustness results are shown in Tables 7 and 8. As we can observe from the tables, adding noise to the output of the attention layer yield better robustness in general. Furthermore, injecting noise into the [CLS] token is more effective than to all the hidden layers.
C.2 Randomization techniques comparison
To show how a lower loss variance makes a randomization method more effective against adversarial attacks, we ran both RanMASK and SAFER, two randomization methods that have a higher variance, through the same experiments on the base model without ensembling. As we can observe from the results in Table 9, both RanMASK and SAFER performed significantly lower than their corresponding baselines in the main experiment. This shows that
these methods cannot be used in a similar way to AdvFooler(i.e., without ensembling during inference), since their high variance makes them more susceptible to attacks, and can only be used in tandem with ensembling and adversarial training with data augmentation.
C.3 AdvFooler against Expectation over Transformation (EoT)
To combat against randomization defense, Athalye et al. (2018) proposed Expectation over Transformation (EoT), a general framework to construct adversarial examples that remain adversarial over a chosen transformation distribution. EoT works by generating an adversarial example from a transformation distribution instead of a single example, which could negate the effects of AdvFooler. However, to capture the distribution of the transformation being made by AdvFooler’s noise, the adversary needs to query the model multiple times for each query, thus increasing the query budget. To evaluate AdvFooleragainst EoT-based attacks, we ran our method against the modified TextBugger and TextFooler with the EoT framework. As we can observe in Table 10, the two EoT-based attacks achieve higher Accuracy Under Attack against AdvFooler compared to the original setting. Although EoT can help negate the effects of AdvFooler’s randomness on adversarial input, the number of
queries needed to find an adversarial example exceeds the budget before it can generate an adversarial example. To re-confirm this explanation, we increased the query budget by a factor of 10. As expected, EoT was able to reduce the Accuracy Under Attack of AdvFooler. Nevertheless, this experiment shows the limited practicality and effectiveness of EoT against AdvFooler.
C.4 AdvFooler’s effect on model’s output error
An immediate question is whether the score returned by AdvFooler is still reliable; otherwise we can just output an arbitrary fixed value for every input, which totally negates any score-based attacks. To calibrate the output of AdvFooler, we calculate the Expected Calibration Error (ECE) of the BERT-base model with and without the use of AdvFooler. We run the experiment five times and report the average ECE score and its standard deviation for comparison. From the results in Table
11, we can see that, the ECE differences between with and without using AdvFooler is low in both datasets, with the margin of error when using AdvFooler only at 0.2%. This shows that even though AdvFooler can affect the output logits of the model, the changes will only deviate slightly from the original prediction.
C.5 AdvFooler performances against the transferred, white-box attack
In the main paper, we focus on defending in the black-box setting, as it is a more realistic scenario in practice. Nevertheless, we provide an empirical study of the effectiveness of AdvFooler against a type of attack where the adversary has access to either the base model or the randomized model to generate the adversarial example of an input. We call this type of attack transferred, white-box attacks. Note that, this attack is not truly a white-box attack, where the fact that the adversary has access to the base model, but there still exists a mismatch between the attacker’s possessed model and the defender’s possessed model due to the added randomization. Even with the randomized model, the base white-box approach used in this study is not specifically designed to make good use of the noise distribution of the randomized model, thus, it is not truly a white-box attack case.
Most white-box attacks focus on increasing the loss of the model through gradient computation, choosing the perturbation in the sentence that increases loss the most. We employ HotFlip (Ebrahimi et al., 2018) as the studied white-box
attack. The experimental setup is similar to that in the main experiments, with the number of words of a sentence that the attacker can perturb increased to 10% and 30% (instead of only two words in the original paper) for IMDB and AGNEWS, respectively. We also give HotFlip access to the model’s original parameters, which they can use to create adversarial examples and bypass defense mechanics provided by the defense methods (in the case of RanMASK, TMD, and AdvFooler). To make sure the adversarial examples created using the process can trick the model using the defense, we also ran the adversarial examples through the defense method 5 times and take the class that being classified to the most. As we can observe in Table 13, AdvFooler is effective against HotFlip in both datasets, increasing the AuA of the baseline model by over 20%. We hypothesize that introducing randomness into the model can turn it into a smoothed classifier, consequently diminishing the adversarial impact.
Furthermore, we also consider the case where the adversary ignores the noise from the defense and only attacks the original model. We compute the AuA/ASR of AdvFoolerin this case and compare it to RanMASK and TMD. Table 14 shows that AdvFooler still achieves high robustness compared to TMD.
C.6 Comparison to Other Defenses With Similar Accuracy
We conduct experiments on tuning the masking rate of RanMASK in AGNEWS such that the clean accuracy is similar to that of AdvFooler. We de-
Table 12: The performance of RanMASK on AGNEWS with different mask rates.
Models MaskRate Clean Accuracy (%) TextBugger TextFooler BERTAttack
AuA(%) (ASR(%)↓) Avg. Query↓ AuA(%) (ASR(%)↓) Avg. Query↓ AuA(%) (ASR(%)↓) Avg. Query↓
BERT 0.9 90.14% 52.50% (41.60%) 582.21 54.60% (38.93%) 511.98 61.10% (31.73%) 595.57 BERT 0.3 93.50% 22.50% (75.88%) 360.12 24.10% (74.09%) 325.63 42.90% (54.12%) 412.99
RoBERTa 0.9 90.41% 52.30% (41.50%) 575.94 54.20% (39.37%) 516.98 60.00% (32.43%) 594.93 RoBERTa 0.3 93.30% 34.00% (63.56%) 396.72 35.7% (61.74%) 359.52 45.60% (50.97%) 429.72
Ba se lin e Ad vF oo ler
anz sells project finance unit australia amp ; new zealand banking group said it would transfer most of its project finance business to standard chartered . .
anz sells project finance unit australia amp ; new zealand banking group said today it most of its project finance business would be transferred to standard chartered . .
anz sells project finance unit australia amp ; new zealand banking group said today it would transfer most of its london - based project finance business to standard .
anz sells project finance unit australia amp ; new zealand banking group said today it would transfer most of its london - based project finance business to standard . .
anz sells project finance unit australia amp ; new zealand banking group said today it would transfer most of its london project finance business to standard chartered .
anz sells project finance unit australia amp ; new zealand banking group said today most of the project finance business would be transferred to standard chartered . .
new zealand banking group said today it would transfer most of its london based project finance business to standard chartered . . .
0.9466
0.9968
0.9994
0.9984
0.9993
0.9946
0.9926
0.9930
0.9975
0.9937
0.9946
0.9970
0.9957
0.9928
0.94
0.95
0.96
0.97
0.98
0.99
1.00
Figure 5: Illustration of each paraphrase’s score when calculated with and without AdvFooler. In this case, MAYA selects the first paraphrase when attacking the baseline model, while selecting the last paraphrase when attacking the model protected by AdvFooler.
crease the random masking rate from 90% of the words in a text example to 30%, which would increase RanMASK’s accuracy, as shown in their paper (Zeng et al., 2023). We also retrain a RanMASK with a random masking rate of 30%, to prevent differences in masking rate between training and inference.
Table 12 shows that when decreasing the masking rate in RanMASK does increase the clean ac-
curacy of the model, from 90% to 93% in accuracy. On the other hand, the accuracy under attack has decreased tremendously, reducing to half of the original AuA. This shows that, while RanMASK was able to be robust against adversarial attacks, this method also requires larger trade-offs in accuracy compared to other methods. The result also shows that RanMASK requires fine-tuning of the masking rate to achieve good performances under attack, as the effective masking rate was chosen from their certified robustness experiments.
C.7 AdvFooler’s performance against multi-granular attacks.
In the main experiments, we focused on attacks that perturbed the text input on word level, i.e., focus on finding important words and replacing them
with synonyms, leading the model to make wrong outputs. However, there are attacks that focus on perturbing a sequence of words, paraphrasing the phrases and sentences of the input. To test the effectiveness of our defense against these types of attacks, we use MAYA - Multi-grAnularitY Attack(Chen et al., 2021) as the attack that perturbs both words and sequences of words in the input text. This attack breaks the sentences into constituencies (phrases, phonemes), then paraphrases them to generate the perturbations. MAYA selects the best perturbation for the next round (if the perturbed sentence is not yet an adversarial example) by querying the model to calculate the confidence scores of these perturbations. The defense performance is reported in Table 15.
As can be observed, AdvFooler is effective in defending against perturbations in different granularities, achieving second-best accuracy under attack (AuA%) and number of queries (#Query). Since MAYA uses confidence scores to select the next perturbation, AdvFooler’s randomization strategy can mislead MAYA’s calculation, causing it to select the incorrect perturbations, similar to the case of word-perturbation attacks.
To empirically confirm this phenomenon, we show the effects of AdvFooler on the scores used by MAYA to select the paraphrase perturbation in Figure 5. From the illustrations, we can observe that AdvFooler causes the scores to slightly change from the baseline model, sufficient to rearrange the ranking of the perturbations. More specifically, as MAYA selects the perturbation with the lowest score, AdvFooler affects MAYA’s selection from the first paraphrase in the Baseline case to the last paraphrase in the protected model with AdvFooler; this misleads the attacker to select a suboptimal perturbation selection. Furthermore, the slight change in scores caused by AdvFooler makes it more difficult to discern which paraphrases are more adversarial, as can be seen from the scores between the baseline and the AdvFooler columns, we can see
that the first paraphrase is the most adversarial in the baseline column, compare to AdvFooler, where the most adversarial paraphrase is harder to differentiate, making the process of selecting paraphrase less trivial for MAYA.
C.8 Comparison against recent defense methods.
In the main experiment, we have compared AdvFooler against several widely known and benchmarked defense methods to show the effectiveness of our method. To further investigate this point, we ran additional experiments against more recent defenses and compared their results to AdvFooler. We selected RSMI (Moon et al., 2023) and DSRM (Gao et al., 2023) for comparison as they are recent state-of-the-art methods and they have reported good results. DSRM increases the model’s robustness through adversarial training by perturbing the input data’s probability distribution. RSMI, on the other hand, makes the model more robust via randomized smoothing through ensemble and Gradient-Guided Masking. We ran these two methods against the main experiment setup and compared their results to ours. Table 16 shows that DSRM can increase the model’s robustness, having higher AuA than InfoBERT and FreeLB in IMDB. However, the overall performance of DSRM is lower compared to AdvFooler. RSMI, on the other hand, was able to perform well compared to most methods, in both AGNEWs and IMDB datasets
Although the performance of RSMI is high, our method still holds many advantages. Firstly, RSMI’s ensemble process adds a substantial inference time compared to AdvFooler (and also DSRM). As shown in Table 17, the inference time of RSMI is almost 12 times more than both AdvFooler and DSRM. Secondly, both DSRM and RSMI require access to and modification of training, while AdvFooler is pluggable, allowing it to
be used without modifying the existing parameters of the model. This is important, as adversarial training methods like DSRM could increase the training time substantially compared to normal finetuning(Gao et al., 2023). These characteristics of AdvFooler make it an attractive defense for a base model without needing further training, or for users to combine AdvFooler with other defenses to boost the performance of these defenses.

heading: D Usage of AI assistant in this paper.
text: We only used AI at the sentence level (e.g., fixing grammar, finding synonyms for words...).

heading: Future Work
text: We leave these to future works