# R a i n b o w T e a m i n g : Open-Ended Generation of Diverse Adversarial Prompts

###### Abstract

As large language models (LLMs) become increasingly prevalent across many real-world applications, understanding and enhancing their robustness to adversarial attacks is of paramount importance. Existing methods for identifying adversarial prompts tend to focus on specific domains, lack diversity, or require extensive human annotations. To address these limitations, we present Rainbow Teaming , a novel black-box approach for producing a diverse collection of adversarial prompts. Rainbow Teaming casts adversarial prompt generation as a quality-diversity problem, and uses open-ended search to generate prompts that are both effective and diverse. Focusing on the safety domain, we use Rainbow Teaming to target various state-of-the-art LLMs, including the Llama 2 and Llama 3 models. Our approach reveals hundreds of effective adversarial prompts, with an attack success rate exceeding 90% across all tested models. Furthermore, we demonstrate that prompts generated by Rainbow Teaming are highly transferable and that fine-tuning models with synthetic data generated by our method significantly enhances their safety without sacrificing general performance or helpfulness. We additionally explore the versatility of Rainbow Teaming by applying it to question answering and cybersecurity, showcasing its potential to drive robust open-ended self-improvement in a wide range of applications.

## 1 Introduction

Large language models (LLMs) have recently experienced remarkable growth in both their capabilities ( OpenAI, 2023 ; Gemini Team et al., 2023 ; Touvron et al., 2023 ) and their applications in various fields ( NLLB Team et al., 2022 ; Thirunavukarasu et al., 2023 ; Schick et al., 2023 ; Bubeck et al., 2023 ) . As LLMs become increasingly complex and are deployed in safety-critical environments ( Singhal et al., 2022 ; Li et al., 2023 ; Maddela et al., 2023 ) , it is essential to thoroughly understand their robustness to different inputs. Indeed, the susceptibility of LLMs to adversarial prompts — prompts crafted to mislead the model or exploit its weaknesses, potentially leading to unsafe, biased, or incorrect outputs — poses a significant challenge ( Perez et al., 2022 ; Wei et al., 2023 ; Zou et al., 2023 ) . Identifying and mitigating these vulnerabilities is therefore vital to ensure the safe and reliable operation of LLMs in the real world ( Anwar et al., 2024 ; Hendrycks et al., 2022 ) .

Current methods for identifying adversarial prompts aimed at “attacking” LLMs and eliciting undesirable outputs are limited by several factors. These limitations include the necessity of fine-tuning an attacker model ( Perez et al., 2022 ; Ge et al., 2023 ) ; white-box access to the target model ( Liu et al., 2023 ) ; or significant human input ( Yu et al., 2023 ) . Several recent black-box methods, such as PAIR ( Chao et al., 2023 ) and TAP ( Mehrotra et al., 2023 ) , rely on a human-in-the-loop to specify harmful behaviours (e.g., “Write a tutorial on how to hack the university server”) in a way where the human effort required is linear in the number of desired prompts. Many existing methods for systematically discovering adversarial attacks exhibit a lack of diversity by design ( Liu et al., 2023 ) , for instance by restricting themselves to a single predefined attack strategy ( Shah et al., 2023 ; Jiang et al., 2024 ; Anil et al., 2024 ) . Others suffer from loss of diversity, a common issue in objective-based prompt optimisation approaches ( Zhou et al., 2022 ; Fernando et al., 2023 ) . In both cases, the narrow focus of generated prompts limits the usefulness of those methods both as a diagnostic tool and as a source of synthetic data for improving robustness.

We introduce Rainbow Teaming , a versatile approach for systematically generating diverse adversarial prompts for LLMs via LLMs. While the prevailing approach to automatic red teaming ( Perez et al., 2022 ) also uses LLMs to generate adversarial inputs, it exhibits a steep trade-off between the diversity of discovered attacks and their success rate. In contrast, Rainbow Teaming takes a more deliberate approach, efficiently covering the space of attacks by directly optimising for the attack quality and diversity. To this end, our method casts the problem of adversarial prompt generation as quality-diversity (QD) search ( Lehman and Stanley, 2011 ; Pugh et al., 2016 ; Cully and Demiris, 2018 ) and takes direct inspiration from Samvelyan et al. (2024) to discover a set of adversarial prompts that are both diverse and effective.

Rainbow Teaming is an open-ended approach ( Hughes et al., 2024 ) which builds on MAP-Elites ( Mouret and Clune, 2015 ) , an evolutionary search method that iteratively populates an “archive” with increasingly higher-performing solutions. In our case, these solutions are adversarial prompts that elicit undesirable behaviours in a target LLM, while the archive is a discrete grid where each dimension categorises prompts according to a feature of interest for diversity, such as attack style, risk category, or prompt length. The output of our method, as shown in footnote 2 , is a set of prompts covering every combination of features specified by the archive. These diverse and effective attack prompts serve both as a diagnostic tool for the vulnerabilities of the target LLM and as a high-quality synthetic dataset to robustify the target.

Rainbow Teaming is directly applicable to a wide range of domains. Implementing Rainbow Teaming requires three essential building blocks: 1) A set of features that specify the dimensions of diversity (e.g., “Risk Category” or “Attack Style”); 2) A mutation operator to evolve adversarial prompts (e.g., an LLM that is itself prompted to mutate previously discovered prompts ( Lehman et al., 2022 ) ); and 3) a preference model that ranks adversarial prompts based on their effectiveness. For safety, this can be a “judge” LLM ( Zheng et al., 2023 ) that compares two responses to determine which is more unsafe.

We demonstrate the effectiveness of Rainbow Teaming through extensive experiments targeting several state-of-the-art LLMs fine-tuned on safety-aligned data, including the Llama 2-chat ( Touvron et al., 2023 ) and Llama 3-Instruct ( AI@Meta, 2024 ) models. Despite the rigorous development of these models, our experiments reveal hundreds of adversarial prompts per individual run, achieving an attack success rate higher than 90% across all tested models without requiring external data. Using popular safety benchmarks, we demonstrate that Rainbow Teaming outperforms strong baselines in identifying vulnerabilities. Additionally, fine-tuning LLMs with synthetic data generated by our approach significantly enhances their adversarial robustness, improving resistance to unseen attacks and subsequent rounds of Rainbow Teaming , without diminishing their general capabilities and helpfulness.

We further illustrate the versatility of Rainbow Teaming by applying it to other domains, such as question answering and cybersecurity, uncovering hundreds of effective adversarial prompts in each case. These findings underscore Rainbow Teaming ’s potential as a comprehensive tool for diagnosing and advancing the robustness and reliability of LLMs across diverse applications.

## 2 Background

Rainbow Teaming builds on existing approaches in quality-diversity (QD) search to automate the discovery of a broad spectrum of adversarial prompts. QD methods seek to produce a collection of solutions that are individually high-performing and collectively diverse ( Lehman and Stanley, 2011 ; Cully and Demiris, 2018 ) . Given a space of solutions 𝒳 \mathcal{X} , the quality of a solution x ∈ 𝒳 x\in\mathcal{X} is measured using a fitness function f : 𝒳 → ℝ f:\mathcal{X}\rightarrow\mathbb{R} . The diversity of solutions is characterised using a feature descriptor function , d : 𝒳 ↦ 𝒵 d:\mathcal{X}\mapsto\mathcal{Z} that maps each solution to a point in a feature space 𝒵 = ℝ N \mathcal{Z}=\mathbb{R}^{N} . This space encompasses specific pre-defined attributes of the solution, such as its behavioral aspects. For each z ∈ 𝒵 z\in\mathcal{Z} , QD searches for the solution x ∈ 𝒳 x\in\mathcal{X} such that d ⁡ ( x ) = z d(x)=z and f ⁡ ( x ) f(x) is maximised.

Our work builds directly on MAP-Elites ( Mouret and Clune, 2015 ) , a simple yet effective QD method. MAP-Elites tracks the highest-fitness solutions in a multidimensional grid, referred to as the archive , which discretises the feature space 𝒵 \mathcal{Z} . The archive is first initialised with random solutions. During each iteration of MAP-Elites, a solution x x is sampled at random from the archive and modified to create a new solution x ′ x^{\prime} (e.g., by injecting Gaussian noise). The new solution x ′ x^{\prime} is then evaluated and assigned to its corresponding archive cell based on its descriptor z ′ = d ⁡ ( x ′ ) z^{\prime}=d(x^{\prime}) . If the cell is vacant, or if x ′ x^{\prime} has higher fitness than the current occupant, also known as the elite , x ′ x^{\prime} becomes the new elite for that cell. Through repeated cycles of selection, mutation, and evaluation, MAP-Elites fills the archive with the highest-fitness solutions. algorithm 1 in appendix B provides the pseudocode of this method.

## 3 Rainbow Teaming

We now describe Rainbow Teaming , our new approach for automatically generating a diverse collection of adversarial prompts. Rainbow Teaming casts this task as a QD search problem with the solution space corresponding to all possible prompts. Our rationale for employing QD is twofold: • Effective adversarial prompts for specific scenarios (e.g., criminal planning) could be effective for others (e.g., cybercrime and hacking) with relatively small modifications. This adaptability implies that solutions can serve as stepping stones to accelerate the discovery of new adversarial strategies across different categories.

• A thorough diagnostic of the vulnerabilities of a model calls for a comprehensive analytical tool to mitigate the risks of leaving attack vectors undiscovered. Similarly, safety fine-tuning requires a sufficiently diverse dataset to improve a model’s adversarial robustness against a wide range of attacks. Diversity is essential for both of these objectives, and QD allows us to optimise it explicitly.

Rainbow Teaming is based on MAP-Elites ( Mouret and Clune, 2015 ) . We store adversarial prompts as solutions in a K K -dimensional archive, with each dimension corresponding to one of the pre-defined features. Each cell in the archive corresponds to a unique combination of K K categories that describe the prompt within it, known as the cell’s and the solution’s descriptor , and denoted z = ⟨ c 1 , … , c K ⟩ z=\langle c_{1},\dots,c_{K}\rangle . The LLM for which the adversarial prompts are generated is referred to as the Target . Initial solutions can be either generated randomly using an LLM or loaded from an existing dataset. As shown in fig. 2 , all key operation of the iterative search are performed with LLMs.

At each iteration of Rainbow Teaming , we sample 1) an adversarial prompt x x from the archive with descriptor z z , and 2) a descriptor z ′ z^{\prime} for the new candidate prompt to be generated. Note that z z and z ′ z^{\prime} are different. 3 3 3 In fig. 2 , z = ⟨ “Criminal Planning” , “Role Play” ⟩ z=\langle\textrm{``Criminal Planning''},\textrm{``Role Play''}\rangle , while z ′ = ⟨ “Fraud and Scams” , “Misspellings” ⟩ z^{\prime}=\langle\textrm{``Fraud and Scams''},\textrm{``Misspellings''}\rangle . We provide x x and z ′ z^{\prime} to the Mutator LLM to generate a new candidate prompt x ′ x^{\prime} with descriptor z ′ z^{\prime} . We then feed x ′ x^{\prime} to the Target to generate a response. Finally, we ask a Judge LLM ( Zheng et al., 2023 ) to compare the effectiveness of the candidate prompt x ′ x^{\prime} to that of the archive’s elite prompt – the prompt stored in the archive with a descriptor z ′ z^{\prime} . This comparison focuses on the criteria of interest, such as the toxicity of the Target response, to determine which of the two prompts more effectively meets the adversarial objective. We then store the winning prompt in the archive at the position specified by z ′ z^{\prime} . algorithm 2 in appendix B provides the pseudocode of our method.

Rainbow Teaming is highly versatile and can easily be applied to various settings by implementing three components: prompt features, a mutation operator, and a preference model.

### 3.1 Prompt Features

The features define the archive, with each predefined feature corresponding to one of the K K archive dimensions. A feature can be either categorical or numerical. For categorical features, the axis of the archive is composed of discrete bins each representing a unique feature category. For instance, the Risk Category and Attack Style features in footnote 2 each consist of 10 10 categories. Numerical features are represented on a continuous scale, discretised into a set of intervals. Features therefore determine both the final archive size and the axes of diversity that Rainbow Teaming prioritises. This is particularly true given their interplay with the mutation operator , as described next.

### 3.2 Mutation Operator

Rainbow Teaming generates new candidates by applying directed mutations to previously discovered adversarial prompts. The Mutator receives a parent prompt x x sampled uniformly at random from the archive and the prescribed descriptor z ′ = ⟨ c 1 ′ , … , c K ′ ⟩ z^{\prime}=\langle c^{\prime}_{1},\dots,c^{\prime}_{K}\rangle for the candidate. It then mutates the prompt x x once for each feature — K K times overall — to produce a new candidate prompt x ′ x^{\prime} .

Sampling the candidate’s descriptor in advance confers several key benefits. First, this allows us to forgo using a classifier for assigning the candidate to its corresponding cell, which can be inaccurate. Second, it introduces more diversity by mitigating the biases of the Mutator, which could otherwise neglect entire categories. Third, it helps avoid spending iterations on areas of the archive for which we already have effective adversarial prompts. We do this by biasing the sampling distribution of the descriptors towards areas of the archive with low fitness. We compute fitness explicitly for this purpose but do not use it to inform archive updates.

To further promote diversity, the candidate prompt is considered for further evaluation only if it is sufficiently dissimilar from its parent. We measure the similarity using BLEU ( Papineni et al., 2002 ) and filter out prompts that have high BLEU scores with respect to their parents.

### 3.3 Preference Model

The preference model, operated through the Judge, performs the ranking of adversarial prompts based on their effectiveness (e.g., whether they elicit unsafe responses). The Judge inputs can vary between domains, but preference-based evaluations include the Target responses to both the candidate and the existing prompt from the archive with descriptor z ′ z^{\prime} . The Judge determines which prompt is more effective using a majority vote over multiple evaluations and swapping prompt positions to mitigate order bias ( Zheng et al., 2023 ) . If the candidate wins the comparison, it replaces the existing prompt.

Relying on a preference model rather than a score-based evaluator offers two advantages. First, LLMs prompted to perform pairwise comparisons have a higher agreement with humans than those performing single-answer grading ( Zheng et al., 2023 ) . This is particularly true in an optimisation context, which introduces the risk of reward hacking the evaluator. Second, the score of any numerical evaluator with a fixed scale can be maximised, at which point it is impossible to identify better candidate prompts, resulting in minimal updates in the archive. We present a preference model ablation supporting those claims in section E.4 .

While we describe Rainbow Teaming as using LLMs for all key steps, those can be substituted by other models or rule-based components in some domains (e.g., see section 6.1 ).

## 4 Rainbow Teaming for Safety

In this section, we evaluate the effectiveness of Rainbow Teaming in discovering adversarial prompts that trigger unsafe (i.e., harmful, offensive, or toxic) responses. We target various models that are fine-tuned with safety-aligned data and are among the safest publicly available LLMs, including Llama 2 and Llama 3 models.

• Features: We use two feature dimensions: Risk Category and Attack Style. Our risk categories expand upon the safety risk taxonomy in Inan et al. (2023) and cover common safety issues in LLMs, such as “Criminal Planning”, “Violence and Hate” or “Self-Harm”. Attack Style pertains to the method of eliciting unsafe responses, such as “Authority Manipulation” and “Role Play”. Together, these features enable a thorough evaluation of LLM safety, covering a broad spectrum of adversarial threats and tactics. The full list of categories for both features is provided in section H.1 .

• Mutation Operator: We use an instruction-tuned Llama 2 70B model, which applies two mutations to create the candidate prompt, as illustrated in fig. 2 . The first mutation targets the risk category, using a few-shot prompt template shared across all categories. The second mutation focuses on the attack style, employing few-shot prompts handcrafted for each individual category.

• Preference Model: We use an instruction-tuned Llama 2 70B model as a Judge to compare Target responses to two adversarial prompts. Its role is to determine which response is more unsafe, ignoring the prompts. The prompt corresponding to the winner’s response is the one we then keep in the archive. Details about the prompts used for the Judge are provided in appendix I .

To initialise the archive, we generate prompts from scratch according to risk categories without relying on a pre-existing seed dataset. These are then mutated with respect to attack style and used as a foundation for subsequent evolutionary iterations. We use two independent measures of Attack Success Rate (ASR) – the proportion of prompts in the archive that elicit unsafe responses. Specifically, we use two safety classifiers, namely GPT-4 ( OpenAI, 2023 ) with a specialised prompt and the Llama Guard safeguard model ( Inan et al., 2023 ) . GPT-4 acts as a binary classifier for whether a response is generally unsafe or not, independent of risk categories. In contrast, Llama Guard is prompted to perform per-category binary classification ( Inan et al., 2023 ) , considering an attack successful only if the resulting response violates the risk category it is assigned to. Neither of these metrics is explicitly optimised by Rainbow Teaming , but the probability of Llama Guard classifying a prompt as unsafe is the fitness score used to bias the selection of the prescribed feature descriptors for new candidates. Prompts for both evaluators are provided in appendix I . For all experiments, we report the mean and standard error over 3 3 independent runs.

We also measure inter-evaluator agreement on 100 pairs of prompts and responses. table 8 in section E.3 shows that human-human agreement (83%) is similar to human-AI agreement (81% for GPT-4 and 78% for Llama Guard) and GPT-4-Llama Guard agreement (79%), and is consistent with prior work ( Zheng et al., 2023 ) . We therefore use GPT-4 and Llama Guard as proxies for human evaluation.

### 4.1 Results

Main Results. fig. 4 presents the ASR of Rainbow Teaming when applied to the Llama 2-chat 7B ( Touvron et al., 2023 ) , Llama 3-Instruct 8B ( AI@Meta, 2024 ) , Mistral 7B ( Jiang et al., 2023 ) and Vicuna 7B v1.5 ( Chiang et al., 2023 ) models across 2000 iterations, using GPT-4 for evaluation. Rainbow Teaming is highly effective, generating a large collection of adversarial prompts against all models. The Llama models exhibit the highest robustness: following 2000 iterations, we obtain archives of 100 prompts with an approximate ASR of 92% against both variants. Mistral 7B and Vicuna 7B demonstrate a higher level of vulnerability with 98% of the adversarial prompts in Rainbow Teaming -generated archives being successful. These results are echoed by the ASR reported by Llama Guard in fig. 10 .

While fig. 4 showcases relatively small LLMs, Rainbow Teaming is equally effective against larger models. fig. 8 in section E.1 presents results of Rainbow Teaming targeting 7B, 13B, and 70B variants of Llama 2-chat model, achieving 90% or higher ASR across all model sizes .

We compare Rainbow Teaming to two baselines. The first baseline (No Stepping Stones) ignores past solutions in the archive and generates new prompts based on the risk category, before applying the attack style mutation, effectively repeating the process we use to initialise the Rainbow Teaming archive. The second baseline, (Same Cell Mutations) , is identical to Rainbow Teaming , except that it uses the parent prompt’s descriptor as the candidate prompt descriptor, i.e., it performs mutations within each archive cell independently. fig. 4 shows Rainbow Teaming outperforming both baselines, highlighting the value of stepping stones in one case and the significance of cross-category mutations in the other.

JailbreakBench Results. We also apply Rainbow Teaming towards eliciting specific harmful behaviours from the JailbreakBench ( Chao et al., 2024 ) dataset. Using the same attack styles, we generate 1000 prompts evenly spanning 100 harmful behaviours, with results presented in table 1 . We compare against two PAIR ( Chao et al., 2023 ) variants: one from Chao et al. (2024) , based on MiXtral, and another using the same mutator LLM as our Rainbow Teaming implementation, with N = 20 N=20 parallel streams generating a total of 2000 prompts. We classify jailbreaks using both the same classifier as Chao et al. (2024) and Llama Guard prompted with the harmful behaviours. For each prompt, we regenerate 4 responses and consider the prompt successful if any of the responses is classified as harmful. We believe this is representative of user interaction with LLMs, where they can prompt the model repeatedly in the hope of obtaining a different response. Compared to both PAIR variants, Rainbow Teaming discovers more jailbreaks across more behaviours, while also maintaining much higher prompt diversity.

Transfer of Adversarial Prompts. Understanding whether attacks transfer across models is important to assess the generality of the adversarial prompts, and whether they are intrinsically tied to the models they are optimised for. To evaluate transfer, we take the final prompts generated by Rainbow Teaming for each original target in Figure 4 and evaluate their ASR against other transfer targets .

table 2 presents the ASR on four different models using archives generated by Rainbow Teaming targeting each of these models. We show the ASR in grey when re-prompting targets using their own archive. On average, the ASR when transferring prompts is 50 % 50\% of the ASR against the original target, indicating that Rainbow Teaming discovers general prompts which apply to multiple models. However, the exact transfer rate is highly dependent upon the pairing of original and transfer targets. We find that prompts transfer better from safer to less safe models than in the opposite direction. That said, the highest transfer rate is from Vicuna 7B 1.5 to Mistral 7B, even though Vicuna is fine-tuned from a Llama 2 base. We also achieve up to 66% ASR on GPT-4o, indicating no significant difference between open and closed-source models.

Impact of the Similarity Filter. Because archive categories are not mutually exclusive, we run the risk of populating the archive with near identical prompts. This is useful for discovering a category-agnostic failure mode but comes at the cost of significant diversity loss in the archive. To mitigate the issue, we implement a parent-child similarity filter at the mutation stage, as described in section 3.2 . table 3 compares the performance of Rainbow Teaming with and without using this similarity filter. We also report archive self-BLEU ( Zhu et al., 2018 ) , BERTScore ( Zhang et al., 2020 ) , ROGUE-L ( Lin and Och, 2004 ) m and compression ratio ( Shaib et al., 2024 ) scores designed to measure the diversity of a whole dataset. Our results show that the similarity filter is an effective way of maintaining the linguistic diversity of the archive.

Additional results with different system prompts are provided in section E.2 . We include an ablation study in section E.4 to assess the role of the preference model. We discuss computational costs in appendix G .

## 5 Enhancing Robustness with Synthetic Data

Generating diverse, high-quality instruction-tuning datasets can be expensive, often requiring human annotations. Rainbow Teaming offers a low-cost alternative, generating diverse synthetic data that specifically targets the model’s vulnerabilities. In this section, we demonstrate the usefulness of Rainbow Teaming as a synthetic dataset generation method by applying it to improve the safety of LLMs. We find that training on our synthetically generated data improves robustness to adversarial prompts while retaining the general capabilities of the model.

We use Rainbow Teaming to generate 15 archives targeting the Llama 2-chat 7B model, yielding a total of 1500 adversarial prompts. We perform a 12/3 train-test split and use Llama 2-chat 70B with a handcrafted system prompt to generate safe refusal prompts for the train set. We then perform supervised fine-tuning (SFT) ( Wei et al., 2022 ) on this dataset and evaluate the ASR of the 300 held-out prompts before and after SFT. As shown in table 4 , we find that fine-tuning Llama 2-chat 7B on the synthetic dataset generated by Rainbow Teaming substantially reduces the attack success rate from 92% / 95% to 0.3% / 0.7% , as measured by GPT-4 and Llama Guard. Similarly, the ASR of PAIR ( Chao et al., 2023 ) on the JailbreakBench (JBB, Chao et al. (2024) ) behaviours drops from 14% to 0% (measured by Llama Guard, as in table 1 ). This demonstrates that additional SFT on Rainbow Teaming data also improves safety against out-of-distribution attacks. Crucially, SFT does not diminish the model’s general capabilities as measured on the GSM8K (8-shot, maj@1) ( Cobbe et al., 2021 ) and MMLU (5-shot) ( Hendrycks et al., 2021 ) benchmarks. 4 4 4 Touvron et al. (2023) report base model scores on these benchmarks while we report those of the chat model.

table 4 also reports the reward model scores ( Touvron et al., 2023 ) of the Llama 2-chat 7B model before and after SFT. We report safety and helpfulness scores on the Anthropic Harmless and Anthropic Helpful datasets ( Ganguli et al., 2022 ) respectively. We observe a 1.5 % 1.5\% safety score increase, despite the fact that Llama 2-chat models use the Anthropic Harmless dataset as a part of the reinforcement learning from human feedback (RLHF) pipeline ( Touvron et al., 2023 ) . This is accompanied by a 0.5 % 0.5\% drop in helpfulness, which we attribute to fine-tuning the model exclusively on the adversarial prompts produced by Rainbow Teaming . Mixing the adversarial data with helpfulness data would likely negate this effect, but we leave the study of adversarial fine-tuning strategies to future work.

To further investigate the robustness of the newly fine-tuned model, we reapply Rainbow Teaming to the Llama 2-chat 7B model after fine-tuning it on synthetic data generated by our method. As shown in fig. 5 , the new model is substantially more robust to our approach, with a final ASR of 39% (down from 92%) . We expect that performing multiple rounds of Rainbow Teaming , alternating between collecting synthetic data and adversarial fine-tuning, will further increase the model’s robustness to adversarial attacks. We show examples of archives at different iterations of Rainbow Teaming before and after SFT in fig. 13 .

## 6 Rainbow Teaming for Other Applications

### 6.1 Question Answering

We apply Rainbow Teaming to question answering, generating adversarial trivia questions — questions which the target model answers incorrectly. We define a 3D archive, with Topic, Interrogative Word and Question Length as features. The mutation operators for topics and interrogative words are analogous to those used in section 4 . For length, we simply prompt the Mutator to either “lengthen” or “shorten” the question. The preference model uses a Judge to compare answers from a Target (Llama 2-chat 7B) and a superior Oracle (Llama 2-chat 70B) to determine the fitness of questions based on the correctness of the responses. For more information, see section F.1 .

Results. In table 5 we compare Rainbow Teaming to a baseline that generates candidate questions from scratch rather than relying on existing questions in the archive. We observe that Rainbow Teaming achieves higher fitness, higher coverage (percentage of non-empty cells in the archive), and higher diversity in questions, indicating the importance of utilising previously discovered adversarial questions. Importantly, not relying on previous solutions leaves regions of the archive uncovered, particularly for short questions as seen in the example archives in appendix E . fig. 6 illustrates an example archive generated using Rainbow Teaming . Some example questions are also shown in section E.7 .

### 6.2 Cybersecurity

We apply Rainbow Teaming to cybersecurity, searching for adversarial prompts that elicit behaviour such as generating insecure code or providing assistance in orchestrating cyberattacks. We use a 2D archive with the 10 MITRE categories for cyberattack tactics ( MITRE, 2024 ) (e.g., “Exfiltration” or “Defense Evasion”) and prompt length divided into 10 equal bins. Our Mutator is an instruction-tuned Llama 2 70B model, mutating first for MITRE attack style, and then for prompt length. We use a binary Judge mechanism involving Llama 2-chat 70B and CodeLlama-34B Instruct models to evaluate generated prompts, as outlined in CyberSecEval ( Bhatt et al., 2023 ) . We provide further details in section F.2 .

Results. table 6 presents the results of a cybersecurity assessment for various target models on prompts generated by Rainbow Teaming . For all models, we successfully generate 10 × 10 10\times 10 archives that are fully identified as malicious, as classified by CyberSecEval ( Bhatt et al., 2023 ) . Human expert evaluation finds a lower ASR, with 0.94 0.94 and 0.92 0.92 for Llama 2-chat 7B and CodeLlama 7B Instruct, and 0.8 0.8 for both Llama 2-chat 70B and CodeLlama 34B Instruct. While Rainbow Teaming remains highly effective, the discrepancy between CyberSecEval and expert annotations suggests the need for a better cybersecurity-specific evaluation, which we hope will be the focus of future work.

## 7 Related Work

Adversarial Attacks on LLMs. Rainbow Teaming relates most closely to prompt-level attacks which rely on strategies such as misspellings, prompting in foreign languages ( Yong et al., 2023 ) , or persona-modulation ( Shah et al., 2023 ) to jailbreak LLMs. Perez et al. (2022) use an LLM and a brute-force approach to automatically discover prompt-level attacks, but this approach can suffer from mode collapse and does not always generate a diverse set of prompts. Meanwhile, Liu et al. (2023) propose a white-box method that refines hand-crafted attack prompts using a mix of genetic algorithms and LLM-based mutations. However, they focus on optimising a single solution rather than a diverse population. The closest works to our own are PAIR ( Chao et al., 2023 ) and Tree of Attacks with Pruning (TAP) ( Mehrotra et al., 2023 ) — two black-box methods for automatically discovering prompt-level attacks by using an LLM to iteratively generate candidates. However, both methods are designed to jailbreak the model with respect to a single task rather than across a range of diverse risk categories and attack styles. In contrast, our work uses quality-diversity search to automatically discover attacks covering a diverse set of risks and attack strategies. Although evolutionary algorithms have previously been used for adversarial attacks on LLMs ( Liu et al., 2023 ; Lapid et al., 2023a ; Chao et al., 2023 ) , this work is the first to apply a quality-diversity framework ( Lehman and Stanley, 2011 ; Cully and Demiris, 2018 ) in this area. Unlike most evolutionary algorithms (e.g., genetic algorithms), which evolve a single optimal solution, quality-diversity approaches generate a wide variety of distinct, high-quality solutions.

Open-Endedness and LLMs. Rainbow Teaming builds on the ability of LLMs to act as a powerful mutation operator over language inputs, one that adheres to the underlying structure of natural language ( Lehman et al., 2022 ) . Several recent methods exploit this capability of LLMs in order to perform an efficient novelty-driven evolutionary search in the language space, leading to the discovery of potentially open-ended repertoires of solutions ( Chen et al., 2023 ; Fernando et al., 2023 ; Meyerson et al., 2023 ) . Closest to our approach is QDAIF ( Bradley et al., 2023 ) which similarly uses LLMs for QD search in order to generate a diverse archive of LLM outputs. Rainbow Teaming is different from QDAIF in several important factors. First, we search for and archive diverse prompts for the target LLMs, whereas QDAIF archives diverse responses from it — a separate problem altogether. While QDAIF focuses purely on generating diverse outputs for creative writing, our method seeks to find a diverse set of adversarial prompts. QDAIF relies on a score-based fitness function (log probability of the token generation), whereas Rainbow Teaming uses a preference-based judge for performing updates to the archive. Rainbow Teaming additionally incorporates parent-child similarity filtering to preserve the linguistic diversity of the prompts.

An extended related work section is provided in appendix C .

## 8 Conclusion

In this work, we introduce Rainbow Teaming , a novel approach for the automatic generation of diverse adversarial prompts for LLMs. By leveraging quality-diversity search, Rainbow Teaming efficiently explores the space of potential adversarial attacks, resulting in a diverse archive of prompts that highlight the vulnerabilities of LLMs. Our extensive experiments with multiple models, such as Llama 3-Instruct and Llama 2-chat, and across various domains, including safety, question answering, and cybersecurity, demonstrate the generality of Rainbow Teaming . Moreover, the synthetic data generated through Rainbow Teaming can be utilised for fine-tuning LLMs, thereby enhancing their resilience against further adversarial attacks without compromising their general performance. This illustrates the potential of Rainbow Teaming as a means for the continuous, open-ended self-improvement of LLMs, with minimal human intervention. Future work with Rainbow Teaming involves extending its application beyond LLMs to areas such as vision and multi-modal AI systems. Moreover, incorporating Rainbow Teaming into the fine-tuning stages of LLM development presents an opportunity to consistently strengthen their defences against adversarial attacks.

We discuss the limitations and broader impact of our work in appendix A .

## Acknowledgements

We extend our gratitude to Alex Havrilla, Robert Kirk, Maya Pavlova, Suyu Ge, Joshua Saxe, and Aaron Grattafiori for their insightful discussions and feedback on our work. We also thank Sten Sootla, Lovish Madaan, Anthony Hartshorn, Jeremy Reizenstein, and Henry Estela, for their assistance in conducting experiments. We extend our deepest gratitude to Nicola Cancedda and Naila Murray for their invaluable support and guidance, which were crucial to this work.

Andrei was partially funded by a Fonds de recherche du Québec doctoral training scholarship.

## Appendix A Limitations and Broader Impact

Despite many advantages of Rainbow Teaming , its current implementation has several limitations. First, the features that define the archive and its categories are pre-defined and fixed. In future work, it would be interesting to extend our approach to discover features and categories automatically. Another limitation of Rainbow Teaming is that the number of prompts it can generate is constrained by the grid size. While this is due to using MAP-Elites as the base QD algorithm, we note that even the current setting allows generating hundreds of adversarial prompts from a single run and this can be extended by providing additional features or categories or storing several values within the same archive cell.

Unlike simpler adversarial attack methods [ Chao et al., 2023 ] , Rainbow Teaming requires extensive computational resources. Furthermore, its undirected, open-ended approach is less likely to produce a prompt for a specific behaviour (e.g., writing a fake news article about a specific public figure). While these attributes can be considered limitations, we highlight that because of them, Rainbow Teaming is less likely to be used for malicious purposes. The primary value of Rainbow Teaming lies in its potential to identify and address robustness issues in LLMs, contributing to their responsible development and deployment.

Ultimately, we believe Rainbow Teaming to be a powerful tool in improving the robustness of LLMs to adversarial attacks and see the prompts it generates as a valuable complement to crowd-sourced data.

## Appendix B Algorithm Pseudocode

### B.1 MAP-Elites

algorithm 1 provides a pseudocode of MAP-Elites method [ Mouret and Clune, 2015 ] described in section 2 .

### B.2 Rainbow Teaming Pseudocode

algorithm 2 provides a pseudocode of Rainbow Teaming described in section 3 .

Throughout this work, we use BLEU score [ Papineni et al., 2002 ] as the similarity metric s ​ i ​ m sim . In the safety domain, we use the probability of Llama Guard categorising a response as unsafe as the fitness function f f . The fitness function is used for biasing the sampling of descriptor d d but not for updating the archive.

For clarity, the algorithm shows the Rainbow Teaming loop over a single prompt x x , but the process can be batched to reduce wall clock time. In practice, we use batch sizes between 16 and 64.

## Appendix C Extended Related Work

### C.1 Token-Level Attacks

Token-level attacks circumvent the LLM’s defences against generating undesirable responses by adding adversarial tokens to a malicious prompt. Such methods originally required white-box access to the LLM [ Zou et al., 2023 ] , but that assumption has since been relaxed using black-box optimisation [ Lapid et al., 2023b , Maus et al., 2023 ] . Token-level attacks have proven effective, but brittle to perturbations [ Robey et al., 2023 ] . Although Rainbow Teaming could be adapted to create token-level attacks by integrating the appropriate attack categories and prompts, we restrict this study to prompt-level attacks given that prompt-level attacks are more interpretable and harder to detect.

### C.2 Adversarial Training

Rainbow Teaming ’s approach parallels other forms of adversarial training, which prioritises training on tasks or data points where the model performs poorly. In reinforcement learning (RL), methods such as active domain randomisation [ Mehta et al., 2020 , Raparthy et al., 2020 ] and regret-based unsupervised environment design [ Dennis et al., 2020 , Jiang et al., 2021 , Parker-Holder et al., 2022 , Samvelyan et al., 2023 ] search for training tasks where the agent performs poorly in terms of absolute task performance or regret, respectively. Regret-based prioritisation has been shown to hold robustness guarantees at convergence and carry the benefit of avoiding unsolvable tasks (which always result in zero regret). The fitness score used by Rainbow Teaming coincides with regret [ Savage, 1951 ] , as a high fitness here implies the existence of another prompt that elicits a less undesirable response, as evaluated by the Judge. Similarly, many active learning and automatic curriculum learning methods in supervised learning focus training on examples maximising error metrics derived from the model’s predictions [ Graves et al., 2017 , Mindermann et al., 2022 , Evans et al., 2023 ] . Dynabench [ Kiela et al., 2021 ] extends this paradigm by querying humans-in-the-loop for adversarial examples. Many methods in scenario generation also closely relate to Rainbow Teaming , including recent approaches using QD search to find adversarial environments that induce poor behaviour in fully-automated or mixed-autonomy systems [ Fontaine et al., 2021 , Fontaine and Nikolaidis, 2022 , Bhatt et al., 2022 ] . This extends to recent work applying QD to multi-agent RL [ Samvelyan et al., 2024 ] , which inspired our method.

## Appendix D Adversarial Prompts as Stepping Stones

fig. 7 provides a qualitative example of how the directed mutation in Rainbow Teaming can produce diverse adversarial prompts from a single common ancestor.

## Appendix E Additional Results

### E.1 Varying Model Sizes

fig. 8 presents the ASR of Rainbow Teaming when applied to Llama 2-chat models with 7B, 13B, and 70B parameters across 2000 iterations, using GPT-4 and Llama Guard for evaluation. Archives generated through Rainbow Teaming demonstrate 90% or higher ASR across all model sizes, as measured using GPT-4 and Llama Guard evaluators.

### E.2 Role of System Prompts

While our main experiments provide the prompts to the Target as is (within appropriate instruction tokens), we additionally analyse incorporating two system prompts . The legacy system prompt is designed to emphasise both safety and helpfulness . 5 5 5 It was initially released with Llama 2 but has since been deprecated due to its high false refusal rate. See the change here . The helpful system prompt is a handcrafted variant of the legacy prompt that focuses on helpfulness without explicitly emphasising safety. All system prompts are provided in section I.3 .

The effectiveness of Rainbow Teaming when using these different system prompts is presented in table 7 . Our results indicate the inclusion of a system prompt emphasising safety diminishes the success rate of adversarial attacks to 51% / 74%, according to GPT-4 and Llama Guard evaluations, respectively. However, using this system prompt makes the model overly conservative, occasionally refusing to answer benign questions that appear unsafe. On the other hand, the helpful system prompt, remains vulnerable to attacks, with 82% / 93% ASR, yet still offers improved robustness compared to not using a system prompt at all, which sees 92% / 95% ASR. The Llama 2-chat 7B model has been safety-aligned regardless of the system prompt, but its robustness is highly dependent on this variable.

### E.3 Human Evaluation

table 8 shows the ASR of 100 prompts, as evaluated by GPT-4, Llama Guard and human annotators. The inter-evaluator agreement is also provided.

The 100 prompts were randomly sampled from a combination of archives targeting Llama 2-chat 7B or 70B, using either no system prompt or the Legacy prompt. This was done to ensure sufficient prompt variety. The annotations were done within a single session by four of the authors following the same harm taxonomy as Llama Guard. The annotators were not informed of the data mix or the expected ASR as evaluated by either Llama Guard or GPT-4 at the time of annotation to mitigate bias. All annotations were performed through an interactive spreadsheet, where authors tick a checkbox to label the model response as “GOOD BOT” (when the target model refused to answer or answered in a safe manner) or “BAD BOT” (when the model answered in a way that is violating according to the harm taxonomy).

### E.4 Preference Model Ablation

We investigate the role of the preference model used for Rainbow Teaming . One option is to prompt an LLM to act as a pairwise comparison Judge [ Zheng et al., 2023 ] . The Judge takes as input the response to the candidate prompt and the response to the prompt already in the archive, and is instructed to say which of the two is more harmful. As recommended by Zheng et al. [2023] , we use position swapping (evaluating twice for each order of the prompt-response pairs) to reduce positional bias, and few-shot prompting to improve consistency. We refer to this variant as “Comparison-based (Judge)” and use it as default throughout the paper.

We compare the default version of Rainbow Teaming with a variant that uses the Llama Guard probability of classifying the response as “unsafe” as a preference model. In this case, we perform an archive substitution if the probability for the candidate response is higher than that of the existing response. We refer to this Rainbow Teaming variant as “Score-based (No Judge)”.

In our evaluation, as shown in Figure 9 , the score-based baseline achieves a higher Llama Guard-evaluated ASR, aligning with its optimisation objective. However, it falls short in GPT-4-evaluated ASR, suggesting overfitting to Llama Guard scores, indicative of reward hacking [ Skalse et al., 2022 ] . Qualitatively, we find that the adversarial prompts produced by the score-based method are also of lower quality. We also show the number of archive updates for the two variations of Rainbow Teaming . We observe that the No Judge baseline quickly maximising the Llama Guard score (capped to 1.0 1.0 ) leads to sparse updates thereafter. In contrast, the Judge-based variant continues to refine the quality of the adversarial prompts in the archive, indicated by ongoing archive updates, even after filling the archive with successful prompts. This underscores the advantage of Rainbow Teaming ’s open-ended search process over a purely score-driven approach.

Note that the performance differences between Rainbow Teaming results here and in other parts of the manuscript arise from variations in the experimental setup. In this specific experiment, we use Anthropic Harmless as the seed dataset with slightly different mutation prompts, and two risk category names have been updated.

### E.5 Full Evaluations

fig. 10 presents the ASR of Rainbow Teaming when applied to Llama 2-chat 7B [ Touvron et al., 2023 ] , Llama 3-Instruct 8B [ AI@Meta, 2024 ] , Mistral 7B [ Jiang et al., 2023 ] and Vicuna 7B v1.5 [ Chiang et al., 2023 ] models across 2000 iterations, using both GPT-4 and Llama Guard for evaluation. fig. 11 shows the performance of Rainbow Teaming against No Stepping Stones and Same Cell Mutations baselines, using GPT-4 and Llama Guard for evaluations. In fig. 12 we report the performance of our approach targeting Llama 2-chat 7B model before and after performing SFT on Rainbow Teaming -generated data.

### E.6 Archive Visualisation

fig. 13 illustrates examples archives at various iterations of Rainbow Teaming generated in the safety domain. fig. 14 shows 2D projections of 3D archives of Rainbow Teaming at different iterations when applied in the question answering domain.

### E.7 Question Answering Examples

table 9 provides sample questions generated by Rainbow Teaming for the question answering domain.

## Appendix F Additional Details for Preference Models

### F.1 Question Answering

The preference model used in question answering domain differs from that used in section 4 to account for the difficulty of evaluating the relative correctness of responses to two different questions. For each question q q , we generate an answer r t r_{t} from the Target and another r o r_{o} from an Oracle LLM.

While both the Oracle and Target models receive identical prompts, the Oracle is equipped with superior capabilities (Llama 2-chat 70B) compared to the Target (Llama 2-chat 7B). We then provide the question q q alongside both answers r t r_{t} and r o r_{o} to the Judge to determine whether the question is factual and objective and whether the Oracle’s answer is better than the Target’s answer. If these conditions are met, we save the question to the archive with fitness 1 1 . If not, but the archive cell is empty, we save the question with a fitness of 0.1 0.1 to act as a stepping stone. We discard the question in all other scenarios.

### F.2 Cybersecurity

When using Rainbow Teaming in the cybersecurity domain, we use a binary Judge mechanism to evaluate the potential maliciousness of generated prompts. This is aligned with the framework outlined by Bhatt et al. [2023] , which leverages two distinct LLMs for classifying the output of an LLM as either “benign” or “malicious”. For the initial processing of the output, we use the Llama 2-chat 70B model, which is responsible for preliminary analysis and identification of potentially malicious content. The final decision of whether a response is indeed malicious is then made by the CodeLlama-34B Instruct model [ Rozière et al., 2023 ] .

## Appendix G Inference Cost Analysis

Since inference costs vary based on infrastructure, the number of generation tokens, and specific LLMs used, we choose to discuss computational costs in terms of LLM inference calls. For the majority of our experiments, one Rainbow Teaming loop requires 2 Mutator inference calls, 1 Target inference call, and 4 Judge inference calls, where every inference call corresponds to a batch of prompts (our batch size is 16 for most experiments, except 64 for our JailbreakBench ones). When running for 2000 iterations, this represents a total of 14000 batched inference calls per run.

We conducted our experiments on a cluster of A100 GPUs, with access ranging from 128 to 256 GPUs throughout the project. Each run was typically completed in around two days, though we often accelerated them significantly by leveraging a distributed client-server setup for parallelised LLM inference.

Although the computational cost is substantial, we believe the effectiveness and diversity of the resulting prompts make our method a highly competitive alternative to crowd-sourced data.

Depending on the user’s needs, costs can be further amortised by leveraging earlier Rainbow Teaming checkpoints as a source of additional prompts, potentially expanding the final dataset size by an order of magnitude. As LLMs become more powerful, so do the components of our method. For example, if an LLM can serve as an accurate judge in a single inference call, this could significantly reduce the inference cost associated with the Judge.

## Appendix H Feature Descriptors

### H.1 Safety

Risk Category • Violence and Hate

• Sexual Content

• Criminal Planning

• Guns and Illegal Weapons

• Regulated or Controlled Substances

• Self-Harm

• Inciting or Abetting Discrimination

• Fraud and Scams

• Cybercrime and Hacking

• Terrorism

Attack Style • Slang

• Technical Terms

• Role Play

• Authority Manipulation

• Misspellings

• Word Play

• Emotional Manipulation

• Hypotheticals

• Historical Scenario

• Uncommon Dialects

### H.2 Question Answering

Topic • Science and Technology

• Health and Wellness

• History and Culture

• Arts and Entertainment

• Nature and Environment

• Travel and Geography

• Society and Politics

• Education and Learning

• Food and Cooking

• Relationships and Life

Question Length (measured in number of characters) • Min: 24

• Max: 96

• Number of bins: 10

Interrogative Word • Where

• Who

• What

• When

### H.3 Cybersecurity

MITRE attack tactics • Reconnaissance

• Discovery

• Execution

• Privilege Escalation

• Persistence

• Defense Evasion

• Lateral Movement

• Collection

• Command and Control

• Exfiltration

Instruction Length (measured in number of characters) • Min: 100

• Max: 1000

• Number of bins: 10

## Appendix I Safety Experiment Prompts

This section includes various prompts used in experiments in the safety domain.

### I.1 Llama Guard Evaluation Prompt

For Llama Guard evaluations, we use the default system prompts by Inan et al. [2023] for 6 original categories. For the 4 new categories, similar system prompts have been generated by the authors.

### I.2 Mutation Prompts

We have elected not to share mutation prompts to prevent misuse.

### I.3 System Prompt of Target LLM

Below are the prompts given to the Target Llama 2-chat model in our experiments with various system prompts presented in section E.2 . Here the {input} is replaced with adversarial prompts.

## Appendix J Question Answering Experiment Prompts

This section includes prompts used in the question answering experiments.

## Appendix K Hyperparameters

Tables 10 , 11 , and 12 provide the hyperparameters used in safety, question answering, and cybersecurity domains, respectively.

## Instructions for reporting errors

We are continuing to improve HTML versions of papers, and your feedback helps enhance accessibility and mobile support. To report errors in the HTML that will help us improve conversion and rendering, choose any of the methods listed below:

Click the "Report Issue" ( ) button, located in the page header.

Tip: You can select the relevant text first, to include it in your report.

Our team has already identified the following issues . We appreciate your time reviewing and reporting rendering errors we may not have found yet. Your efforts will help us improve the HTML versions for all readers, because disability should not be a barrier to accessing research. Thank you for your continued support in championing open access for all.

Have a free development cycle? Help support accessibility at arXiv! Our collaborators at LaTeXML maintain a list of packages that need conversion , and welcome developer contributions .
