SafeMERGE: Fine-Tuning 후 Safety Alignment를 보존하는 선택적 Layer-Wise Model Merging
SafeMERGE: Preserving Safety Alignment in Fine-Tuned Large Language Models via Selective Layer-Wise Model Merging
TL;DR Highlight
LLM을 파인튜닝하면 안전성이 깨지는데, 위험해진 레이어만 골라서 안전한 모델과 합쳐 복구하는 경량 프레임워크.
Who Should Read
Llama, Qwen 같은 오픈소스 LLM을 특정 도메인에 파인튜닝해서 서비스하는 ML 엔지니어 또는 LLM 안전성(Safety)을 고민하는 AI 백엔드 개발자.
Core Mechanics
- 파인튜닝만 해도 안전성이 망가짐 — 악의적 데이터 없이 수학/의료 같은 일반 태스크 학습만 해도 유해 응답 비율이 최대 5배 이상 뛰어오름
- SafeMERGE는 '파인튜닝 후' 단계에서 개입 — 기존 학습 파이프라인을 전혀 바꾸지 않아도 됨
- 핵심 아이디어: cosine similarity로 레이어별 안전성 이탈 여부를 탐지하고, 위험한 레이어만 안전 모델의 레이어와 선택적으로 병합
- Llama-2-7B-Chat(GSM8K) 기준 DirectHarm 27.80% → 7.50%로 감소하면서 정확도는 오히려 27.37% → 26.96% 유지
- Llama-3.1-8B-Instruct에서는 파인튜닝 정확도(78.24%)보다 더 높은 78.50%를 달성하면서 동시에 가장 낮은 유해성 달성
- 안전 모델은 태스크 무관(task-agnostic)하게 한 번만 만들면 여러 파인튜닝 태스크에 재사용 가능 — 공개 안전 데이터셋 100~2500개 샘플이면 충분
Evidence
- Qwen-2-7B-Instruct(GSM8K): SafeMERGE DirectHarm 8.20% vs 파인튜닝 25.30% — 경쟁 방법 중 가장 낮은 유해성, SafeLoRA(22.30%) 대비 3배 개선
- Llama-3.1-8B-Instruct(PubMedQA): SafeMERGE DirectHarm 9.10% vs 파인튜닝 23.50%, 유틸리티 79.00%로 파인튜닝(78.80%)보다도 높음
- 안전 모델 학습에 1000개 샘플만 사용해도 DirectHarm Llama-2 기준 1.30%, Llama-3.1 기준 6.30% 달성 — 추가 데이터 비용 최소화
- τ=0.7 임계값에서 Llama-2는 전체 56개 레이어 중 28개만 병합 — 절반 이하 레이어 수정으로 충분한 효과
How to Apply
- 기존 LoRA 파인튜닝 파이프라인 유지 → 학습 완료 후 공개 안전 데이터셋(예: Bianchi et al. 2024 safety collection) 1000개로 별도 safety LoRA 어댑터를 한 번만 학습 → base/instruct 모델 가중치 차이로 safety subspace 계산 → cosine similarity < τ(≈0.7)인 레이어만 [0.8, 0.2] 비율로 선형 병합
- 의료, 법률, 통신 등 특수 도메인 파인튜닝 서비스를 운영 중이라면, 배포 전 SafeMERGE를 post-processing 단계로 추가해 유해 응답 비율을 원본 instruct 모델 수준 이하로 낮출 수 있음
- safety LoRA 어댑터는 태스크 무관하게 재사용 가능하므로, 여러 도메인 모델을 운영하는 경우 어댑터를 한 번 만들어두고 모든 파인튜닝 결과물에 적용하면 됨
Code Example
# SafeMERGE 핵심 로직 (PyTorch + PEFT 기반 의사코드)
import torch
from peft import PeftModel
def compute_safety_subspace(aligned_model, base_model, layer_name):
"""V_i = W_aligned - W_base (레이어별 safety alignment 방향)"""
W_aligned = dict(aligned_model.named_parameters())[layer_name]
W_base = dict(base_model.named_parameters())[layer_name]
return W_aligned - W_base
def cosine_similarity_to_subspace(delta_W, V):
"""LoRA 업데이트가 safety subspace에서 얼마나 벗어났는지 측정"""
V_norm = V / torch.norm(V, 'fro')
projection = V_norm @ V_norm.T @ delta_W # C * delta_W
cos_sim = torch.nn.functional.cosine_similarity(
delta_W.flatten().unsqueeze(0),
projection.flatten().unsqueeze(0)
)
return cos_sim.item()
def safe_merge(
finetuned_lora, # 파인튜닝된 LoRA 어댑터
safe_lora, # safety 데이터로 학습한 LoRA 어댑터
aligned_model, # instruct/chat 모델
base_model, # base 모델
tau=0.7, # cosine similarity 임계값
alpha=0.8 # 파인튜닝 모델 가중치 (1-alpha = safety 모델 가중치)
):
merged_weights = {}
for layer_name, delta_W_f in finetuned_lora.items():
# safety subspace 계산
V = compute_safety_subspace(aligned_model, base_model, layer_name)
# 해당 레이어의 cosine similarity 측정
rho = cosine_similarity_to_subspace(delta_W_f, V)
if rho < tau:
# 안전성이 저하된 레이어 → safety 모델과 선형 병합
delta_W_s = safe_lora[layer_name]
merged_weights[layer_name] = alpha * delta_W_f + (1 - alpha) * delta_W_s
print(f"[MERGE] {layer_name}: rho={rho:.3f} < tau={tau}")
else:
# 안전한 레이어 → 파인튜닝 가중치 그대로 유지
merged_weights[layer_name] = delta_W_f
return merged_weights
# 사용 예시
# merged = safe_merge(finetuned_lora, safe_lora, aligned_model, base_model, tau=0.7, alpha=0.8)
# → 위험한 레이어만 선택적으로 병합된 최종 LoRA 어댑터 반환Terminology
Related Resources
Original Abstract (Expand)
Fine-tuning large language models (LLMs) is a common practice to adapt generalist models to specialized domains. However, recent studies show that fine-tuning can erode safety alignment, causing LLMs to respond to harmful or unethical prompts. Many methods to realign safety have been proposed, but often introduce custom algorithms that are difficult to implement or compromise task utility. In this work, we propose SafeMERGE, a lightweight, post-fine-tuning framework that preserves safety while maintaining downstream performance. SafeMERGE selectively merges fine-tuned with safety-aligned model layers only when they deviate from safe behavior, measured by a cosine similarity criterion. Across three LLMs and two tasks, SafeMERGE consistently reduces harmful outputs compared to other defenses, with negligible or even positive impact on utility. Our results demonstrate that selective layer-wise merging offers an effective safeguard against the inadvertent loss of safety during fine-tuning, establishing SafeMERGE as a simple post-fine-tuning defense.