SlowGuess/NAACL_2021_OCR huggingface dataset:
Chong Zhang Jieyu Zhao Huan Zhang Kai-Wei Chang Cho-Jui Hsieh
Department of Computer Science, UCLA
{chongz, jyzhao, kwchang, chohsieh} @cs.ucla.edu, huan@huan-zhang.com
Robustness and counterfactual bias are usually evaluated on a test dataset. However, are these evaluations robust? If the test dataset is perturbed slightly, will the evaluation results keep the same? In this paper, we propose a "double perturbation" framework to uncover model weaknesses beyond the test dataset. The framework first perturbs the test dataset to construct abundant natural sentences similar to the test data, and then diagnoses the prediction change regarding a single-word substitution. We apply this framework to study two perturbation-based approaches that are used to analyze models' robustness and counterfactual bias in English. (1) For robustness, we focus on synonym substitutions and identify vulnerable examples where prediction can be altered. Our proposed attack attains high success rates  $(96.0\% - 99.8\%)$  in finding vulnerable examples on both original and robustly trained CNNs and Transformers. (2) For counterfactual bias, we focus on substituting demographic tokens (e.g., gender, race) and measure the shift of the expected prediction among constructed sentences. Our method is able to reveal the hidden model biases not directly shown in the test dataset. Our code is available at https://github.com/chong-z/nlp-second-order-attack.
Recent studies show that NLP models are vulnerable to adversarial perturbations. A seemingly "invariance transformation" (a.k.a. adversarial perturbation) such as synonym substitutions (Alzantot et al., 2018; Zang et al., 2020) or syntax-guided paraphrasing (Iyyer et al., 2018; Huang and Chang, 2021) can alter the prediction. To mitigate the model vulnerability, robust training methods have been proposed and shown effective (Miyato et al., 2017; Jia et al., 2019; Huang et al., 2019; Zhou et al., 2020).
Figure 1: A vulnerable example beyond the test dataset. Numbers on the bottom right are the sentiment predictions for film and movie. Blue  $x_0$  comes from the test dataset and its prediction cannot be altered by the substitution film → movie (robust). Yellow example  $\tilde{x}_0$  is slightly perturbed but remains natural. Its prediction can be altered by the substitution (vulnerable).
In most studies, model robustness is evaluated based on a given test dataset or synthetic sentences constructed from templates (Ribeiro et al., 2020). Specifically, the robustness of a model is often evaluated by the ratio of test examples where the model prediction cannot be altered by semantic-invariant perturbation. We refer to this type of evaluations as the first-order robustness evaluation. However, even if a model is first-order robust on an input sentence  $x_0$ , it is possible that the model is not robust on a natural sentence  $\tilde{x}_0$  that is slightly modified from  $x_0$ . In that case, adversarial examples still exist even if first-order attacks cannot find any of them from the given test dataset. Throughout this paper, we call  $\tilde{x}_0$  a vulnerable example. The existence of such examples exposes weaknesses in models' understanding and presents challenges for model deployment. Fig. 1 illustrates an example.
In this paper, we propose the double perturbation framework for evaluating a stronger notion of second-order robustness. Given a test dataset, we consider a model to be second-order robust if there is no vulnerable example that can be identified in the neighborhood of given test instances
Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies, pages 3899-3916 June 6-11, 2021. ©2021 Association for Computational Linguistics
$(\S 2.2)$ . In particular, our framework first perturbs the test set to construct the neighborhood, and then diagnoses the robustness regarding a single-word synonym substitution. Taking Fig. 2 as an example, the model is first-order robust on the input sentence  $x_0$  (the prediction cannot be altered), but it is not second-order robust due to the existence of the vulnerable example  $\tilde{x}_0$ . Our framework is designed to identify  $\tilde{x}_0$ .
We apply the proposed framework and quantify second-order robustness through two second-order attacks (§3). We experiment with English sentiment classification on the SST-2 dataset (Socher et al., 2013) across various model architectures. Surprisingly, although robustly trained CNN (Jia et al., 2019) and Transformer (Xu et al., 2020) can achieve high robustness under strong attacks (Alzantot et al., 2018; Garg and Ramakrishnan, 2020) (23.0%–71.6% success rates), for around 96.0% of the test examples our attacks can find a vulnerable example by perturbing 1.3 words on average. This finding indicates that these robustly trained models, despite being first-order robust, are not second-order robust.
Furthermore, we extend the double perturbation framework to evaluate counterfactual biases (Kusner et al., 2017) ( $\S 4$ ) in English. When the test dataset is small, our framework can help improve the evaluation robustness by revealing the hidden biases not directly shown in the test dataset. Intuitively, a fair model should make the same prediction for nearly identical examples referencing different groups (Garg et al., 2019) with different protected attributes (e.g., gender, race). In our evaluation, we consider a model biased if substituting tokens associated with protected attributes changes the expected prediction, which is the average prediction among all examples within the neighborhood. For instance, a toxicity classifier is biased if it tends to increase the toxicity if we substitute straight  $\rightarrow$  gay in an input sentence (Dixon et al., 2018). In the experiments, we evaluate the expected sentiment predictions on pairs of protected tokens (e.g., (he, she), (gay, straight)), and demonstrate that our method is able to reveal the hidden model biases.
Our main contributions are: (1) We propose the double perturbation framework to diagnose the robustness of existing robustness and fairness evaluation methods. (2) We propose two second-order attacks to quantify the stronger notion of second-
Figure 2: An illustration of the decision boundary. Diamond area denotes invariance transformations. Blue  $x_0$  is a robust input example (the entire diamond is green). Yellow  $\tilde{x}_0$  is a vulnerable example in the neighborhood of  $x_0$ . Red  $\tilde{x}_0'$  is an adversarial example to  $\tilde{x}_0$ . Note:  $\tilde{x}_0'$  is not an adversarial example to  $x_0$  since they have different meanings to human (outside the diamond).
order robustness and reveal the models' vulnerabilities that cannot be identified by previous attacks. (3) We propose a counterfactual bias evaluation method to reveal the hidden model bias based on our double perturbation framework.
2 The Double Perturbation Framework
In this section, we describe the double perturbation framework which focuses on identifying vulnerable examples within a small neighborhood of the test dataset. The framework consists of a neighborhood perturbation and a word substitution. We start with defining word substitutions.
2.1 Existing Word Substitution Strategy
We focus our study on word-level substitution, where existing works evaluate robustness and counterfactual bias by directly perturbing the test dataset. For instance, adversarial attacks alter the prediction by making synonym substitutions, and the fairness literature evaluates counterfactual fairness by substituting protected tokens. We integrate the word substitution strategy into our framework as the component for evaluating robustness and fairness.
For simplicity, we consider a single-word substitution and denote it with the operator  $\oplus$ . Let  $\mathcal{X} \subseteq \mathcal{V}^l$  be the input space where  $\mathcal{V}$  is the vocabulary and  $l$  is the sentence length,  $\pmb{p} = (p^{(1)}, p^{(2)}) \in \mathcal{V}^2$  be a pair of synonyms (called patch words),  $\mathcal{X}_p \subseteq \mathcal{X}$  denotes sentences with a single occurrence of  $p^{(1)}$  (for simplicity we skip other sentences),  $x_0 \in \mathcal{X}_p$  be an input sentence, then  $x_0 \oplus p$  means "substitute  $p^{(1)} \to p^{(2)}$  in  $x_0$ ". The result after substitution is:
$$
x _ {0} ^ {\prime} = x _ {0} \oplus \boldsymbol {p}.
$$
Taking Fig. 1 as an example, where  $\pmb{p} =$  (film, movie) and  $x_0 = a$  deep and meaningful film, the perturbed sentence is  $x_0' = a$  deep and meaningful movie. Now we introduce other components in our framework.
2.2 Proposed Neighborhood Perturbation
Instead of applying the aforementioned word substitutions directly to the original test dataset, our framework perturbs the test dataset within a small neighborhood to construct similar natural sentences. This is to identify vulnerable examples with respect to the model. Note that examples in the neighborhood are not required to have the same meaning as the original example, since we only study the prediction difference caused by applying synonym substitution  $p$  (§2.1).
Constraints on the neighborhood. We limit the neighborhood sentences within a small  $\ell_0$  norm ball (regarding the test instance) to ensure syntactic similarity, and empirically ensure the naturalness through a language model. The neighborhood of an input sentence  $x_0\in \mathcal{X}$  is:
$$
\operatorname {N e i g h b o r} _ {k} \left(x _ {0}\right) \subseteq \operatorname {B a l l} _ {k} \left(x _ {0}\right) \cap \mathcal {X} _ {\text {n a t u r a l}}, \tag {1}
$$
where  $\mathrm{Ball}_k(x_0) = \{x\mid \| x - x_0\| _0\leq k,x\in \mathcal{X}\}$  is the  $\ell_0$  norm ball around  $x_0$  (i.e., at most  $k$  different tokens), and  $\mathcal{X}_{\mathrm{natur}}$  denotes natural sentences that satisfy a certain language model score which will be discussed next.
Construction with masked language model. We construct neighborhood sentences from  $x_0$  by substituting at most  $k$  tokens. As shown in Algorithm 1, the construction employs a recursive approach and replaces one token at a time. For each recursion, the algorithm first masks each token of the input sentence (may be the original  $x_0$  or the  $\tilde{x}$  from last recursion) separately and predicts likely replacements with a masked language model (e.g., DistilBERT, Sanh et al. 2019). To ensure the naturalness, we keep the top 20 tokens for each mask with the largest logit (subject to a threshold, Line 9). Then, the algorithm constructs neighborhood sentences by replacing the mask with found tokens. We use the notation  $\tilde{x}$  in the following sections to denote the constructed sentences within the neighborhood.
3 Evaluating Second-Order Robustness
With the proposed double perturbation framework, we design two black-box attacks<sup>1</sup> to identify vulnerable examples within the neighborhood of the test set. We aim at evaluating the robustness for inputs beyond the test set.
3.1 Previous First-Order Attacks
Adversarial attacks search for small and invariant perturbations on the model input that can alter the prediction. To simplify the discussion, in the following, we take a binary classifier  $f(x): \mathcal{X} \to \{0,1\}$  as an example to describe our framework. Let  $x_0$  be the sentence from the test set with label  $y_0$ , then the smallest perturbation  $\delta^*$  under  $\ell_0$  norm distance is:2
$$
\delta^ {*} := \underset {\delta} {\operatorname {a r g m i n}} \| \delta \| _ {0} \text {s . t .} f (x _ {0} \oplus \delta) \neq y _ {0}.
$$
Here  $\delta = p_1 \oplus \dots \oplus p_l$  denotes a series of substitutions. In contrast, our second-order attacks fix  $\delta = p$  and search for the vulnerable  $x_0$ .
3.2 Proposed Second-Order Attacks
Second-order attacks study the prediction difference caused by applying  $\pmb{p}$ . For notation convenience we define the prediction difference  $F(x; \pmb{p})$ :
1 Black-box attacks only observe the model outputs and do not know the model parameters or the gradient.
For simplicity, we use  $\ell_0$  norm distance to measure the similarity, but other distance metrics can be applied.
Figure 3: The attack flow for SO-Beam (Algorithm 2). Blue  $x_0$  is the input sentence and yellow  $\tilde{x}_0$  is our constructed vulnerable example (the prediction can be altered by substituting film → movie). Green boxes in the middle show intermediate sentences, and  $f_{\mathrm{soft}}(x)$  denotes the probability outputs for film and movie.
$$
\mathcal {X} \times \mathcal {V} ^ {2} \rightarrow \{- 1, 0, 1 \} \text {b y :} ^ {3}
$$
$$
F (x; \boldsymbol {p}) := f (x \oplus \boldsymbol {p}) - f (x). \tag {2}
$$
Taking Fig. 1 as an example, the prediction difference for  $\tilde{x}_0$  on  $\pmb{p}$  is  $F(\tilde{x}_0; \pmb{p}) = f(\dots \text{moving movie.}) - f(\dots \text{moving film.}) = -1$ .
Given an input sentence  $x_0$ , we want to find patch words  $\pmb{p}$  and a vulnerable example  $\tilde{x}_0$  such that  $f(\tilde{x}_0 \oplus \pmb{p}) \neq f(\tilde{x}_0)$ . Follow Alzantot et al. (2018), we choose  $\pmb{p}$  from a predefined list of counter-fitted synonyms (Mrkšić et al., 2016) that maximizes  $|f_{\mathrm{soft}}(p^{(2)}) - f_{\mathrm{soft}}(p^{(1)})|$ . Here  $f_{\mathrm{soft}}(x): \mathcal{X} \to [0,1]$  denotes probability output (e.g., after the softmax layer but before the final argmax),  $f_{\mathrm{soft}}(p^{(1)})$  and  $f_{\mathrm{soft}}(p^{(2)})$  denote the predictions for the single word, and we enumerate through all possible  $\pmb{p}$  for  $x_0$ . Let  $k$  be the neighborhood distance, then the attack is equivalent to solving:
$$
\tilde {x} _ {0} = \underset {x \in \operatorname {N e i g h b o r} _ {k} \left(x _ {0}\right)} {\operatorname {a r g m a x}} | F (x; \boldsymbol {p}) |. \tag {3}
$$
Brute-force attack (SO-Enum). A naive approach for solving Eq. (3) is to enumerate through  $\operatorname{Neighbor}_k(x_0)$ . The enumeration finds the smallest perturbation, but is only applicable for small  $k$  (e.g.,  $k \leq 2$ ) given the exponential complexity.
Beam-search attack (SO-Beam). The efficiency can be improved by utilizing the probability output, where we solve Eq. (3) by minimizing the cross-entropy loss with regard to  $x \in \mathrm{Neighbor}_k(x_0)$ :
$$
\mathcal {L} (x; \boldsymbol {p}) := - \log \left(1 - f _ {\min }\right) - \log \left(f _ {\max }\right), \tag {4}
$$
where  $f_{\mathrm{min}}$  and  $f_{\mathrm{max}}$  are the smaller and the larger output probability between  $f_{\mathrm{soft}}(x)$  and  $f_{\mathrm{soft}}(x \oplus$
$\pmb{p}$ ), respectively. Minimizing Eq. (4) effectively leads to  $f_{\mathrm{min}} \to 0$  and  $f_{\mathrm{max}} \to 1$ , and we use a beam search to find the best  $x$ . At each iteration, we construct sentences through  $\mathrm{Neighbor}_1(x)$  and only keep the top 20 sentences with the smallest  $\mathcal{L}(x; \pmb{p})$ . We run at most  $k$  iterations, and stop earlier if we find a vulnerable example. We provide the detailed implementation in Algorithm 2 and a flowchart in Fig. 3.
In this section, we evaluate the second-order robustness of existing models and show the quality of our constructed vulnerable examples.
3.3.1 Setup
We follow the setup from the robust training literature (Jia et al., 2019; Xu et al., 2020) and experiment with both the base (non-robust) and robustly trained models. We train the binary sentiment classifiers on the SST-2 dataset with bag-of-words (BoW), CNN, LSTM, and attention-based
3We assume a binary classification task, but our framework is general and can be extended to multi-class classification.
Original: 70% Negative
Input Example: in its best moments, resembles a bad high school production of grease, without benefit of song.
Genetic: 56% Positive
Adversarial Example: in its best moment, recalling a naughty high school production of lubrication, unless benefit of song.
BAE: 56% Positive
Adversarial Example: in its best moments, resembles a great high school production of grease, without benefit of song.
SO-Enum and SO-Beam (ours): 60% Negative (67% Positive)
Vulnerable Example: in its best moments, resembles a bad (unhealthy) high school production of musicals, without benefit of song.
Table 1: Sampled attack results on the robust BoW. For Genetic and BAE the goal is to find an adversarial example that alters the original prediction, whereas for SO-Enum and SO-Beam the goal is to find a vulnerable example beyond the test set such that the prediction can be altered by substituting bad  $\rightarrow$  unhealthy.
Base models. For BoW, CNN, and LSTM, all models use pre-trained GloVe embeddings (Pennington et al., 2014), and have one hidden layer of the corresponding type with 100 hidden size. Similar to the baseline performance reported in GLUE (Wang et al., 2019), our trained models have an evaluation accuracy of  $81.4\%$ ,  $82.5\%$ , and  $81.7\%$ , respectively. For attention-based models, we train a 3-layer Transformer (the largest size in Shi et al. 2020) and fine-tune a pre-trained bert-base-uncased from HuggingFace (Wolf et al., 2020). The Transformer uses 4 attention heads and 64 hidden size, and obtains  $82.1\%$  accuracy. The BERT-base uses the default configuration and obtains  $92.7\%$  accuracy.
Robust models (first-order). With the same setup as base models, we apply robust training methods to improve the resistance to word substitution attacks. Jia et al. (2019) provide a provably robust training method through Interval Bound Propagation (IBP, Dvijotham et al. 2018) for all word substitutions on BoW, CNN and LSTM. Xu et al. (2020) provide a provably robust training method on general computational graphs through a combination of forward and backward linear bound propagation, and the resulting 3-layer Transformer is robust to up to 6 word substitutions. For both works we use the same set of counter-fitted synonyms provided in Jia et al. (2019). We skip BERT-base due to the lack of an effective robust training method.
Attack success rate (first-order). We quantify first-order robustness through attack success rate, which measures the ratio of test examples that an adversarial example can be found. We use first-order attacks as a reference due to the lack of a direct baseline. We experiment with two black-box attacks: (1) The Genetic attack (Alzantot et al., 2018; Jia et al., 2019) uses a population-based op
tization algorithm that generates both syntactically and semantically similar adversarial examples, by replacing words within the list of counterfitted synonyms. (2) The BAE attack (Garg and Ramakrishnan, 2020) generates coherent adversarial examples by masking and replacing words using BERT. For both methods we use the implementation provided by TextAttack (Morris et al., 2020).
Attack success rate (second-order). We also quantify second-order robustness through attack success rate, which measures the ratio of test examples that a vulnerable example can be found. To evaluate the impact of neighborhood size, we experiment with two configurations: (1) For the small neighborhood  $(k = 2)$ , we use SO-Enum that finds the most similar vulnerable example. (2) For the large neighborhood  $(k = 6)$ , SO-Enum is not applicable and we use SO-Beam to find vulnerable examples. We consider the most challenging setup and use patch words  $p$  from the same set of counter-fitted synonyms as robust models (they are provably robust to these synonyms on the test set). We also provide a random baseline to validate the effectiveness of minimizing Eq. (4) (Appendix A.1).
Quality metrics (perplexity and similarity). We quantify the quality of our constructed vulnerable examples through two metrics: (1) GPT-2 (Radford et al., 2019) perplexity quantifies the naturalness of a sentence (smaller is better). We report the perplexity for both the original input examples and the constructed vulnerable examples. (2)  $\ell_0$  norm distance quantifies the disparity between two sentences (smaller is better). We report the distance between the input and the vulnerable example. Note that first-order attacks have different objectives and thus cannot be compared directly.
Attack Success Rate (%)
Genetic	BAE	SO-Enum	SO-Beam
Base Models:
BoW	57.0	69.7	95.3	99.7
CNN	62.0	71.0	95.3	99.8
LSTM	60.0	68.3	95.8	99.5
Transformer	73.0	74.3	95.4	98.0
BERT-base	41.0	61.5	94.3	98.7
Robust Models:
BoW	28.0	63.1	81.5	88.4
CNN	23.0	64.4	91.0	96.0
LSTM	24.0	61.0	62.9	77.5
Transformer	56.0	71.6	91.2	96.2
We experiment with the validation split (872 examples) on a single RTX 3090. The average running time per example (in seconds) on base LSTM is 31.9 for Genetic, 1.1 for BAE, 7.0 for SO-Enum  $(k = 2)$ , and 1.9 for SO-Beam  $(k = 6)$ . We provide additional running time results in Appendix A.3. Table 1 provides an example of the attack result where all attacks are successful (additional examples in Appendix A.5). As shown, our second-order attacks find a vulnerable example by replacing grease  $\rightarrow$  musicals, and the vulnerable example has different predictions for bad and unhealthy. Note that, Genetic and BAE have different objectives from second-order attacks and focus on finding the adversarial example. Next we discuss the results from two perspectives.
Second-order robustness. We observe that existing robustly trained models are not second-order robust. As shown in Table 2, our second-order attacks attain high success rates not only on the base models but also on the robustly trained models. For instance, on the robustly trained CNN and Transformer, SO-Beam finds vulnerable examples within a small neighborhood for around  $96.0\%$  of the test examples, even though these models have improved resistance to strong first-order attacks (success rates drop from  $62.0\% -74.3\%$  to  $23.0\% -71.6\%$  for Genetic and BAE). This phenomenon can be explained by the fact that both first-order attacks and robust training methods focus on synonym substitutions on the test set, whereas our attacks, due to their second-order nature, find vul
Table 2: The average rates over 872 examples (100 for Genetic due to long running time). Second-order attacks achieve higher successful rate since they are able to search beyond the test set.
SO-Enum	SO-Beam
Original PPL	Perturb PPL	\( \ell_0 \)	Original PPL	Perturb PPL	\( \ell_0 \)
Base Models:
BoW	168	202	1.1	166	202	1.2
CNN	170	204	1.1	166	201	1.2
LSTM	168	204	1.1	166	204	1.2
Transformer	165	193	1.0	165	195	1.1
BERT-base	170	229	1.3	168	222	1.4
Robust Models:
BoW	170	212	1.2	171	222	1.4
CNN	166	209	1.2	168	210	1.3
LSTM	194	251	1.3	185	260	1.8
Transformer	170	213	1.2	165	208	1.3
Table 3: The quality metrics for second-order methods. We report the median perplexity (PPL) and average  $\ell_0$  norm distance. The original PPL may differ across models since we only count successful attacks.
nerable examples beyond the test set, and the search is not required to maintain semantic similarity. Our methods provide a way to further investigate the robustness (or find vulnerable and adversarial examples) even when the model is robust to the test set.
Quality of constructed vulnerable examples. As shown in Table 3, second-order attacks are able to construct vulnerable examples by perturbing 1.3 words on average, with a slightly increased perplexity. For instance, on the robustly trained CNN and Transformer, SO-Beam constructs vulnerable examples by perturbing 1.3 words on average, with the median<sup>5</sup> perplexity increased from around 165 to around 210. We provide metrics for first-order attacks in Appendix A.5 as they have different objectives and are not directly comparable.
Furthermore, applying existing attacks on the vulnerable examples constructed by our method will lead to much smaller perturbations. As a reference, on the robustly trained CNN, Genetic attack constructs adversarial examples by perturbing 2.7 words on average (starting from the input examples). However, if Genetic starts from our vulnerable examples, it would only need to perturb a single word (i.e., the patch words  $\pmb{p}$ ) to alter the prediction. These results demonstrate the weakness of the models (even robustly trained) for those inputs beyond the test set.
3.3.3 Human Evaluation