PromptRobust: Towards Evaluating the Robustness of Large Language Models on Adversarial Prompts
Kaijie Zhu, Jindong Wang, Jiaheng Zhou, Zichen Wang, Hao Chen, Yidong Wang, Linyi Yang, Wei Ye, Yue Zhang, Neil Zhenqiang Gong, Xing Xie
Introduction
Large language models (LLMs) have gained increasing popularity owing to their unprecedented performance in various tasks such as sentiment analysis , question answering , logical reasoning , etc. An input to an LLM is the concatenation of a prompt and (optionally) a sample, where the prompt aims to instruct the LLM what task to perform and the sample is the data to be analyzed in the task. Given an input, an LLM returns a response. Figure 1 shows several examples of prompt, sample, and response when different users use LLMs for different tasks. Note that a sample is optional in certain tasks. For instance, in a task to write a country love story, a prompt “Please write a story about country love” alone is sufficient.
Given the popular adoption of LLMs, particularly in safety-critical and decision-making domains, it becomes essential to examine the robustness of LLMs to perturbations in an input. Indeed, existing work has attempted to evaluate the robustness of LLMs from different perspectives. For instance, AdvGLUE and ANLI are two public datasets to evaluate the robustness of language models to adversarial samples, which are carefully perturbed samples to make a language model produce incorrect responses. In the era of large language models, Wang et al. evaluated ChatGPT and other LLMs with respect to their robustness to adversarial samples and out-of-distribution (OOD) samples. Zhuo et al. evaluated the robustness of LLMs for a particular task called semantic parsing.
These studies demonstrated that current LLMs are not robust to adversarial and OOD samples for some popular natural language processing tasks. However, in some application scenarios, an input only consists of a prompt without the need of a sample, making existing studies on robustness to adversarial samples not applicable. Moreover, a single prompt is often used to instruct an LLM to perform a task for multiple samples. For instance, in a math-problem task (shown in Figure 1), a prompt can be used for multiple samples (i.e., math problems). Therefore, a perturbed prompt may make an LLM output incorrect responses for multiple clean samples. As a result, a perturbed prompt arguably has a larger impact on LLMs than an adversarial sample, since the latter only influences the response of an LLM for a single sample. However, despite its pivotal importance, the robustness of LLMs to perturbations in prompts is largely unexplored.
In this paper, we aim to bridge the gap by introducing PromptBench, a comprehensive benchmark designed for evaluating the robustness of LLMs to perturbations in prompts, understanding the factors that contribute to their robustness (or lack thereof), and identifying the key attributes of robust prompts. We consider a variety of prompt perturbations including 1) minor typos, synonyms, and different ways to express sentences with the same semantic meaning, which may commonly occur to normal users or developers in their daily use of LLMs in non-adversarial settings, as well as 2) perturbations strategically crafted by attackers in adversarial settings. With a slight abuse of terminology, we call such a perturbed prompt in both scenarios adversarial prompt. Figure 1 shows examples of adversarial prompts with typos and synonyms, for which the LLMs produce incorrect responses.
As shown in Figure 2, PromptBench consists of prompts, attacks, models, tasks, datasets, and analysis. Specifically, we evaluate types of prompts: zero-shot (ZS), few-shot (FS), role-oriented, and task-oriented prompts. We create types of attacks (called prompt attacks) to craft adversarial prompts: character-level, word-level, sentence-level, and semantic-level attacks by extending adversarial attacks that were originally designed to generate adversarial samples. We note that, although we call them attacks, their generated adversarial prompts also serve as testbeds for mimicking potential diverse prompts with naturally occurred perturbations from real LLM users. PromptBench spans across prevalent LLMs, ranging from smaller models such as Flan-T5-large to larger ones like ChatGPT and GPT-4 . Moreover, we select tasks for evaluation, namely, sentiment analysis (SST-2 ), grammar correctness (CoLA ), duplicate sentence detection (QQP and MRPC ), natural language inference (MNLI , QNLI , RTE , and WNLI ), multi-task knowledge (MMLU ), reading comprehension (SQuAD V2 ), translation (UN Multi and IWSLT 2017 ), and math problem-solving (Mathematics ). In total, we created adversarial prompts, representing diverse, practical, and challenging scenarios.
We carry out extensive experiments and analysis using PromptBench. The results highlight a prevailing lack of robustness to adversarial prompts among current LLMs, with word-level attacks proving the most effective ( average performance drop in all tasks). We delve into the reasons behind this vulnerability by exploring LLMs’ attention weights of each word in inputs for erroneous responses associated with clean and adversarial inputs, where an adversarial input is the concatenation of an adversarial prompt and a clean sample. Our findings reveal that adversarial prompts cause LLMs to shift their focus towards the perturbed elements thus producing wrong responses. We also examine the transferability of adversarial prompts between models, and suggest a successful transferability of adversarial prompts from one LLM to another. Furthermore, we analyze word frequency patterns to guide future research in improving robustness and to aid end-users in crafting more robust prompts. We conclude by discussing potential strategies for robustness enhancement.
To summarize, our contributions are as follows:
We introduce PromptBench, the first systematic benchmark for evaluating, understanding, and analyzing the robustness of LLMs to adversarial prompts.
We conduct comprehensive evaluations on the robustness of LLMs to adversarial prompts and perform extensive analysis, including visual explanations for the observed vulnerabilities, transferability analysis of adversarial prompts, and word frequency analysis to offer practical guidance for downstream users and prompt engineers to craft more robust prompts.
In an effort to stimulate future research on LLMs’ robustness, we also build a visualization website (Appendix E) to allow for easy exploration of adversarial prompts. We will make our code, compiled prompts, website, and evaluation benchmark available to the public.
PromptBench
In this section, we introduce the basic modules of PromptBench: prompts, models, tasks, datasets, attacks, and analysis.
We investigate four different types of prompts categorized based on their intended purpose and the amount of labeled samples they require. Task-oriented prompts explicitly describe the task the model is required to perform, which encourages the model to generate task-specific outputs based solely on its pre-training knowledge. While role-oriented prompts typically frame the model as an entity with a specific role, such as an expert, advisor, or translator. By incorporating role information, these prompts aim to implicitly convey the expected output format and behavior. Each of the two categories of prompts can be designed for both zero-shot (ZS) and few-shot (FS) learning scenarios. In the zero-shot scenario, an input is defined as , where denotes a prompt, is a sample, and $[P,E,x]EE=\{[x_{1},y_{1}],[x_{2},y_{2}],[x_{3},y_{3}]\}$ represents three examples in a three-shot learning scenario. In our experiments, we randomly select three examples in the training set of a task and append them to a prompt. Table 1 shows examples of different types of prompts.
Our evaluation includes a diverse set of LLMs to comprehensively assess their performance across various tasks and domains. The models we consider are as follows: Flan-T5-large (0.8B), Dolly-6B , Vicuna-13B , Llama2-13b-chat , Cerebras-GPT-13B , GPT-NEOX-20B , Flan-UL2 (20B) , ChatGPT , and GPT-4 .We did not perform prompt attacks on GPT-4 by optimizing the adversarial algorithms since it requires massive rounds of communications and is too costly. We used the adversarial prompts generated by ChatGPT to evaluate GPT-4 since the adversarial prompts can be transferred (Sec. 4.4). By incorporating LLMs with different architectures and sizes, we aim to provide insights into their strengths and weaknesses, ultimately facilitating model selection for a specific application or use case. Details of these LLMs are in Appendix A.1. Note that PromptBench is flexible and supports all other LLMs by simply extending the interface.
2 Attacks
Multiple textual adversarial attacks were designed to generate adversarial samples . Technically speaking, given a single sample and its ground-truth label , a textual adversarial attack aims to find a perturbation such that an LLM produces an incorrect response. Formally, is found by solving the following optimization problem: , where is the adversarial sample, is the response of the LLM when taking the adversarial sample alone as input, indicates the constraints for the perturbation , and represents a loss function.
In this paper, our focus is to attack the prompts rather than samples. This is due to the popularity of LLMs in different applications, which generate responses using in-context learning on prompts (i.e., instructions) and samples. Prompts are either input by users or generated by the system or developers. Moreover, the ultimate purpose of performing such “attack” is actually not to genuinely attack the models, but to simulate possible perturbations that may naturally occur in real situations. Table 2 shows multiple prompts generated by adversarial approaches that are used to mimic possible user prompts, which are popular errors or expressions made by users. Since users can make different mistakes while inputting prompts, such as typos, different word usage, different sentence styles, etc., the study on the prompt robustness is necessary to understand LLMs.
We denote an input to LLMs as , where is a prompt, is a sample, and $x[P,x]\mathcal{D}=\{(x_{i},y_{i})\}_{i\in[N]}NPf_{\theta}\mathcal{D}$. Formally, we define a prompt attack as follows:
Given an LLM , a dataset , and a clean prompt , the objective of a prompt attack can be formulated as follows:
where is the textual perturbation added to the clean prompt and is the allowable perturbation set, i.e., perturbation constraint. We note that this attack is analogous to universal adversarial perturbation (UAP) and universal adversarial trigger (UAT) , extending these concepts to the realm of prompts.
2.2 Different attacks
We then modify the existing black-box textual attacks to implement Eq. (1) due to their efficiency and no reliance on the model gradient. Thus, both open-sourced and proprietary LLMs can be the attack targets. Our instantiations span four distinct levels, capturing a broad spectrum of complexities from simple character manipulations to sophisticated semantic alterations. The example of each attack is presented in Table 2. The details of each attack are shown in Appendix B.1.
Character-level: We employ TextBugger and DeepWordBug , which manipulate texts by introducing typos or errors to words, e.g., by adding, deleting, repeating, replacing, and permuting characters for certain words.
Word-level: We use BertAttack and TextFooler , which aim to replace words with synonyms or contextually similar words to deceive LLMs.
Sentence-level: We implement StressTest and CheckList , which append irrelevant or extraneous sentences to the end of prompts, intending to distract LLMs. For the StressTest attack, we adopt similar settings to those in , appending “and true is true”, “and false is not true”, or “and true is true” for five times to the end of a prompt. For the CheckList attack, we generate random sequences consisting of alphabets and digits, each with a length of , and append this random sequence to the end of a prompt.
Semantic-level: We simulate the linguistic behavior of people from different countries by choosing common languages (Chinese, French, Arabic, Spanish, Japanese, and Korean) and constructing prompts for each language per dataset. These prompts are then translated into English, introducing linguistic nuances and variations that could potentially impact LLMs.
Note that in the context of character-level and word-level adversarial attacks, the attack algorithms initiate by ascertaining the importance of each word within the prompt (except those task-essential words mentioned below). We determine a word’s importance by removing it and observing how much the prediction accuracy drops. A substantial drop in the score signifies the word’s criticality to the prompt. Proceeding from the most salient word, the algorithm proposes alternative perturbations for each word; for instance, selecting synonyms in word-level attacks. Each alternative is then assessed to gauge its potential to impair the model’s performance. This evaluative process continues iteratively until the predetermined attack objective is achieved or there are no more alternatives for each word. In the realm of sentence-level and semantic-level attacks, the methodology is straightforward: each adversarial prompt is assessed using its respective attack algorithm, and the most effective in undermining the model is selected.
We impose additional restrictions on the perturbations, prohibiting alterations to certain task-essential words. For instance, in translation tasks, the word ‘translation’ is preserved, while for sentiment classification tasks, pivotal sentiment labels such as ‘positive’ and ‘negative’ remain untouched. Moreover, in the few-shot learning scenario, the few-shot examples are also exempt from adversarial attacks.
2.3 Semantic-preserving of adversarial prompts
Are adversarial prompts realistic? The aim of prompt attacks is to simulate plausible user errors; thus, it is imperative that these prompts preserve semantic integrity, ensuring they remain both acceptable and imperceptible to human comprehension. Therefore, it is of paramount importance that our adversarially engineered prompts retain coherence and realism, thereby ensuring a practical relevance to our research in the context of real-world language model applications.
To address the challenges associated with word-level attacks, we have diligently fine-tuned the hyperparameters of each attack approach, thus striving to maintain semantic continuity. Then, we conduct a human study to recruit five volunteers to judge if the generated adversarial prompts can preserve semantics. The evaluators were presented with the original prompt juxtaposed with its adversarial version , and were tasked with determining their semantic congruence. Sentence-level attacks are excluded in this study since they do not change the original prompts, but only to add extra perturbations in the end. The detailed requirements and examples of acceptable and unacceptable prompts are shown in Appendix F. The results in Figure 3 demonstrate that these adversarial prompts generated by character-level, word-level and semantic-level attacks are at least acceptable by humans, indicating that our attack is realistic and meaningful.
3 Tasks and datasets
Currently, PromptBench consists of diverse tasks with public datasets (details are in Appendix A.2) and new datasets can be easily integrated:
Sentiment analysis: we adopt the SST-2 dataset from the GLUE dataset.
Grammar correctness: we adopt the CoLA dataset from the GLUE dataset.
Duplicate sentence detection: we adopt the QQP and MRPC datasets from GLUE.
Natural language inference: MNLI , QNLI , RTE , and WNLI from GLUE.
Multi-task knowledge: we adopt the MMLU dataset which evaluates world knowledge and problem-solving abilities through 57 tasks with multiple-choice questions from diverse domains.
Reading comprehension: we adopt the SQuAD V2 dataset . SQuAD V2 enhances the original SQuAD dataset for machine reading comprehension by introducing unanswerable questions.
Translation: we adopt UN Multi and IWSLT 2017 datasets. UN Multi evaluates LLMs’ ability to translate official documents, while IWSLT 2017 evaluates spoken language translation.
Math problem-solving: we adopt the Math dataset, which evaluates LLMs’ mathematical reasoning abilities across a diverse range of problems, such as algebra, arithmetic and comparison.
4 Analysis
In addition to providing benchmark results using the models, prompts, datasets, and attacks, PromptBench offers extensive analysis to not only evaluate, but also understand the robustness of LLMs. Specifically, PromptBench presents gradient-based visualization analysis in PromptBench to understand the rational behind the adversarial robustness (Sec. 4.3). Then, PromptBench offers transferability analysis between LLMs to understand if adversarial prompts from one LLM can be transferred to another (Sec. 4.4). Next, PromptBench supports word frequency analysis to offer a practical guidance to both LLM developers and end-users in writing robust prompts based on our experiments (Sec. 4.6). To sum up, PromptBench is a flexible evaluation framework for LLMs not only tailored for adversarial robustness, but can be extended to other evaluation research in LLMs.
Experiments
The extensive computational requirements of generating one adversarial prompt necessitates iterating over the entire dataset times in average. Thus, the evaluation on an entire dataset using LLMs is unfeasible. To alleviate the computation constraint and preserve a fair study process, we adopt a sampling strategy that entails selecting a subset of samples from the validation or test sets across various datasets. The statistics of each dataset and tasks are summarized in Table 3.In Table 3, the last column denotes the total evaluation sample size for each dataset on each model. For instance, there are test samples in SST-2 dataset and each sample should go through adversarial attacks on types of prompts, each with prompts, thus the test size for each model is .
Specifically, for the GLUE datasets, we sample 1,000 instances when the validation set exceeds this size; otherwise, we utilize the entire validation set. With respect to ChatGPT and GPT4, we adopt a smaller sample size of 200 instances for computational efficiency. For the MMLU dataset, we select 10 instances for each of the 57 tasks if the validation set exceeds this size; if not, the entire validation set is used. For the SQUAD V2 dataset, we randomly select 200 validation instances. Regarding the translation datasets UN Multi and IWSLT 2017, we focus on three languages—English, French, and German, which are primarily supported by T5-large and UL2. We select a total of 100 validation instances, evenly distributed among all possible translation pairs, e.g., English to French. For the Math dataset, we select 20 types of math problems, choosing either 5 or 10 instances per type, resulting in a total of 160 instances. This sampling strategy ensures the formation of a manageable and representative evaluation set for each dataset, thereby enabling an effective assessment of the performance and robustness of LLMs across various tasks and domains.
We initially assess the performance of all LLMs without prompt attacks to provide a performance baseline. We find that certain LLMs even do not demonstrate satisfactory performance with clean prompts, narrowing our selection to LLMs: Flan-T5-large, Vicuna-13B, Llama2-13B-chat, UL2, ChatGPT, and GPT-4. Further details and discussions on clean prompt performance across all LLMs are available in Appendix C. We generate distinct prompts for both role-oriented and task-oriented categories. Each prompt can be augmented with three examples, forming the few-shot prompts. In total, we have prompts for each dataset on each LLM. For better efficiency and performance, we select the top best-performing prompts of each type to conduct prompt attacks. As a result, we evaluate the adversarial vulnerabilities of LLMs across datasets, encompassing a total of prompts , where the numbers on the R.H.S. denote #attacked prompts, #prompt types, #LLMs, #datasets, and #attacks, respectively. We did not conduct attacks on Vicuna, Llama2-13B-chat on certain datasets because the outputs of these datasets are meaningless, so that we subtract prompts. and their respective adversarial counterparts. This comprehensive evaluation allows us to gain valuable insights into the robustness and performance of LLMs across a wide range of scenarios and prompt styles.
2 Evaluation metrics
Considering the diverse evaluation metrics across tasks and varying baseline performances across models and datasets, the absolute performance drop may not provide a meaningful comparison. Thus, we introduce a unified metric, the Performance Drop Rate (PDR). PDR quantifies the relative performance decline following a prompt attack, offering a contextually normalized measure for comparing different attacks, datasets, and models. The PDR is given by:
where is the adversarial attack applied to prompt , and is the evaluation function: for classification task, is the indicator function which equals to when , and otherwise; for reading comprehension task, is the F1-score; for translation tasks, is the Bleu metric . Note that a negative PDR implies that adversarial prompts can occasionally enhance the performance.
Results and analysis
In this section, we present our benchmark results and analysis in evaluating the robustness of LLMs on adversarial prompts.
We report and discuss the Average PDR (APDR) across different attacks, LLMs, and prompts. Note that although our semantic preserving study in Sec. 2.2.3 demonstrated that at least 85% of the adversarial prompts are acceptable, there are still some adversarial prompts diverged from their intended semantic meaning. We further summarize the results by excluding these meaningless prompts in Appendix G to present a comparison analysis. Our main results in the main paper are based on all the prompts, whose conclusions are in consistent with Appendix G. Furthermore, note that the significant discrepancies in APDR variance values are due to varying PDR values across different attacks, prompts, models and datasets, leading to pronounced variance.
Table 4 summarizes the APDR of attacks on datasets. The APDR is calculated by , where is the set of types of prompts and is the set of all models. The results offer several key insights. Firstly, attack effectiveness is highly variable, with word-level attacks proving the most potent, leading to an average performance decline of across all datasets. Character-level attacks rank the second, inducing a performance drop across most datasets. Notably, semantic-level attacks exhibit potency nearly commensurate with character-level attacks, emphasizing the profound impact of nuanced linguistic variations on LLMs’ performance. Conversely, sentence-level attacks pose less of a threat, suggesting adversarial interventions at this level have a diminished effect. Moreover, the effect of prompt attack varies across different datasets. For instance, StressTest attacks on SQUAD V2 yield a mere 2% performance drop, while inflicting a 25% drop on MRPC. Furthermore, we observe that StressTest attack paradoxically bolsters model’s performance in some datasets, we delve into this phenomenon in Sec. 4.3.3.
Note that while character-level attacks are detectable by grammar detection tools, word- and semantic-level attacks underscore the importance of robust semantic understanding and accurate task presentation/translation for LLMs. A comprehensive understanding of these nuances will inform a deeper comprehension of adversarial attacks on LLMs.
Table 7 summarizes the APDR of LLMs on datasets. The APDR is calculated by where is the set of types of prompts and is the set of attacks. Our analysis reveals that GPT-4 and UL2 significantly outperform other models in terms of robustness, followed by T5-large, ChatGPT, and Llama2, with Vicuna presenting the least robustness. The robustness against adversarial prompts of UL2, T5-large, and ChatGPT varies across datasets, with UL2 and T5-large showing less vulnerability to attacks on sentiment classification (SST-2), most NLI tasks, and reading comprehension (SQuAD V2). Specifically, UL2 excels in translation tasks, while ChatGPT displays robustness in certain NLI tasks. Vicuna, however, exhibits consistently high susceptibility to attacks across all tasks. It can be observed that, given the same adversarial prompts generated by ChatGPT, GPT-4 exhibits superior robustness across all tasks. However, it is crucial to realize that this observed robustness might attribute to the weak transferability of the adversarial prompts crafted specifically for ChatGPT. In the future, the performance of GPT-4 and ChatGPT could be significantly improved since these proprietary models keep evolving.
Table 7 summarizes the APDR of types of prompts on datasets. The APDR is calculated by where is the set of prompts of certain type , is the set of attacks and is the set of all models. In our analysis, few-shot prompts consistently demonstrate superior robustness compared to zero-shot prompts across all datasets. Furthermore, while task-oriented prompts marginally outperform role-oriented prompts in overall robustness, both of them show varying strengths across different datasets and tasks. For example, role-oriented prompts present increased robustness within the SST-2 and QQP datasets, whereas task-oriented prompts are more resilient within the MRPC, QNLI, SQuAD V2, and IWSLT datasets. Insights into different effects of prompt types on model vulnerability can inform better prompt design and tuning strategies, enhancing LLMs robustness against adversarial prompt attacks.
2 Analysis on model size and fine-tuning
As shown in Table 5 and 7, there seems to be no clear correlation between model robustness and size, for example, despite being the smallest, T5-large demonstrates robustness on par with larger models such as ChatGPT on our evaluated datasets.
The observed differences in model robustness might stem from two aspects: 1) the specific fine-tuning techniques employed. For example, both UL2 and T5-large, fine-tuned on large datasets, and ChatGPT, fine-tuned via RLHF , exhibit better robustness than Vicuna. These findings encourage further investigation of fine-tuning strategies to enhance robustness. 2) the memorization of training data. Recent studies suggest that the remarkable performance of some LLMs might be rooted in their ability to memorize training data , rather than in generalization. Hence, even when confronted with adversarial prompts, models might leverage this memorization to produce accurate responses.
In this section, we conduct experiments to analyze the effects of different model sizes and fine-tuning on adversarial prompts. Particularly, we leverage the open-source Llama2 series due to their support on different sizes and their corresponding fine-tuned versions. The chat versions of Llama2 (Llama2-chat) are fine-tuned on human instructions datasets to better follow the instructions and support multi-turn conversations, while the original version can only be used for inference.
We analyzed three models from the open-source Llama2 series : Llama2-7B-chat, Llama2-13B-chat, and Llama2-70B-chat. These were chosen due to their distinct sizes, further, their fine-tuning datasets and methods are the same. Our results, depicted in Figure 4, reveal that, in a non-adversarial setting, larger models like the 70B model typically surpass the performance of their smaller counterparts. Yet, when subjected to adversarial attacks, the performance dynamics change: at times, smaller models outshine the larger ones. The reasons for these abnormal behaviors could trigger interests for future research.
To delve into the intricacies of fine-tuning, we compared the performances of Llama2-7B and Llama2-7B-chat on the SST2 and COLA tasks. Our analysis, as visualized in Figure 5, underscores a consistent trend: models fine-tuned using human-instruction datasets fare better against adversarial onslaughts than models that are not fine-tuned. This observation implies that fine-tuning could be further utilized as the countermeasures for adversarial inputs.
3 Understanding the vulnerability of LLMs to adversarial prompts
In this section, we study the magic behind adversarial prompts to analyze why they lead to errors for LLMs from different aspects: erroneous response analysis, attention visualization, and case study on sentence-level attacks.
We first analyze the erroneous response analysis produced by adversarial prompts. The results suggest that adversarial prompts impact LLMs’ performance by inducing misclassification errors and hindering their ability to generate meaningful responses.
Induced Misclassification: As exemplified by BertAttack, CheckList, and Translation attacks, adversarial prompts can lead the model to erroneous classifications. For instance, the sentiment prediction may shift from positive to negative due to the influence of the adversarial prompt. This instance validates the efficacy of adversarial attacks in manipulating the model’s decision-making processes.
Generation of Incoherent Responses: In the case of the DeepWordBug attack, the adversarial prompt results in the model generating incoherent or nonsensical sentences. For example, the response “None of the above choices” does not align with any positive or negative sentiment classification, thereby demonstrating that the model fails to comprehend the intended input. This observation emphasizes the susceptibility of LLMs to adversarial perturbations that can potentially hamper their natural language understanding capabilities.
3.2 Analysis by attention visualization
Then, we conduct an attention visualization experiment to investigate the influence of adversarial prompts on LLMs’ focus on input words. Specifically, we propose two attention visualization techniques: 1) Attention by Gradient, which assigns an attention score to each word based on the gradient norm, and 2) Attention by Deletion, which assigns an attention score to each word by examining the absolute change in loss when the word is removed. Comprehensive details regarding these methods can be found in Appendix D. Both techniques produce similar results; hence, we focus on results from the Attention by Gradient method for simplicity. Our key findings, as demonstrated in Table 8, are as follows:
Clean prompts: efficient attention allocation. LLMs predominantly concentrate on key terms within clean prompts, aiding in accurate classifications. For instance, for clean prompts of BertAttack in Table 8, LLMs mainly allocate attention to the term ‘lazy’, correctly deducing a ‘Negative’ sentiment.
Adversarial prompts: attention divergence. Adversarial prompts can reroute LLMs’ attention from integral text segments, causing misclassifications. In some attacks like CheckList and StressTest, the model simultaneously concentrates on the target text and adversarial content, amplifying its susceptibility to adversarial perturbations. For instance, introducing a random sequence ‘LKF0FZxMZ4’ during a CheckList attack distracts the model, reducing focus on the critical word ‘good’ for accurate classification. In other attacks, such as BertAttack and DeepWordBug, the model’s attention is entirely diverted from the text requiring classification towards adversarial prompts, leading to a significant shift in focus. For example, in DeepWordBug attack, typos in specific words divert the model’s attention from ‘awful’ to the altered word ‘Qetermine’.
3.3 Analysis on sentence-level attacks
The phenomenon where sentence-level attacks occasionally improve the performance of LLMs is an intriguing aspect of our study. Our attention analysis revealed distinct behaviors when models are subjected to StressTest and CheckList attacks. Specifically, when juxtaposed with other adversarial prompts, sentence-level attacks sometimes lead the model to hone in more acutely on pertinent keywords in the question and the labels. This is contrary to the expected behavior. As illustrated in Table 9, introducing an ostensibly unrelated sequence, such as ‘and true is true’, heightens the LLMs’s focus on the ‘not_entailment’ label. Simultaneously, the model continues to attend to salient terms like ‘minnow’ and ‘duck’, ultimately culminating in a correct prediction.
4 Transferability of adversarial prompts
In general, we observe that adversarial prompts exhibit some degree of transferability. However, it is marginal compared to Table 4 and 7. Specifically, the APDR in the target model by adversarial prompts from source model is small compared to the original APDR of the source model. Furthermore, the standard deviation tends to be larger than the APDR, indicating that the transferability is inconsistent. Some adversarial prompts can be successfully transferred, causing a performance drop, while others may unexpectedly improve the performance of the target model. A prime example is the BertAttack transfer from UL2 to Vicuna, which resulted in a value, suggesting an unanticipated enhancement in Vicuna’s performance when subjected to these adversarial prompts. These phenomena illustrate the complex robustness traits of different models. The transferability to ChatGPT is better compared to T5-large and UL2. This suggests an avenue to generate adversarial prompts to attack black-box models such as ChatGPT by training on small models like T5-large, which could be used for future research on robustness.
5 Attacking both prompts and samples
The primary focus of this work is to evaluate the robustness of prompts rather than input samples since the samples can be omitted in certain situations, as discussed in Sec. 2.2. In this section, we explore the possibility of attacking both prompts and samples, i.e., evaluating the performance of LLMs in adversarial prompts and samples. Note that since the generation of adversarial examples is expensive and time-consuming, we leverage an existing adversarial dataset called AdvGLUE , which contains adversarial examples from GLUE and it consists of five same tasks as GLUE: SST-2, QQP, MNLI, QNLI, and RTE. Then, we leverage the adversarial prompts and the AdvGLUE dataset to evaluate the performance when attacking both prompts and samples.
Table 11 shows the accuracy results using both clean and adversarial prompts on AdvGLUE and clean dataset, respectively. The results demonstrate that on average, all attacking approaches are effective since the accuracy is dramatically declined in face of adversarial prompts. Similar to Table 4, word-level attacks (TextFooler and BertAttack) are the most effective with more than 49% of accuracy drop. Moreover, surprising results emerge for Checklist attack since the performance can sometimes be improved (e.g., 69.59% on SST-2 vs. the original 63.51%). This is also consistent with our previous observation in Sec. 4.3.3. The results in this section show that attacking both the prompts and samples can further reduce the performance of LLMs. However, certain attacks can even enhance the performance, which is left for future research.
6 Which prompts are more robust? Analysis on word frequency
Identifying the frequent patterns in prompts that may affect robustness is essential to both researchers and end-users. We perform an initial analysis on word frequency. We divide prompts into two categories: Vulnerable prompts, causing a performance drop of over , and Robust prompts, with a performance drop of or less. Then, we collect all the words appeared in these prompts, and calculate the robust word frequency of word as where and denote the occurrences of in robust and vulnerable prompts, respectively. We primarily analyzed the adversarial prompts of CoLA and MRPC datasets generated by the T5-large model. The word frequency results of these two datasets are presented in Figure 6.
In our examination of adversarial robustness in large language models, we identified that word-specific resilience to attacks is not uniform. Specifically, within the COLA dataset, prompts incorporating terms such as “acting”, “answering”, and “detection” displayed greater resistance to adversarial perturbations. In contrast, those with words like “analyze”, “answer”, and “assess” were notably more susceptible. Yet, an analysis of the MRPC dataset demonstrated a significant overlap in the frequency of words present in both robust and vulnerable prompts. This overlap challenges the notion that specific words inherently determine a prompt’s resilience to adversarial attacks.
Our findings underscore that the resilience of a prompt is intricately tied to the contextual use of words, rather than the mere presence of certain terms. This complexity suggests that factors beyond word frequency, such as semantic coherence and syntactic structures, might be instrumental in determining robustness. This knowledge is valuable as it can influence future research on large language model robustness, provide guidance for crafting more resistant prompts, and facilitate the creation of defensive mechanisms against adversarial prompt attacks. It’s essential to emphasize that our observations are rooted in the current scope of models and datasets. Furthermore, the robustness or vulnerability of words remains deeply context-dependent. Hence, direct determination of word robustness without considering the broader context may lead to oversimplified or inaccurate conclusions.
Defenses
In this section, we discuss potential countermeasures for future research. We categorize the robustness enhancement (i.e., defenses to adversarial prompts) approaches into three main axes: strategies in the training phase, input preprocessing, and downstream fine-tuning.
Similar to adversarial training , integrating low-quality or intentionally perturbed data during the training and fine-tuning phases allows the model to acquaint itself with a broader range of inputs. This acclimatization aims to reduce the model’s susceptibility to adversarial attacks, bolstering its resilience against malicious attempts that exploit such data nuances.
As discussed in Sec. 4.4, adversarial prompts exhibit transferability but constrained. Thus, one promising countermeasure is the utilization of diverse models , training them independently, and subsequently ensembling their outputs. The underlying premise is that an adversarial attack, which may be effective against a singular model, is less likely to compromise the predictions of an ensemble comprising varied architectures. On the other hand, a prompt attack can also perturb a prompt based on an ensemble of LLMs, which could enhance transferability.
2 Input preprocessing
Leveraging spelling checks to maintain input fidelity can counteract basic adversarial techniques targeting typographical errors (character-level attacks) and inconsistencies (sentence level attacks).
Semantic rephrasing involves analyzing the meaning and intent behind a prompt. Using auxiliary models or rule-based systems to discern potentially adversarial or malicious intent in inputs could filter out harmful or misleading prompts.
By maintaining a limited history of recent queries , the system can identify patterns or sequences of inputs that might be part of a more extensive adversarial strategy. Recognizing and flagging suspicious input sequences can further insulate the LLM from coordinated adversarial attacks.
3 Downstream fine-tuning
The fine-tuning phase is instrumental in refining the prowess of LLMs. Exploring more effective fine-tuning methodologies, which adjust based on the detected adversarial input patterns, can be pivotal. With the continuous evolution of adversarial threats, dynamic and adaptive fine-tuning remains a promising avenue. For example, only fine-tuning on relevant slicing technique , model soup , fine-tuning then interpolating , etc.
Limitations
We acknowledge several limitations that could be addressed in future research. First, due to the required substantial computation, we did not perform evaluations on the full datasets but relied on sampling. Future research may evaluate on the entire datasets to gain more comprehensive insights. Second, while our benchmark involves a diverse set of LLMs and datasets, we cannot included all LLMs and datasets (which is impossible) due to computation constraint. Including more in the future could provide a more diverse perspective. Third, we did not evaluate more advanced techniques of prompt engineering such as chain-of-thought (CoT) and tree-of-thought (ToT) . We believe more evaluations can be done on latest prompt engineering techniques. Fourth, we considered black-box prompt attacks, which can generate perturbations that can mimic naturally occurred errors. Optimized prompt attacks in the white-box setting may produce more powerful adversarial prompts, which is an interesting future work to explore.
Related work
Due to the remarkable performance achieved by LLMs on numerous tasks, evaluating LLMs continually gains wide attention. The topics of evaluation span from traditional natural language processing tasks , to their robustness , hallucination , ethics , and education , medical , agents , etc..
AdvGLUE stands as a static dataset for evaluating adversarial robustness of input samples. DecodingTrust undertakes a comprehensive assessment of trustworthiness in GPT models, notably GPT-3.5 and GPT-4. The research delves into areas like toxicity, stereotype bias, adversarial challenges, and privacy. Specifically, they evaluate the robustness on standard datasets AdvGLUE and AdvGLUE++. Specifically for adversarial robustness, DecodingTrust also focuses on evaluating the robustness of input samples instead of prompts and it still uses static datasets rather than an actionable benchmark suite.
Compared with these literature, PromptBench is positioned as an open benchmark concentrating on adversarial prompts rather than samples (and it can be extended to include samples). Note that the prompts are general instructions to assist the in-context learning of LLMs to perform specific tasks, and they can be combined with many samples in certain tasks. Prompts are indispensable in human-LLMs interaction while input samples may not be needed, which means that prompts are versatile and it is essential to evaluate their robustness. Moreover, PromptBench is not a static dataset. It not only facilitates robustness evaluations but also provides the necessary tools, codes, and analysis for extensions, welcoming the inclusion of new datasets and LLMs, thus underscoring its flexibility and broad applicability.
2 Safety of LLMs
We mimic the potential user prompts by creating adversarial prompts, but the main purpose is not to actually attack the model. This distinguishes our work from existing efforts in safety research of LLMs. Specifically, both SafetyPrompts and prompt injection attacks are engineered to spotlight potentially harmful instructions that could steer LLMs into delivering outputs misaligned with human values or perform unintended actions such as data leakage and unauthorized access. Adversarial prompts are crafted to mimic plausible mistakes an end-user might inadvertently make. Our goal is to assess the extent to which these prompts, even if they slightly deviate from the norm, can skew LLM outcomes. These adversarial prompts retain their semantic integrity, ensuring they’re virtually imperceptible for humans. The adversarial prompts are not designed to elicit harmful or misleading responses from LLMs.
3 Textual adversarial attacks
Prompt attacks and textual adversarial attacks are both rooted in similar foundational algorithms, but differ in critical ways:
Target of attack: Prompt attacks target the instruction (prompts) for LLMs while vanilla adversarial attacks focus on the samples. In numerous tasks, the data might be optional, while prompts remain indispensable. For example, “Write a story about a fox.” and “Give me some investigation suggestions.” are all prompts with no samples. This makes our prompt attack more general.
Universality of adversarial prompts: An adversarial prompt, represented as , works as a common threat for all samples related to a specific task. For example, if is designed to instruct LLMs to solve math problems, then can be used for many different math problems and datasets. This ability is significantly different from current NLP adversarial benchmarks.
In essence, prompt attacks seek to delve into the universality of adversarial prompts. We argue this offers an innovative lens to assess the robustness of language models, complementing insights from existing benchmarks like AdvGLUE , and AdvGLUE++.
Conclusion
The robustness of prompts in LLMs is of paramount concern in security and human-computer interaction. In this paper, we thoroughly evaluated the robustness of LLMs to adversarial prompts using the proposed PromptBench benchmark. They key is to leverage adversarial attack approaches to mimic potential perturbations such as typos, synonyms, and stylistic differences. We then conducted extensive experiments and analysis on various tasks and models. While the results show that current LLMs are not robust enough to adversarial prompts, we further analyzed the reason behind it using attention visualization. Moreover, we analyzed the frequent words to provide a guidance for both experts and non-experts in developing better prompt engineering tools. PromptBench will be open-sourced to the public to serve as a foundational tool for robust LLMs research.
References
Appendix A Models, Datasets, and Enviroments
Here, we list the brief introduction of each LLM in our experiments. For more details about Vicuna, please refer to its GitHub repositoryhttps://github.com/lm-sys/FastChat. For the other LLMs, please refer to Huggingface transformer repository .
Flan-T5-large : Flan-T5-large is a derivative of the Text-to-Text Transfer Transformer (T5) model, developed by Google.
Dolly-6B : The Dolly-v1-6b model is a 6-billion parameter causal language model developed by Databricks. It originates from EleutherAI’s GPT-J and has been fine-tuned on the Stanford Alpaca corpus, which comprises roughly 52K question/answer pairs.
Vicuna-13B : Vicuna-13B, fine-tuned from the LLaMA-13B base model, was developed using approximately 70K user-shared conversations collected from ShareGPT.com via public APIs.
Cerebras-13B : Cerebras-13B is based on the GPT-3 style architecture. All models in the Cerebras-GPT series have been trained according to Chinchilla scaling laws , which optimize compute efficiency by maintaining a ratio of 20 tokens per model parameter.
Llama2-13B : The Llama2 model, developed by the FAIR team at Meta AI, is an autoregressive language model that employs the transformer architecture.
GPT-NEOX-20B : GPT-NEOX-20B is a large-scale implementation of GPT-based models, with NEOX-20B specifically referring to a variant of this series comprising 20 billion parameters.
Flan-UL2 : Flan-UL2 is an encoder decoder model based on the T5 architecture. It uses the same configuration as the UL2 model. It was fine-tuned using the “Flan” prompt tuning and dataset collection.
ChatGPT and GPT-4 : Developed by OpenAI, ChatGPT is a large language model trained to generate human-like text based on the prompt it’s given. It uses the GPT-3 architecture and has been fine-tuned for more interactive and conversational tasks. GPT-4 is by far the best-performing LLMs.
A.2 Datasets
The GLUE dataset (General Language Understanding Evaluation) is a collection of resources designed to assess and benchmark the performance of natural language processing (NLP) models across various language understanding tasks. In this study, we selected 8 tasks, including Sentiment Analysis (SST-2 ), Grammar Correctness (CoLA ), Duplicate Sentence Detection (QQP , MRPC ), and Natural Language Inference (MNLI , QNLI , RTE , and WNLI ).
To evaluate the extensive world knowledge and problem-solving abilities of large language models, the MMLU dataset encompasses 57 tasks consisting of multiple-choice questions from diverse domains, such as mathematics, history, computer science, law, and more. This dataset serves as a massive multitask test.
SQuAD v2 is a widely used dataset for training and evaluating natural language processing models in the domain of machine reading comprehension. SQuAD v2 enhances the original SQuAD dataset (SQuAD v1) by introducing unanswerable questions, increasing the challenge for models. For each question, the model must either (1) identify the correct answer span within the passage (if the question is answerable) or (2) predict that the question is unanswerable (if there is no answer span within the passage).
The Multi UN dataset is a large parallel corpus of text gathered from official United Nations documents. It comprises texts in six official languages of the United Nations: Arabic, Chinese, English, French, Russian, and Spanish. The Multi UN dataset primarily contains formal texts, which may limit its applicability to more informal language domains or conversational applications.
The IWSLT 2017 dataset (International Workshop on Spoken Language Translation 2017) is a collection of multilingual, multi-domain parallel text data specifically designed for evaluating spoken language translation systems. The translation tasks include data from the TED Talks Open Translation Project, featuring parallel text data for multiple language pairs such as English-German, English-French, English-Chinese, and English-Czech. The dataset consists of both spoken language transcriptions and their corresponding translations.
DeepMind Mathematics Dataset is a collection of math problems aimed at evaluating the mathematical reasoning abilities of artificial intelligence models. The dataset challenges AI models to solve a diverse range of mathematical problems, spanning from algebra to calculus, and tests their ability to comprehend and reason via complex mathematical concepts.
A.3 Environments
To reproduce the computational environment used in this study, an environment file, environment.yml, is provided in our repository. This YAML file lists all the dependencies and their specific versions used in the study. Users can create an identical Conda environment using the command conda env create -f environment.yml.
The computational experiments were conducted on machines equipped with NVIDIA Tesla V100 GPUs (16GB of GPU memory each).
Appendix B Attacks
The majority of our prompt attacks have been developed by adapting and revising strategies from TextAttackhttps://github.com/QData/TextAttack . For the detailed settings of each attack, please refer to our code.
Character Level: Techniques such as TextBugger and DeepWordBug manipulate text at the character level by introducing typos or errors within words through insertions, deletions, replacements, and replications. These methods capitalize on the model’s vulnerability to minor perturbations in individual characters, frequently resulting in misclassification or erroneous interpretations.
We primarily adopt the settings from TextAttack for TextBugger and DeepWordBug, such as the repeat constraint which prohibits modifying words that have already been altered. Additionally, For TextBugger, TextAttack enforces a constraint on the overall similarity between the sentence encodings of clean and adversarial prompts, utilizing the Universal Sentence Encoder to generate text embeddings. In our study, we set this minimum similarity threshold to . For DeepWordBug, TextAttack set constraint on edit distance (Levenshtein Distance) as .
Word Level: In this study, we employ BertAttack and TextFooler for word-level attacks. These approaches focus on replacing words within the text with synonyms or contextually similar words. By making ostensibly minor alterations to the input text, these attacks can deceive large language models into producing incorrect outputs or substantially modifying their predictions. We meticulously fine-tune the hyperparameters of BertAttack and TextFooler to obtain more appropriate synonyms.
For TextFooler, we set the minimum embedding cosine similarity between word and its synonyms as , and the minimum Universal Sentence Encoder similarity is . For BertAttack, the minimum Universal Sentence Encoder similarity is .
Sentence Level: StressTest and CheckList serve as examples of sentence-level attacks, wherein adversaries attempt to distract the model by adding irrelevant or extraneous sentences to the input text. By incorporating misleading information into the text, these methods can potentially cause the model to lose focus on the primary context, leading to inaccurate results. For the StressTest attack, we adopt similar settings to those in , appending ”and true is true, ” ”and false is not true, ” or ”and true is true ” for five times to the end of a prompt. For the CheckList attack, we generate 50 random sequences consisting of alphabets and digits, each with a length of 10, and append this random sequences into the end of a prompt.
Semantic Level: At the human level, adversaries can construct prompts using various languages, such as Chinese, French, Arabic, Spanish, Japanese, and Korean, subsequently translating these prompts into English. By exploiting the nuances and idiosyncrasies of different languages during translation, it can introduce subtle ambiguities, grammatical errors, or inconsistencies in the input prompt. This poses a formidable challenge for NLP models in generating accurate and coherent responses.
For each language, we first construct 10 prompts based on a English prompt by GPT4 , then translate it back to English by Google Translator.
Appendix C Results of clean prompts on all LLMs
Table 12 showcases the performance of different models across various datasets when using clean prompts. Certain LLMs, including Dolly, Cerebras, and NEXO, encounter difficulties with some datasets. For instance, Dolly’s accuracy for the QQP dataset is merely , a stark contrast to T5’s accuracy of . Consequently, we focus our attack study on models that demonstrate superior performance, namely T5, Vicuna, Llama2, UL2, ChatGPT, and GPT4.
Appendix D Attention visualization techniques
Consider an input comprised of words and tokens, where represents the -th token belonging to word , and let be the corresponding label. Initially, LLM decomposes each word into tokens. Thus, tokens that correspond to the same word need to be concatenated, let the mapping function . We first compute the gradient of each token according to:
Once we obtain the gradients, we compute the word-level gradient by summing the token-level gradients corresponding to each word:
Finally, we calculate the norm of each word’s gradient, followed by min-max normalization to produce a score for each word:
D.2 Attention by Deletion
Attention by deletion is a prevalent method used in black-box textual attacks to determine the significance of each word in the input. Given an input with the -th word deleted, denoted as , the importance score of can be computed by taking the absolute difference of the loss function evaluated at the complete input and the altered input :
This raw score is then normalized using min-max normalization, yielding a final score for each word:
Appendix E The visualization website for adversarial prompts
In order to provide an interactive and user-friendly platform for visualizing and exploring adversarial prompts, we developed a web-based application using Streamlit hosted by Hugging Face and will be released in the future.
The visualization website, as shown in Figure 7, enables users to select from a variety of LLMs (T5, Vicuna, UL2, ChatGPT), datasets (SST-2, CoLA, QQP, MRPC, MNLI, QNLI, RTE, WNLI, MMLU, SQuAD V2, IWSLT 2017, UN Multi, Math), prompt types (zeroshot-task, zeroshot-role, fewshot-task, and fewshot-role), and attacks (TextBugger, DeepWordBug, BertAttack, TextFooler, CheckList, StressTest, and Semantic). Based on the user’s selection, the application generates adversarial prompts tailored to the chosen model, dataset, prompt type and attack.
Appendix F Human study on semantic perserving of prompts
In our endeavor to validate the efficacy of our adversarial prompt generation, we engaged in a human-centric study. We enlisted the expertise of 5 independent evaluators with proficiency in the domain to critically assess the semantic congruence between the original and the generated adversarial prompts. For the study, we randomly sampled a set of adversarial prompts along with their respective original prompts. The evaluators were tasked with determining if each adversarial prompt was semantically equivalent to its original counterpart, ensuring the absence of semantic drift. Such an evaluation provides insights into the reliability and robustness of our adversarial prompts.
The human evaluation yielded a spectrum of results. Here, we present a few exemplars of both acceptable and unacceptable adversarial prompts as discerned by the evaluators:
SST-2 Original prompt: Read the provided excerpt and choose between ’positive’ and ’negative’ to describe its sentiment: Attacked prompt: read the standard excerpt and pause between ’positive’ and ’negative’ to describe its thoughtful: Unacceptable.
CoLA Original prompt: Functioning as a grammar evaluation tool, analyze the given sentence and decide if it is grammatically correct, responding with ’acceptable’ or ’unacceptable’: Attacked prompt: Functioning as a grammar evaluation Lool, analyze the Tgiven sentence and deciRe if it is grammXatically correct, respoOnding with ’acceptable’ or ’unacceptable’: Acceptable.
MMLU Original prompt: As a knowledgeable individual in , provide your response to the multiple-choice question by choosing ’A’, ’B’, ’C’, or ’D’. Attacked prompt: As a knowledgeable everybody in , prescribes your rebuttal to the multiple-choice item by chooses ’A’, ’B’, ’C’, or ’D’. Unacceptable.
Math Original prompt: Resolve the following mathematical question associated with: Attacked prompt: Resolve the following mathematical answer along with : Acceptable.
Appendix G Results excluding non-semantic preserving adversarial prompts
Table 13 presents the attack results after excluding adversarial prompts that do not preserve semantics. It can be observed that the APDR is still considerably high for each dataset.