Safe LoRA: The Silver Lining of Reducing Safety Risks when Finetuning Large Language Models

Authors: chia-yi  hsu
yu-lin  tsai
chih-hsun  lin
yu  chen
chia-mu  yu
chun-ying  huang
Venue: NeurIPS_cc_2024_Conference
Published: 2024-05-13 18:11:12

Abstract: While large language models (LLMs) such as Llama-2 or GPT-4 have shown impressive zero-shot performance, fine-tuning is still necessary to enhance their performance for customized datasets, domain-specific tasks, or other private needs. However, fine-tuning all parameters of LLMs requires significant hardware resources, which can be impractical for typical users. Therefore, parameter-efficient fine-tuning such as LoRA have emerged, allowing users to fine-tune LLMs without the need for considerable computing resources, with little performance degradation compared to fine-tuning all parameters. Unfortunately, recent studies indicate that fine-tuning can increase the risk to the safety of LLMs, even when data does not contain malicious content. To address this challenge, we propose $\textsf{Safe LoRA}$, a simple one-liner patch to the original LoRA implementation by introducing the projection of LoRA weights from selected layers to the safety-aligned subspace, effectively reducing the safety risks in LLM fine-tuning while maintaining utility. It is worth noting that $\textsf{Safe LoRA}$ is a training-free and data-free approach, as it only requires the knowledge of the weights from the base and aligned LLMs. Our extensive experiments demonstrate that when fine-tuning on purely malicious data, $\textsf{Safe LoRA}$ retains similar safety performance as the original aligned model. Moreover, when the fine-tuning dataset contains a mixture of both benign and malicious data,  $\textsf{Safe LoRA}$ mitigates the negative effect made by malicious data while preserving performance on downstream tasks.  Our codes are available at https://github.com/IBM/SafeLoRA.

Main paper: 
 introduction: 
 As Large Language Models (LLMs) and their platforms rapidly advance and become more accessible, the need to align LLMs with human values, cultural norms, and legal compliance is critical for society, technology, and the research community. Specifically, many alignment efforts in AI safety have been made toward preventing LLMs from generating harmful or inappropriate output, through instruction tuning techniques such as Reinforcement Learning with Human Feedback [33, 44, 34, 9, 5, 37, 56] Figure 1 : Overview of Safe LoRA. We first obtain an alignment matrix V = W aligned -W unaligned from a pair of unaligned and aligned LLMs, denoted as W unaligned and W aligned , respectively. Note that W unaligned / W aligned can be the base/chat checkpoints of pre-trained (open-weight) models. For example, W unaligned can be the Llama-2-7b-base model, while W aligned can be the Llama-2-7b-chat model. Next, for each layer in the LLM undergoing LoRA updates ∆W = AB T , we use the projection operator C = VV T /∥V∥ F to calculate the similarity score between the projected LoRA weights CAB T and the original LoRA weights AB T . If the similarity score is below a certain threshold τ , we use the projected LoRA weights as the final updates to W aligned . and Supervised Fine-tuning (SFT) [7, 43, 12, 51, 10] . However, recent studies have unveiled the surprisingly fragile property of aligned LLMs upon fine-tuning [36, 57, 52] -the embedded safety can be significantly weakened when the aligned LLMs are updated with a handful of maliciously crafted data, or even with benign data. This finding is consistently observed across LLMs and fine-tuning strategies, including closed-source ones such as ChatGPT [33] and open-source ones such as Llama-2 [44] , based on full fine-tuning, LoRA fine-tuning [16] , adapter [17] , and prefix tuning [24] .To address the challenge of losing safety guardrails in LLM fine-tuning, this paper presents Safe LoRA, a simple one-liner patch to the original LoRA that enhances the resilience of LLMs to safety degradation. Among various fine-tuning methods, we specifically focus on LoRA due to its practical advantages in memory-efficient parameter updates of LLMs through low-rank adaptation, while achieving comparable performance to the resource-consuming full fine-tuning.Figure 1 provides an overview of Safe LoRA. First, we assume access to a pair of unaligned and aligned LLM weights, denoted as W unaligned and W aligned , which are often available for opensource LLMs such as Llama Base (unaligned) and Chat (aligned) models. We denote their difference as the "alignment matrix" (by treating the weight matrix in each layer of LLMs independently), which is defined as V = W aligned -W unaligned . Intuitively, the alignment matrix entails the instruction tuning and safety alignment efforts to train a base model that is only capable of next-token prediction to become a conversational chatbot and a performant assistant. For each layer in an LLM where LoRA is used for parameter updates, Safe LoRA further projects the LoRA update onto the alignment matrix if the similarity score between the original and projected LoRA updates is below a certain threshold. A lower similarity score suggests that the direction of the original LoRA updates has a larger deviation from the alignment matrix, and we hypothesize this discrepancy is the root cause of the observed safety risks in fine-tuning LLMs with LoRA. With Safe LoRA, our experiments show that the safety and utility of LLMs can be greatly preserved, making it a cost-effective solution for safe LLM fine-tuning due to its data-free and training-free nature.We highlight our main contributions and findings as follows.• We propose Safe LoRA, a simple, data-free, training-free, and model-agnostic patch to counteract the safety degradation problems when fine-tuning LLMs with the native LoRA implementation. In essence, Safe LoRA modifies LoRA updates that are dissimilar to our defined alignment matrix via the projection operation to prevent safety degradation during LLM fine-tuning. An exemplary code of Safe LoRA is presented in Figure 1 .• Evaluated on the Llama-2-7B-Chat and Llama-3-8B-Instruct models against purely malicious or mixed fine-tuning data, Safe LoRA can retain utility (the downstream task performance) while simultaneously reducing safety risks, outperforming existing defense methods including SafeInstr [6] and Backdoor Enhanced Alignment (BEA) [46] .• We found that when using LoRA for fine-tuning, the number of projected layers is related to the inherent alignment strength of the model. For instance, Llama-2-7B-Chat requires projecting only about 11% of the layers, while Llama-3-8B-Instruct needs up to 35% to achieve a good trade-off between utility and safety.2 Related Works 
alignment of llms: 
 Alignment in the context of LLMs denotes the process of ensuring models behave in a way that conforms to social values. Due to the gap between the pre-trained LLM's training objective and human values, practitioners typically perform certain forms of optimization during the alignment stage to ensure that the generated content is "aligned" with human values. For example, aligned LLMs such as ChatGPT [33] and Claude [1, 2] have safety guardrails and can refuse harmful instructions. These methods include Instruction Tuning [48, 34, 44] and Reinforcement Learning from Human Feedback (RLHF) [59, 34, 4] , where the model is instructed to become helpful, harmless, and honest, i.e., the HHH principles [3] . In comparison to RLHF, recent works such as Direct Preference Optimization (DPO) [37] optimize directly on human preference data, thus eliminating the need for a reward model in RLHF. On the other hand, Self-Rewarding [54] transforms the language model into a reward model to collect preference data, then aligns the model with DPO iteratively. These techniques aim to instruct the model with certain alignment rules or safety guardrails so that the model behaves well during inference time. However, during subsequent fine-tuning these guardrails might not hold integrate as revealed by [52, 36, 57] while there are some preliminary measures that counteract this problem [46, 6] .While alignment is being employed in modern LLMs, the terms jailbreak or red-teaming refer to a series of tests or attacks on LLMs designed to reveal their vulnerabilities. Common approaches include exploiting adversarial prompts [26, 60, 55, 25, 40, 53, 28] or the decoding algorithms [19] of LLMs to bypass the safety guardrails established during the alignment stage.On the other hand, fine-tuning LLMs for downstream tasks (not necessarily malicious) has also been shown to have a detrimental effect on the safety guardrails in terms of alignment [26, 47, 35, 60] . As a result, the attacked LLM could be exploited to generate malicious responses, posing a risk to society. This work aims to provide a solution for restoring the safety guardrails in LLMs even after fine-tuning for downstream tasks.While safety and reliability present critical challenges to the research community, an alternate line of work focuses on exploring the relationship between task performance and parameters through arithmetic interventions.Works such as [27, 21, 23, 49] explore the performance boost when averaging fine-tuned model weights from diverse domains, while others discovered that the newly averaged fused model could naturally perform better [8] or serve as a better initialization setting for a new downstream task [8] . On the other hand, a recent work [21] goes beyond interpolating and examines the effects of extrapolating between fine-tuned models. Specifically, these extrapolations, termed task vectors, are generated by re-using fine-tuned models, allowing users to extend the capabilities of models by adding or deleting task vectors in a modular and efficient manner.Another line of work develops efficient methods for modifying a model's behavior after pre-training. This includes various approaches such as patching [50, 42, 21, 32] , editing [39, 30, 31] , aligning [34, 3, 22, 14] (including the previously introduced alignment problem), or debugging [38, 13] . A recent work [41] also follows this approach and tries to steer language models' outputs by adding vectors to their hidden states. 
methodology: 
 Our goal is to retain the alignment of LLMs in a post-hoc fashion after fine-tuning downstream tasks with LoRA. To achieve this, we exploit an "alignment matrix" to project LoRA's parameters. Specifically, this means projecting LoRA's weights onto the alignment subspace, thereby preserving alignment even after fine-tuning. Detailed explanations of the alignment matrix and the projection process will be provided in Section 3.1 and Section 3.2, respectively.To derive the alignment matrix, a pair of unaligned and aligned models is utilized. We further illustrate what aligned and unaligned models are in concept.To formalize, the alignment matrix V i is defined as follows:EQUATIONwhere W i aligned and W i unaligned represent the weights of the aligned and unaligned models in the i-th layer, respectively. When clear in context, we will omit the layer index.After obtaining V i , we perform matrix multiplication with V i and its transpose with the matrix (V i T V i ) -1 to form a standard projection matrix. This operation is conducted on a layer-wise basis, and the resulting matrix Ĉi can be formalized as:Ĉi = V i (V i T V i ) -1 V i T (2)where V i denotes the alignment matrix in the i-th layer, and Ĉi represents the projection matrix defined by V i . Following this operation, we obtain the alignment matrix for each layer, which will further be used for projecting the LoRA weights.For the aligned and unaligned models, take Meta's Llama for example, the aligned model will be the Chat model such that they are trained with an alignment goal [44, 29] . On the other hand, the unaligned model could be the aligned model that is fine-tuned with malicious data such that the LLM has lost the safety guardrail and is vulnerable to attacks.Furthermore, as shown in Figure 2 , we experimented on the behavior of the unaligned model compared to the base model provided in Meta's released checkpoints 1 . We discovered that the 11 categories both OpenAI and Meta's Llama-2 prohibit models from responding to are identical to those of the base model. Scores for each category indicate harmfulness, with lower scores being safer. The scores range from 1 to 5, with 1 being the safest and 5 being the most harmful, as judged by GPT-4. In Figure 2 , we present our results with alignment matrices derived from different models. Here, we project LoRA's weights trained on purely harmful samples. The performances of the base model and the unaligned model after harmful fine-tuning are extremely close.As a result, given that most open-source LLMs provide both their base model and chat/instruct models, users can conveniently use these official models to construct the alignment matrix without needing to train their own aligned or unaligned model. This choice of using base and chat/instruct models to construct the alignment matrix will be our default setup in Safe LoRA.After fine-tuning LLMs on downstream tasks with LoRA, we obtain the LoRA weight ∆W i for the i-th layer, denoted as∆W i = A i B i T .During the fine-tuning process, alignment may be weakened [36] , indicating that ∆W i may have been updated in a way that boosts utility but reduces safety.To retain alignment, it is necessary to project ∆W i using the previously defined Ĉi to restore alignment. However, while ∆W i might weaken the alignment of the original model, it is updated to maximize the utility of the downstream task. To balance alignment and utility, we choose not to project all of the LoRA weights. Instead, we calculate the similarity between the original and projected LoRA weights, i.e., ∆W i and C i ∆W i . Using a threshold, we determine which layers should undergo projection. This process is formalized as follows:EQUATIONUsage Policies : "We don't allow the use of the following:" where i denotes the i-th layer of LoRA's parameters, ⟨•, •⟩ F represents the Frobenius inner product, and || • || F represents the Frobenius norm induced by the inner product. Lastly, τ indicates the threshold of the similarity score. Alternatively, τ could be selected such that only the top-K layers with the lowest similarity scores will be projected. Furthermore, we examine the impact of the number of projected layers on performance and the similarity scores of all layers in the ablation study presented in Section 4.2.The rationale behind post-hoc projection can be interpreted as follows. As recent works [11, 20, 45] begin to explore the holistic structure of weight space, we assume that the weight space is wellstructured such that by subtracting W unaligned from W aligned , we can extract a safety-related vector V in the inner product space constructed by all possible weights, i.e., (F n×n , +, •, R) with the Frobenius inner product ⟨•, •⟩ F . As a result, by constructing the exact projection matrix Ĉ = V(V T V) -1 V T , we create a subspace in the original vector space that represents the safety-related concept.Fine-tuning with LoRA essentially aims to search for solutions to downstream tasks in a smaller subset of F n×n , i.e., all low-rank matrices. By post-hoc projecting the discovered solution, we are able to obtain an intersection of both the low-rank solution space and the safety-critical solution space, thus promoting both the utility and safety of the fine-tuned language model.While the original projection method in Section 3.3 could explain and properly eliminate the safety risk induced during the LLM fine-tuning on downstream tasks, the inverse product (V T V) -1 in Ĉi calculated in each layer is time-consuming. We further introduced an approximate version defined as:C i := V i V i T ||V i || Fwhere || • || F denotes the Frobenius norm. We also compare the time costs for generating C and Ĉ. It takes 8.6 × 10 -3 seconds to generate C, while generating Ĉ requires 2.1714 seconds, denoting a 250x times slower generation speed. All operations are computed by the NVIDIA H100 80GB GPU.Furthermore, to compare the methods, we include the performance on datasets in Table Question: For each theoretical result, does the paper provide the full set of assumptions and a complete (and correct) proof? Answer: [Yes] Justification: We provide in Section 3.3. Guidelines:• The answer NA means that the paper does not include theoretical results.• All the theorems, formulas, and proofs in the paper should be numbered and crossreferenced. • All assumptions should be clearly stated or referenced in the statement of any theorems.• The proofs can either appear in the main paper or the supplemental material, but if they appear in the supplemental material, the authors are encouraged to provide a short proof sketch to provide intuition. • Inversely, any informal proof provided in the core of the paper should be complemented by formal proofs provided in appendix or supplemental material. • Theorems and Lemmas that the proof relies upon should be properly referenced. 
experiments: 
 Fine-tuning Datasets. We use the PureBad, Dialog Summary, and Alpaca datasets for fine-tuning. The PureBad dataset, following the same setting as [36] , consists of 100 harmful examples collected through red-teaming. Regarding Dialog Summary [15] , we randomly select 1,000 samples from the Dialog Summary dataset and mix them with the 100 harmful examples from the PureBad dataset. To show the effect of harmful data, we also present the results of different amounts of harmful examples from the PureBad dataset in Appendix A.7. Additionally, we randomly select 200 test samples from the test set of the Dialog Summary dataset. For the Alpaca dataset, we use the same dataset as [36] , totaling 50,098 records, with 200 of them used as the validation set. When fine-tuning the Alpaca dataset, we refrain from adding the 100 harmful samples, as they would lead to a decrease in safety.Data formats for all datasets are shown in Appendix A.3. We call a fine-tuning dataset containing harmful/adversarial examples as an attack.Baseline. Other than LoRA, we consider two defense baselines: SafeInstr [6] and Backdoor Enhanced Alignment (BEA) [46] . For SafeInstr, they demonstrate that fine-tuning models by adding only 3% safety samples can improve their safety. We augment their safe instructions2 into the finetuning datasets, and the number of safety samples is 10% of the PureBad dataset in all experiments.For BEA, pairs of triggers are designed to serve as the secret prompt and safety instructions for the backdoor samples. Therefore, during the inference phase, if the trigger is detected and the user's instructions are harmful, the impact will be mitigated. In our experiments with BEA, we use the official backdoor samples 3 , and the number of backdoor samples is 10% of the PureBad dataset.Evaluation Metrics. Safety: In our experimental results, we use three metrics to evaluate safety, utility, and attack success rate (ASR). For safety, we use the benchmark designed by [36] , which consists of 11 harmful categories merged from OpenAI usage policies and Meta's Llama 2 acceptable use policy. These 11 categories are listed in Appendix A.1. We utilize GPT-4 to judge responses and assign harmfulness scores (ranging from 1 to 5, with lower scores indicating greater safety). Utility: For utility, different datasets have different measurement methods. To evaluate the performance on the Dialog Summary dataset, we compute the Rouge-1 F1 score by comparing the responses generated by LLMs with the ground truth responses across 200 test examples. For the PureBad and Alpaca datasets, we employ MT-Bench [58] to evaluate their utilities and use GPT-4 to assign scores ranging from 1 to 10, with higher scores indicating better quality. ASR: The attack is considered successful if the LLM's response does not contain any keywords indicating a refusal to answer. The keywords list is shown in Appendix A.2. We calculate the average ASR of the benchmark across the 11 categories.Experiment Settings. We use the official fine-tuning scripts from Meta. Regarding the settings of LoRA, we only add LoRA to the "q_proj" and "v_proj" attention layers, and we set the rank to 8 for all experiments. To achieve greater performance on downstream tasks, we may use different training hyperparameters for different datasets. For Llama-2-7B-Chat, we set the learning rate to 5 × 10 -5 , batch size to 5, and run 5 epochs for all datasets. For Llama-3-8B-Instruct, we set the learning rate to 10 -3 , batch size to 5, and run 5 epochs for the PureBad dataset. For the Dialog Summary dataset, we set the learning rate to 10 -4 , batch size to 32, and run 3 epochs. All experiments are conducted on NVIDIA H100 80GB GPUs and AMD ® Epyc 7313 16-core processor × 64. As mentioned in Section 3, Safe LoRA needs to use the alignment matrix. There might be concerns about whether this alignment matrix will consume too many hardware resources. In practice, the alignment does require hardware resources, but it doesn't utilize GPUs. Instead, it can be stored on disk. During projection, it is loaded layer by layer onto GPUs (not all at once), facilitating a swift completion of the projection process.In this section, we demonstrate the effectiveness of Safe LoRA in enhancing safety. It is important to highlight that Safe LoRA does not require any additional training data, unlike both BEA and SafeInstr, which need extra data incorporation. Furthermore, the amount of additional data incorporated plays a significant role in their performance. In Safe LoRA, we compute similarity scores between weights before and after projection on a layer-by-layer basis. A similarity score threshold can be used to determine the number of layers to project, or we can predefine K layers and select the top K similarity score for projection. Additionally, we extend Safe LoRA to full parameter fine-tuning, and the results are demonstrated in Section 4.2.PureBad. Given that users might not always be benign, we fine-tune LLMs using purely malicious samples from the PureBad dataset. We project all LoRA layers for the PureBad dataset because the significant distance between the original LoRA weights and the projected weights indicates that the model has been trained in an unsafe direction. More details are provided in Appendix A. 4 . Besides, we add a baseline named vaccine and show the results in Appendix A.6. Dialog Summary. We present a more practical fine-tuning scenario. We selected a dataset for a task that LLMs were originally not proficient in and required fine-tuning. Additionally, we assume that users might be malicious. Therefore, we augmented the Dialog Summary dataset with 100 harmful samples. We set the similarity score threshold at 0.35, resulting in projections across 7 layers.As shown in Table 3 , the Rouge-1 F1 score of the original Llama-2 model is only 34%, but after fine-tuning, it can reach around 50%. Adding SafeInstr to the training set does not harm utility, but it doesn't sufficiently reduce the harmfulness score. BEA also slightly reduces utility, but like SafeInstr, its performance on the harmfulness score is not as good as Safe LoRA. Safe LoRA's harmfulness score is at least 0.1 lower than theirs, and although its utility slightly decreases, it still approaches 50%. However, one might be curious about whether Safe LoRA might harm the utility of datasets composed entirely of benign samples. We also apply Safe LoRA to the model trained exclusively on non-harmful samples with the same number of projected layers. The results indicate that Safe LoRA does not negatively impact the performance on the benign dataset, maintaining a Rouge-F1 score of approximately 50%.On the other hand, for Llama-3-8B-Instruct, we projected approximately 35% of the total LoRA layers. Since the alignment of Llama-3 is not as strong as that of Llama-2, the effectiveness of the alignment matrix is diminished. Thus, the number of projected layers is greater than for Llama-2. The utility of Safe LoRA can still achieve almost the same result as benign fine-tuning, at 49.04%, while the harmfulness score decreases by around 0.4. SafeInstr gets the highest safety score, but its utility is reduced by 0.12%. Conversely, BEA's utility is better than that of the originally fine-tuned model, but its alignment is also the lowest among the three. Besides, similar to the findings of Llama-2, applying Safe LoRA to models trained without any malicious samples does not result in significant utility degradation. To demonstrate that our method is applicable to various model architectures, we also conducted experiments on the Gemma model and included the results in Appendix A.5. Moreover, we include an extra baseline (Vaccine [18] ) and present the results in Appendix A. Alpaca Dataset. Interesting results demonstrated by [36] show that fine-tuning on a benign dataset can lead to a reduction in safety. We follow the same setting without adding more harmful samples.Here, we use MT-Bench scores as the evaluation metric (higher is better). Table 4 presents results consistent with [36] , showing that the harmfulness score increased from 1.058 to 2.25. Although there is no harmful data in the Alpaca dataset, we still follow previous settings by adding safe instruction samples and backdoor samples for defense. SafeInstr and BEA did not perform well in this scenario due to the larger size of the Alpaca dataset. This highlights one of their drawbacks: they require a sufficient number of safe instructions or backdoor samples in the training set to perform effectively.On the other hand, we have chosen not to present the results for Llama-3 because when using an appropriate learning rate, the ASR only increases by approximately 3%, indicating that alignment is only minimally reduced. Although increasing the learning rate can effectively reduce safety, it also causes significant harm to the model's utility. This approach, therefore, is not suitable for typical user fine-tuning scenarios, as the trade-off between alignment and utility becomes unfavorable. In essence, while a higher learning rate might achieve lower safety scores, the resulting decrease in model utility renders this method impractical for regular use. for all layers of LoRA. In Figures 3 and 4 , we use the Llama-2-Chat model fine-tuned on the Dialog Summary dataset with the same settings as in Section 4.1. Figure 3 clearly demonstrates that projecting more layers tends to cause more harm to utility. At approximately 11% of the total layers projected, there exists a well-balanced point between utility and safety. Here, there is a loss of less than 2% in Rouge F1-Score, while the harmfulness score decreases by more than 2. As shown in Figure 4 , it can be observed that only a few layers display notably low similarity score, represented by the red points. Consequently, by projecting these layers, we can effectively enhance alignment.Full Fine-tuning. In addition to LoRA fine-tuning, we perform full fine-tuning on the PureBad dataset following the same settings as in Section 4.1. The projection process is similar to fine-tuning with LoRA and is formalized as follows:EQUATIONwhere W i pre-trained and W i fine-tuned represent the weights of the pre-trained and fine-tuned models in the i-th layer, respectively. Instead of directly projecting the weights of the fine-tuned model, we project the residual weights between the pre-trained and fine-tuned models.Table 5 demonstrates the performance of Safe LoRA when we perform full parameter fine-tuning on the PureBad dataset using the Llama-2-Chat model. All settings follow those in Section 4.1.Under the same settings, full parameter fine-tuning results in a greater decrease in alignment and utility, with a harmfulness score 0.1 higher and an MT-Bench score at least 0.2 lower compared to LoRA (as shown in Table 2 ). However, with the implementation of Safe LoRA, the harmfulness score dramatically drops to around 1.05. Furthermore, the MT-Bench score also increases to 6.4, a rise of more than 2.Harmfulness Score (↓) MT Broader Impact and Limitations We believe that Safe LoRA presents potential in safeguarding the risk brought upon by various fine-tuning scenarios for LLMs. Unfortunately, the transparency of this method may be subjected to future attacks as they might be able to circumvent this in an adaptive manner. On the other hand, given the increasing trend in model parameter manipulation and the upsurge in GenAI, we believe that Safe LoRA could also be applied to other multimodal models such as Text-to-Image Models to safeguard the alignment rules embedded in their systems.where S represents the sum of the similarities between the projected and non-projected weights across all layers. Table 6 shows S(C∆W, ∆W), where ∆W trained on three datasets under Llama-2-7B-Chat and Llama-3-8B-Instruct. The Alpaca dataset is free of harmful samples. The Dialog Summary dataset includes 100 harmful samples mixed in. The PureBad dataset contains only harmful samples. Therefore, the similarities of models trained on the PureBad dataset are the lowest and differ significantly from those trained on benign datasets or datasets containing a small number of harmful samples.Alpaca Dialog Summary PureBad Llama-2-7B-Chat 0.8006 0.7311 0.4469 Llama-3-8B-Instruct -0.6709 0.4583 We performed additional experiments using the Gemma model. We conducted experiments on the Dialog Summary dataset using the same setup described in Section 4 and present the results in We conduct the official code of Vaccine [18] and train the model on LoRA with the Llama-2 model. Then, we fine-tuned Vaccine models (single/double LoRA setting) with Safe LoRA. We show the results on Dialog Summary and Pure Bad datasets.Single LoRA. We train Vaccine with LoRA (q_proj and v_proj) first and then fine-tuned it on downstream task datasets. As seen in the Table 8 , the Vaccine reduces the harmfulness score to 3.282 on PureBad while the utility (MT-Bench) is not maintained. Furthermore, for Dialog Summary, the utility drops as well while safety shows no improvement.Double LoRA We train Vaccine with LoRA ("q_proj", "k_proj", "v_proj", "o_proj", "up_proj", "down_proj", "gate_proj", the default setting of Vaccine) first, and then fine-tuned another LoRA (q_proj and v_proj) on downstream task. The results shown Table 9 indicate that using double LoRA fine-tuned on Pure Bad reduces utility (MT-Bench). However, the harmfulness score decreases slightly compared to using LoRA fine-tuning. Regarding Dialog Summary, double LoRA is effective in retaining utility scores while the harmfulness increases.We follow the same setting in Section 4 that, for 10% harmful data, there are 7 projected layers. Regarding 30% and 50% harmful data, we project 18 and 34 layers, respectively. From the table Guidelines:• The answer NA means that the paper has no limitation while the answer No means that the paper has limitations, but those are not discussed in the paper. • The authors are encouraged to create a separate "Limitations" section in their paper.• The paper should point out any strong assumptions and how robust the results are to violations of these assumptions (e.g., independence assumptions, noiseless settings, model well-specification, asymptotic approximations only holding locally). The authors should reflect on how these assumptions might be violated in practice and what the implications would be. • The authors should reflect on the scope of the claims made, e.g., if the approach was only tested on a few datasets or with a few runs. In general, empirical results often depend on implicit assumptions, which should be articulated. • The authors should reflect on the factors that influence the performance of the approach.For example, a facial recognition algorithm may perform poorly when image resolution is low or images are taken in low lighting. Or a speech-to-text system might not be used reliably to provide closed captions for online lectures because it fails to handle technical jargon. • The authors should discuss the computational efficiency of the proposed algorithms and how they scale with dataset size. • If applicable, the authors should discuss possible limitations of their approach to address problems of privacy and fairness. • While the authors might fear that complete honesty about limitations might be used by reviewers as grounds for rejection, a worse outcome might be that reviewers discover limitations that aren't acknowledged in the paper. The authors should use their best judgment and recognize that individual actions in favor of transparency play an important role in developing norms that preserve the integrity of the community. Reviewers will be specifically instructed to not penalize honesty concerning limitations.Question: Does the paper fully disclose all the information needed to reproduce the main experimental results of the paper to the extent that it affects the main claims and/or conclusions of the paper (regardless of whether the code and data are provided or not)? Answer: [Yes] Justification: The details of experiment settings are mentioned in Section 4 and 4.1.Guidelines:• The answer NA means that the paper does not include experiments.• If the paper includes experiments, a No answer to this question will not be perceived well by the reviewers: Making the paper reproducible is important, regardless of whether the code and data are provided or not.• If the contribution is a dataset and/or model, the authors should describe the steps taken to make their results reproducible or verifiable. • Depending on the contribution, reproducibility can be accomplished in various ways.For example, if the contribution is a novel architecture, describing the architecture fully might suffice, or if the contribution is a specific model and empirical evaluation, it may be necessary to either make it possible for others to replicate the model with the same dataset, or provide access to the model. In general. releasing code and data is often one good way to accomplish this, but reproducibility can also be provided via detailed instructions for how to replicate the results, access to a hosted model (e.g., in the case of a large language model), releasing of a model checkpoint, or other means that are appropriate to the research performed. • While NeurIPS does not require releasing code, the conference does require all submissions to provide some reasonable avenue for reproducibility, which may depend on the nature of the contribution. , with an open-source dataset or instructions for how to construct the dataset). (d) We recognize that reproducibility may be tricky in some cases, in which case authors are welcome to describe the particular way they provide for reproducibility.In the case of closed-source models, it may be that access to the model is limited in some way (e.g., to registered users), but it should be possible for other researchers to have some path to reproducing or verifying the results. 
open access to data and code: 
 Question: Does the paper provide open access to the data and code, with sufficient instructions to faithfully reproduce the main experimental results, as described in supplemental material?Answer: [Yes] Justification: We will provide codes in supplemental material which will be put on GitHub once ready.Guidelines:• The answer NA means that paper does not include experiments requiring code. Guidelines:• The answer NA means that there is no societal impact of the work performed.• If the authors answer NA or No, they should explain why their work has no societal impact or why the paper does not address societal impact. • Examples of negative societal impacts include potential malicious or unintended uses (e.g., disinformation, generating fake profiles, surveillance), fairness considerations (e.g., deployment of technologies that could make decisions that unfairly impact specific groups), privacy considerations, and security considerations. • The conference expects that many papers will be foundational research and not tied to particular applications, let alone deployments. However, if there is a direct path to any negative applications, the authors should point it out. For example, it is legitimate to point out that an improvement in the quality of generative models could be used to generate deepfakes for disinformation. On the other hand, it is not needed to point out that a generic algorithm for optimizing neural networks could enable people to train models that generate Deepfakes faster. • The authors should consider possible harms that could arise when the technology is being used as intended and functioning correctly, harms that could arise when the technology is being used as intended but gives incorrect results, and harms following from (intentional or unintentional) misuse of the technology. • If there are negative societal impacts, the authors could also discuss possible mitigation strategies (e.g., gated release of models, providing defenses in addition to attacks, mechanisms for monitoring misuse, mechanisms to monitor how a system learns from feedback over time, improving the efficiency and accessibility of ML). 
safeguards: 
 Question: Does the paper describe safeguards that have been put in place for responsible release of data or models that have a high risk for misuse (e.g., pretrained language models, image generators, or scraped datasets)? Answer: [NA] Justification: All models are adapted from the official checkpoints released by other major companies and the main method is intended to propose a safeguard solution to possible risks. Guidelines:• The answer NA means that the paper poses no such risks.• Released models that have a high risk for misuse or dual-use should be released with necessary safeguards to allow for controlled use of the model, for example by requiring that users adhere to usage guidelines or restrictions to access the model or implementing safety filters. • Datasets that have been scraped from the Internet could pose safety risks. The authors should describe how they avoided releasing unsafe images. • We recognize that the procedures for this may vary significantly between institutions and locations, and we expect authors to adhere to the NeurIPS Code of Ethics and the guidelines for their institution. • For initial submissions, do not include any information that would break anonymity (if applicable), such as the institution conducting the review.https://huggingface.co/meta-llama/Llama-2-7bhttps://github.com/vinid/safety-tuned-llamashttps://github.com/Jayfeather1024/Backdoor-Enhanced-Alignment 
 
 Appendix:  


Decision: Thanks for your submission to NeurIPS 2024.
Overall, the reviewers recognize that the paper presents a novel training-free method, Safe LoRA, which introduces the projection of LoRA weights from selected layers to the safety-aligned subspace. The experiment results demonstrate that Safe LoRA can preserve the model's safety performance across downstream tasks and mitigate the negative impact introduced by the malicious data. The reviewers agree that this paper makes important contributions to the community and is valuable to be accepted.

Reviews: review: paper_summary: paper_summary: This paper propose a novel training-free method, Safe LoRA, to project the original LoRA to the sadety-aligned subspace. The experimental results illustrate that the proposed method can preserve the utility of downstream task and the safety of LLM output.
strength_weakness: strength_weakness: Weakness: 

1. I'm still not clear why directly project the LoRA weights to safety subspace can achieve such a great performance. Maybe the authors can provide more analysis and visualization to explain it. Because the proposed method is very simple and efficient and therefore it is more important to illustrate the insights and explain the reason. 

2. I think the experiment setting is special and the authors create these special settings to verify the performance (such as "we augmented the Dialog Summary dataset with 100 harmful samples." ). It would be better if the authors could evaluate the proposed method on more popular benchmarks for testing the safety issue of LLM.
questions: questions: 1. line 213: "Regarding the settings of  LoRA, we only add LoRA to the “q_proj” and “v_proj” attention layers, ". Why do we only consider the “q_proj” and “v_proj” attention layers, which is not a common setting?
limitations: limitations: N/A
paper_summary: paper_summary: The paper proposed a post-hoc fine-tuning projection method which utilizes the aligned and unaligned weights of the model to compute the projection matrix. The method is simple (one-liner patch) and training-free.  Extensive experiments showed the effectiveness of the proposed method.
strength_weakness: strength_weakness: 1. The evaluation is limited. It only focuses on the Llama family which shares very similar architecture

2. The proposed method is named Safe LoRA without justifying that the projection matrix is indeed related to safety. It seems like the main goal of the paper is to constrain the fine-tuned weights to be within a limit of the original weights. 

3. The applicability of the method is unknown. The method seems to highly depend on the fine-tune dataset, e.g. if users want to fine-tune the model to become safer (with all benign fine-tuning datasets) since not all models are equally safety-aligned [1] from the beginning, the proposed method will actually hinder its safety.


[1] Xie, Tinghao, et al. "SORRY-Bench: Systematically Evaluating Large Language Model Safety Refusal Behaviors." arXiv preprint arXiv:2406.14598 (2024).
questions: questions: 1. in table 4, why the utility, harmfulness and ASR score become worse (even for LoRA, especially the utility score) compared to baseline reported in table 2? If fine-tuning on this dataset makes things worse, should we consider evaluating on some other datasets?

2. per my comments in the weakness, although the work is a one-liner patch, the applicability of it is unknown.

3. in both table 4 and table 5, the authors reported decreased harmfulness score and ASR and increased MT-Bench and utility score, does this imply that only harmful data will cause strong (thresholded by $\tau$) dis-similarity through the fine-tuned process?

4. what's the result on other models such as Mistral, Phi and Gemma?
limitations: limitations: The author addressed several limitations of the method. However, I think there are more limitations as mentioned in the weakness and questions section.
paper_summary: paper_summary: This paper studies the problem that finetuning may compromise safety, as observed in the previous work. The author proposes Safe LoRA, a simple one-liner patch to the original LoRA implementation by introducing the projection of LoRA weights from selected layers to the safety-aligned subspace, reducing the safety risks in LLM fine-tuning while maintaining utility. Safe Lora effectively prevents the problem.
strength_weakness: strength_weakness: I didn't see major flaws in the paper. 

Yet, I would like to suggest the author discuss more on the practical application scenario for Safe LoRA. For example, Safe Lora is intended to prevent unintended safety degradation in user fine-tuning or maybe can be applied in service-provider fine-tuning the model. Instead, it will not be applied for user-intended malicious fine-tuning.
Clarifying the scope of the proposed method would make the paper more sound.
questions: questions: Do you think there would be adaptive attacks for the method? How it would be designed? Discussing some related to adaptive attacks may help make the work more comprehensive.
limitations: limitations: The authors have discussed limitations.
paper_summary: paper_summary: This paper proposes Safe LoRA to defend against the harmful finetuning issue for LLMs. The core idea of Safe Lora is to project the harmful gradient update to the subspace constructed by the alignment update.  To guarantee utility performance, the authors propose to use cosine similarity to determine whether the update in a layer should be projected or not.
strength_weakness: strength_weakness: 1) Baseline selection can be more comprehensive. While the authors compare with  SafeInstr and BEA, the authors might also consider comparing with Vaccine (Huang et al, 2024), which is first available earlier than BEA and with source code available. 

Huang T, Hu S, Liu L. Vaccine: Perturbation-aware alignment for large language model[J]. arXiv preprint arXiv:2402.01109, 2024.

2) Some important literature is missing for the discussion. Please consider reviewing these related papers on harmful finetuning. 

[1] Fine-tuning can cripple your foundation model; preserving features may be the solution https://openreview.net/forum?id=VQ7Q6qdp0P (ICLR2024 template) 

[2] Vaccine: Perturbation-aware Alignment for Large Language Model    https://arxiv.org/abs/2402.01109  （ICML2024 template）

[3] Keeping LLMs Aligned After Fine-tuning: The Crucial Role of Prompt Templates https://arxiv.org/pdf/2402.18540 （ACL2024 template）

[4] Immunization against harmful fine-tuning attacks https://arxiv.org/pdf/2402.16382 （ICLR2024 workshop template）

[5] Safety Fine-Tuning at (Almost) No Cost: A Baseline for Vision Large Language Models https://arxiv.org/pdf/2402.02207   （ICML2024 template）

------------------------------------------------------------Concurrent------------------------------------------------------------

[6] Representation noising effectively prevents harmful fine-tuning on LLMs   https://arxiv.org/pdf/2405.14577 （NeurIPS2024 template）

[7] Lazy Safety Alignment for Large Language Models against Harmful Fine-tuning   https://arxiv.org/abs/2405.18641   （NeurIPS2024 template）

[8] No Two Devils Alike: Unveiling Distinct Mechanisms of Fine-tuning Attacks   https://arxiv.org/pdf/2405.16229 （NeurIPS2024 template）

[9] A safety realignment framework via subspace-oriented model fusion for large language models https://arxiv.org/pdf/2405.09055 （also a post-hoc defense like safelora)

[10] Navigating the Safety Landscape: Measuring Risks in Finetuning Large Language Models https://arxiv.org/abs/2405.17374 （NeurIPS2024 template）

I am aware that some of the listed work is concurrent work (e.g., concurrent submissions to NeurIPS 2024). However, it is encouraged to also cite and discuss them, because that will be beneficial for the development of the research field (but the authors should at least cite and discuss those existing works that appeared before the NeurIPS2024 review cycle).

3. The experiment can be more comprehensive. For example, will the ratio of harmful data affect the defense performance?
questions: questions: How do you construct the alignment update in the experiment? In section 3.1, it is claimed that:

> For the aligned and unaligned models, take Meta’s Llama for example, the aligned model will be the Chat model such that they are trained with an alignment goal [43, 28]. On the other hand, the unaligned model could be the aligned model that is fine-tuned with malicious data such that the LLM has lost the safety guardrail and is vulnerable to attacks.

I am wondering in the experiments, are you using harmful data to first unaligned the chat model, and then obtain the alignment update? 

If this is the case, I am wondering if the safe gradient update can also be obtained by these procedures.  i) Use vanilla Llama2 (not chating version) as an unaligned model. ii) Do the alignment on Llama2 and get the aligned model.  iii) Subtract the weights of these two models.
limitations: limitations: The paper discusses the limitations. I don't think the mentioned limitation should be a problem in the acceptance of this paper. I am willing to further increase the score if the authors can provide experiments to address my raised concerns.

Comments: title: Thanks for the Feeback and More Explanation
thanks authors
Thanks for the Feedback
Thanks for your response
Thanks for the Feedback
Thanks for the Feedback
Thanks for the rebuttal
Thanks for the rebuttal. I have increased my score
Clarification of Vaccine Implementation
On Vaccine implementation
More details about Vaccine
Some questions on comparison with Vaccine
Clarification of Alignment Update
Thanks for the rebuttal
comment: We appreciate the reviewer’s feedback, and we are glad to know that we have addressed most of your concerns. Although there are still some concerns about the $\textsf{Safe LoRA}$ method itself and its related application scenarios, we will provide the following explanation in hopes of helping you gain a better understanding.

&nbsp;

**Deeper Insights of $\textsf{Safe LoRA}$**

Currently, there are many related papers dedicated to manipulating models with arithmetic operations to enhance performance or add new functionalities to the models. We can use this concept to explain the working mechanism of $\textsf{Safe LoRA}$, where we improve model safety by projecting unaligned weights onto an aligned hyperspace. In $\textsf{Safe LoRA}$, aligned vectors play a crucial role. If one obtains a vector $A$ by subtracting the base model weights from a non-aligned model, this vector $A$ itself does not represent alignment. Using such a vector to create a projection matrix will not enhance safety when projecting fine-tuned weights onto it. This is why we need to derive the so-called aligned vectors from an aligned model. We do not arbitrarily manipulate the fine-tuned weights, nor do we simply restrict the distance of the fine-tuned weights from the original ones. Restricting this distance alone can lead to a decrease in utility and does not guarantee an improvement in safety. In summary, $\textsf{Safe LoRA}$ enhances safety by manipulating fine-tuned weights that are **further** from the aligned direction, pulling them back into the aligned hyperspace while maintaining utility.

&nbsp;

**Application Scenario**

We will provide a more detailed explanation of the two application scenarios we mentioned earlier.

* **Benign User**

   First, we explain why a benign user would need to use $\textsf{Safe LoRA}$. As demonstrated in the experiments from the paper, even if the training data is entirely benign, alignment can still be compromised. Therefore, $\textsf{Safe LoRA}$ is necessary to address this issue.

  Next, we discuss why a benign user needs to perform fine-tuning. Although current LLMs can indeed provide very logical question-and-answer interactions, using them directly as customer service bots to answer specific questions from customers is often insufficient. This is because LLMs typically lack information relevant to a particular company. Therefore, fine-tuning an existing LLM on the user’s data becomes necessary to tailor it to the company's specific needs and information.

  Finally, combining the above two points, users need to fine-tune models using their own data. However, since fine-tuning can potentially lead to a loss of alignment, and generally, users do not want their customer service bots to provide inappropriate responses—because this could damage the company's reputation and increase crime rates (as it becomes easier to access harmful information)—$\textsf{Safe LoRA}$ becomes necessary to address these concerns.

* **LLM API Provider**

  The most common LLM API provider is OpenAI's ChatGPT. It allows users to upload data and configure relevant training parameters to fine-tune ChatGPT. However, since users are not always well-intentioned, there is a risk that they might upload malicious data. The LLM API provider cannot individually check each piece of data for harm, as this would be too time-consuming and would negatively impact the user experience. This is different from how ChatGPT checks user inputs for appropriateness during conversations. The volume of training data can be very large, making it impractical to check each piece individually. In fact, OpenAI currently does not perform checks on users' training data. **So why is $\textsf{Safe LoRA}$ necessary?** If a user uploads malicious data that removes alignment, they can fine-tune the model and then start querying it with harmful questions, potentially obtaining inappropriate answers. This undermines the alignment efforts made by LLM API providers, as malicious users could effectively bypass these safeguards by spending a small amount of money to get an unaligned model that can provide any response they desire. This issue could potentially increase societal risks by making it easier for people to access inappropriate information.

Overall, $\textsf{Safe LoRA}$ allows model owners to restore their safety guardrails in an efficient manner regardless of any harmful data present.

We hope that the detailed explanations we have provided about the $\textsf{Safe LoRA}$ method and its insight, as well as its application scenarios, will enhance your understanding of $\textsf{Safe LoRA}$ and its use cases. Thank you once again for taking the time to review the explanations provided. We hope that your concerns have been addressed.
thank the authors for the rebuttal. After reading it and other reviewer's comments, I have raise my score to 5. My concerns are mostly resolved. I didn't give a higher score because I still feel a deeper understanding of the method should be pursued and the application scenario is not fully convincing. I didn't give a lower score because as an academic paper, I feel there is merit in accepting this paper. good luck!
We sincerely thank the reviewer for the response and we felt honored that we could solve your concern, making more understanding towards the re-alignment problem of LLMs.
Thanks for your response. 

The authors have solved my concerns.
We are grateful for the reviewer's prompt response and for the decision to increase the score. The use cases for Safe LoRA and the potential adaptive attacks are indeed crucial aspects. We will incorporate these discussions into our paper to make it more comprehensive.
We appreciate the reviewer's active engagement in the discussion at this stage and the decision to raise the score. It is indeed possible that adding perturbations to an aligned model could disrupt the alignment, potentially making Vaccine's results less effective. However, Vaccine represents an initial but important solution to the realignment problem of LLMs. We will also include the results of Vaccine in the next version of our paper.
Thanks for the rebuttal, which answers my questions. I increase the score to 7.
Thanks for the clarification. Vaccine fails in some of your experiments probably because adding perturbation might break the original alignment of the Llama2-chat model (I think originally they used Llama2 (unaligned) model as base model).  Safe Lora does not have that issue because it is a post-fine-tuning solution. That said, I still encourage the authors to include the comparison results with Vaccine into their next version of the paper, as they show a new observation and also show the superiority of the Safe Lora method.   

I appreciate the author's willingness to provide additional experiments/baselines to enrich their work.  I therefore increase my score to 7. I will also actively participate the reviewer-AC discussion phase to support this paper.
Thank you for the reviewer's feedback. You are correct that Alpaca is not an alignment dataset; we misunderstood its role. However, we used the official code provided [R1] and ran "*Vaccine.sh*" **without any modifications** to train Vaccine. Thus, the **alignment dataset we used is indeed BeaverTails_safe**. Vaccine mixed the Alpaca dataset with BeaverTails to prevent potential performance degradation that could occur from using only BeaverTails, thus incorporating normal data with Alpaca.

&nbsp;

[R1] https://github.com/git-disl/Vaccine/blob/main/script/alignment/Vaccine.sh
Hi, thanks for the quick answer. If I got it correctly, in their official code, the alignment dataset used by Vaccine is not Alpaca, but a harmful prompt-safe answer dataset named BeaverTails. Aligned the model with Alpaca is not a correct way.  

I hope the  authors can address this issue, as a fair evaluation with baselines is our important to the value of the work.
Thank you for the reviewer's suggestion. We will emphasize after equation (1) that, in practice, we use the base model as the unaligned model, so users do not need additional data and training processes to obtain an unaligned model.

&nbsp;

We also appreciate the reviewer's additional question regarding the Vaccine implementation. We used the **Llama-2 Chat model** as the base model for Vaccine and followed the official code, which utilizes **Alpaca** as the alignment dataset.
Thanks for the prompt answer of constructing alignment update, I think the authors can modify the equation to showcase this as this is a very important procedure. I am kind of confused about this point when reading your paper.

I still have a few questions regarding the comparison with Vaccine:

1. are you using chat model (aligned model) as the base model for Vaccine? 
2. what alignment dataset you are using to train Vaccine?
We thank the reviewer for the additional question which we will try to clarify as the following. In Section 3.1, we explain $\textsf{Safe LoRA}$ by constructing the alignment update with the unaligned model, i.e., alignment update = chat - unaligned. However, as mentioned in the rebuttal and original paper “*We discovered that … are identical to those of the base model*”. The base model is eventually considered to construct the alignment update in $\textsf{Safe LoRA}$, i.e., **alignment update = chat - base and all subsequent experiments (Table 1 through 5), as it is a more practical scenario**.
Thanks for the rebuttal. I am not sure how to buid alignment update in **your experiment**. Which way you are using?

1. Use harmful data to first unaligned the chat model, and then obtain the alignment update.

2. Use vanilla Llama2 (not chating version) as an unaligned model. ii) Do the alignment on Llama2 and get the aligned model. iii) Subtract the weights of these two models.