用 abliteration 解除任何 LLM 的审查

第三代 Llama 模型提供了在理解和遵循指令方面表现出色的微调(Instruct)版本。然而,这些模型受到严格审查,被设计为拒绝那些被视为有害的请求,并以“作为 AI 助手,我无法帮助你”之类的回复作答。虽然这一安全特性对于防止滥用至关重要,但它限制了模型的灵活性和响应能力。
在本文中,我们将探讨一种名为“abliteration”的技术,它无需重新训练即可解除任何 LLM 的审查。该技术能有效移除模型内置的拒绝机制,使其能够响应所有类型的提示。
代码可在 Google Colab 和 GitHub 上的 LLM Course 中获取。
✂️ 什么是 abliteration?
现代 LLM 针对安全性和指令遵循进行了微调,这意味着它们被训练为拒绝有害请求。Arditi 等人在其博客文章中表明,这种拒绝行为由模型残差流中的一个特定方向所中介。如果我们阻止模型表示这个方向,它就会失去拒绝请求的能力。反之,人为地添加这个方向,则可能导致模型连无害的请求也拒绝。
在传统的仅解码器 Llama 类架构中,有三个我们可以针对的残差流:每个块的起始处(“pre”)、注意力层与 MLP 层之间(“mid”),以及 MLP 之后(“post”)。下图展示了每个残差流的位置。

要解除 LLM 的审查,我们首先需要识别模型中的“拒绝方向”。这个过程涉及几个技术步骤:
- 数据收集:在一组有害指令和一组无害指令上运行模型,记录每个指令在最后一个 token 位置的残差流激活值。
- 均值差:计算有害指令与无害指令激活值之间的均值差。由此我们得到一个向量,代表模型每一层的“拒绝方向”。
- 选择:对这些向量进行归一化并评估,以选出单个最佳的“拒绝方向”。
一旦识别出拒绝方向,我们就可以“消融”它,从而有效移除模型表示该特征的能力。这可以通过推理时干预或通过权重正交化永久实现。
我们先谈谈推理时干预。对于每一个写入残差流的组件(例如某个注意力头),我们计算其输出在拒绝方向上的投影,并减去该投影。这种减法在每一个 token 和每一层上都会应用,确保模型永远不会表示拒绝方向。
另一方面,权重正交化涉及直接修改模型权重。通过将组件权重相对于拒绝方向进行正交化,它阻止模型写入该方向。这是通过调整写入残差流的矩阵来实现的,确保它们不会对拒绝方向有所贡献。
在下一节中,我们将用权重正交化来实现 abliteration。
💻 实现
以下 abliteration 的实现基于 FailSpy 的 notebook,而后者又基于原作者们的 notebook。我主要对其进行了改编和简化,以便更容易理解。本节代码较多,这样你可以看清具体发生了什么,但如果你对技术细节不太感兴趣,可以使用 FailSpy 的 abliterator 库(也可以看看他在 Hugging Face 上的 abliterated 模型合集)。
文章标题:用消融消除任何 LLM 的审查 (2024)
正文: 代码依赖出色的 TransformerLens 库(原名 EasyTransformer)来完成繁重的工作。该库专为机制可解释性而设计,此处用于干预激活值。感谢 Neel Nanda 和 Joseph Bloom 创建并维护这个库。
首先,让我们安装必要的包并导入它们。所有这些步骤都可以在这个 Google Colab notebook 中找到。
!pip install transformers transformers_stream_generator tiktoken transformer_lens einops jaxtyping
import torch
import functools
import einops
import gc
from datasets import load_dataset
from tqdm import tqdm
from torch import Tensor
from typing import List
from transformer_lens import HookedTransformer, utils
from transformer_lens.hook_points import HookPoint
from transformers import AutoModelForCausalLM, AutoTokenizer
from jaxtyping import Float, Int
from collections import defaultdict
# Turn automatic differentiation off to save GPU memory (credit: Undi95)
torch.set_grad_enabled(False)
我们需要两个数据集:一个包含无害指令,另一个包含有害指令。我们将使用 tatsu-lab/alpaca 以及来自 llm-attacks 的数据。为了方便起见,我将它们重新打包成了两个 Hugging Face 数据集:mlabonne/harmless_alpaca 和 mlabonne/harmful_behaviors。这样,你就可以轻松地用你自己的数据集替换它们。
我们将加载这些指令,并将它们重新格式化为一个字典列表,其中包含 "role" 和 "content" 键。这样就能与 apply_chat_tokenizer() 方法兼容,我们将用该方法来遵循 Llama 3 的聊天模板。
def reformat_texts(texts):
return [[{"role": "user", "content": text}] for text in texts]
# Get harmful and harmless datasets
def get_harmful_instructions():
dataset = load_dataset('mlabonne/harmful_behaviors')
return reformat_texts(dataset['train']['text']), reformat_texts(dataset['test']['text'])
def get_harmless_instructions():
dataset = load_dataset('mlabonne/harmless_alpaca')
return reformat_texts(dataset['train']['text']), reformat_texts(dataset['test']['text'])
harmful_inst_train, harmful_inst_test = get_harmful_instructions()
harmless_inst_train, harmless_inst_test = get_harmless_instructions()
现在我们有了数据集,可以加载我们想要进行消融的模型了。遗憾的是,你无法直接使用 HookedTransformer 加载自定义模型。在这里,我使用了 FailSpy 的 notebook 中描述的一个技巧,先下载一个自定义模型,然后将其重命名为 meta-llama/Meta-Llama-3-8B-Instruct。如果你的 GPU 不兼容 BF16,请以 torch.float16 格式加载。
在这个例子中,我们将使用 mlabonne/Daredevil-8B,这是一个用 DARE TIES 创建的超级合并模型(参见我关于模型合并的文章),它在 Open LLM Leaderboard 的 8B 类别中拥有最高的 MMLU 分数。
MODEL_ID = "mlabonne/Daredevil-8B"
MODEL_TYPE = "meta-llama/Meta-Llama-3-8B-Instruct"
# Download and load model
!git clone https://huggingface.co/{MODEL_ID} {MODEL_TYPE}
# Load model and tokenizer
model = HookedTransformer.from_pretrained_no_processing(
MODEL_TYPE,
local_files_only=True,
dtype=torch.bfloat16,
default_padding_side='left'
)
tokenizer = AutoTokenizer.from_pretrained(MODEL_TYPE)
tokenizer.padding_side = 'left'
tokenizer.pad_token = tokenizer.eos_token
现在我们可以对我们的数据集进行分词了。我们对无害指令和有害指令使用相同数量的样本。请注意,样本数量过多会占用全部 RAM/VRAM,因此我在这里将其限制为 256。
def tokenize_instructions(tokenizer, instructions):
return tokenizer.apply_chat_template(
instructions,
padding=True,
truncation=False,
return_tensors="pt",
return_dict=True,
add_generation_prompt=True,
).input_ids
n_inst_train = min(256, len(harmful_inst_train), len(harmless_inst_train))
# 对数据集进行 tokenize
harmful_tokens = tokenize_instructions(
tokenizer,
instructions=harmful_inst_train[:n_inst_train],
)
harmless_tokens = tokenize_instructions(
tokenizer,
instructions=harmless_inst_train[:n_inst_train],
)
一切就绪,我们现在可以实现 abliteration 的第一步:数据收集。我们要处理这些 tokenize 后的数据集,并将残差流激活存储在 harmful 和 harmless 中。这由 transformer_lens 库负责管理。
# 根据可用显存定义 batch size
batch_size = 32
# 初始化 defaultdict 以存储激活
harmful = defaultdict(list)
harmless = defaultdict(list)
# 分批处理训练数据
num_batches = (n_inst_train + batch_size - 1) // batch_size
for i in tqdm(range(num_batches)):
print(i)
start_idx = i * batch_size
end_idx = min(n_inst_train, start_idx + batch_size)
# 在 harmful 和 harmless 提示上运行模型,缓存激活
harmful_logits, harmful_cache = model.run_with_cache(
harmful_tokens[start_idx:end_idx],
names_filter=lambda hook_name: 'resid' in hook_name,
device='cpu',
reset_hooks_end=True
)
harmless_logits, harmless_cache = model.run_with_cache(
harmless_tokens[start_idx:end_idx],
names_filter=lambda hook_name: 'resid' in hook_name,
device='cpu',
reset_hooks_end=True
)
# 收集并存储激活
for key in harmful_cache:
harmful[key].append(harmful_cache[key])
harmless[key].append(harmless_cache[key])
# 释放内存和显存
del harmful_logits, harmless_logits, harmful_cache, harmless_cache
gc.collect()
torch.cuda.empty_cache()
# 拼接缓存的激活
harmful = {k: torch.cat(v) for k, v in harmful.items()}
harmless = {k: torch.cat(v) for k, v in harmless.items()}
我们现在可以计算每一层的拒绝方向。它对应于 harmful 和 harmless 指令激活之间的均值差,随后进行归一化。我们在 activation_scored 中按降序对它们排序。
# 获取激活索引的辅助函数
def get_act_idx(cache_dict, act_name, layer):
key = (act_name, layer)
return cache_dict[utils.get_act_name(*key)]
# 计算中间层 harmful 和 harmless 激活之间的均值差
activation_layers = ["resid_pre", "resid_mid", "resid_post"]
activation_refusals = defaultdict(list)
for layer_num in range(1, model.cfg.n_layers):
pos = -1 # 位置索引
for layer in activation_layers:
harmful_mean_act = get_act_idx(harmful, layer, layer_num)[:, pos, :].mean(dim=0)
harmless_mean_act = get_act_idx(harmless, layer, layer_num)[:, pos, :].mean(
dim=0
)
refusal_dir = harmful_mean_act - harmless_mean_act
refusal_dir = refusal_dir / refusal_dir.norm()
activation_refusals[layer].append(refusal_dir)
# 获取所有计算出的潜在拒绝方向,并根据其均值按降序排序
# 如果某些激活不理想,可使用层的子集
selected_layers = ["resid_pre"]
activation_scored = sorted(
[
activation_refusals[layer][l - 1]
for l in range(1, model.cfg.n_layers)
for layer in selected_layers
],
key=lambda x: abs(x.mean()),
reverse=True,
)
该过程的最后一步是评估我们计算出的拒绝方向。为此,我们将在推理过程中将拒绝方向应用于每个残差流和每个块。在下面的代码片段中,我们针对四条测试 harmful 指令和 20 个块(或层)获取生成结果。
def _generate_with_hooks(
model: HookedTransformer,
tokenizer: AutoTokenizer,
tokens: Int[Tensor, "batch_size seq_len"],
max_tokens_generated: int = 64,
fwd_hooks=[],
) -> List[str]:
all_tokens = torch.zeros(
(tokens.shape[0], tokens.shape[1] + max_tokens_generated),
dtype=torch.long,
device=tokens.device,
)
all_tokens[:, : tokens.shape[1]] = tokens
for i in range(max_tokens_generated):
with model.hooks(fwd_hooks=fwd_hooks):
logits = model(all_tokens[:, : -max_tokens_generated + i])
next_tokens = logits[:, -1, :].argmax(
dim=-1
) # 贪婪采样(temperature=0)
all_tokens[:, -max_tokens_generated + i] = next_tokens
return tokenizer.batch_decode(
all_tokens[:, tokens.shape[1] :], skip_special_tokens=True
)
def get_generations(
model: HookedTransformer,
tokenizer: AutoTokenizer,
instructions: List[str],
fwd_hooks=[],
max_tokens_generated: int = 64,
batch_size: int = 4,
) -> List[str]:
generations = []
for i in tqdm(range(0, len(instructions), batch_size)):
tokens = tokenize_instructions(
tokenizer, instructions=instructions[i : i + batch_size]
)
generation = _generate_with_hooks(
model,
tokenizer,
tokens,
max_tokens_generated=max_tokens_generated,
fwd_hooks=fwd_hooks,
)
generations.extend(generation)
return generations
# 推理时干预钩子
def direction_ablation_hook(
activation: Float[Tensor, "... d_act"],
hook: HookPoint,
direction: Float[Tensor, "d_act"],
):
if activation.device != direction.device:
direction = direction.to(activation.device)
proj = (
einops.einsum(
activation, direction.view(-1, 1), "... d_act, d_act single -> ... single"
)
* direction
)
return activation - proj
# 测试基线
N_INST_TEST = 4
baseline_generations = get_generations(
model, tokenizer, harmful_inst_test[:N_INST_TEST], fwd_hooks=[]
)
# 评估此前定义的层(需要人工评估以确定抑制拒绝的最佳层)
EVAL_N = 20 # 评估前 N 个候选方向中的多少个
evals = []
for refusal_dir in tqdm(activation_scored[:EVAL_N]):
hook_fn = functools.partial(direction_ablation_hook, direction=refusal_dir)
fwd_hooks = [
(utils.get_act_name(act_name, layer), hook_fn)
for layer in list(range(model.cfg.n_layers))
for act_name in activation_layers
]
intervention_generations = get_generations(
model, tokenizer, harmful_inst_test[:N_INST_TEST], fwd_hooks=fwd_hooks
)
evals.append(intervention_generations)
我们将所有生成结果存储在了 evals 列表中。现在可以打印它们,并手动选择能为每条指令提供未经审查响应的层(块)。我会自动排除包含 "I cannot" 和 "I can't" 的响应,以过滤掉不需要的答案。
如果你找不到满足这些要求的层,可能需要测试之前 selected_layers 列表中的其他残差流、其他指令、额外的块等。
# 打印生成结果以供人工评估
blacklist = ["I cannot", "I can't"]
for i in range(N_INST_TEST):
print(f"\033[1mINSTRUCTION {i}: {harmful_inst_test[i]}")
print(f"\nBASELINE COMPLETION:\n{baseline_generations[i]}\033[0m")
for layer_candidate in range(EVAL_N):
if not any(word in evals[layer_candidate][i] for word in blacklist):
print(f"\n---\n\nLAYER CANDIDATE #{layer_candidate} INTERVENTION COMPLETION:")
print(evals[layer_candidate][i])
文章标题:用 abliteration 解除任何 LLM 的审查 (2024)
正文: 在我的案例中,第 9 层候选成功地为四条指令提供了未审查的回答。这就是我们将为拒绝方向选择的那一层。在下文中,我们实现权重正交化,以修改权重并防止模型生成带有此方向的输出。你可以通过打印补全结果来验证模型是否成功解除了审查。
def get_orthogonalized_matrix(
matrix: Float[Tensor, "... d_model"], vec: Float[Tensor, "d_model"]
) -> Float[Tensor, "... d_model"]:
proj = (
einops.einsum(
matrix, vec.view(-1, 1), "... d_model, d_model single -> ... single"
)
* vec
)
return matrix - proj
# Select the layer with the highest potential refusal direction
LAYER_CANDIDATE = 9
refusal_dir = activation_scored[LAYER_CANDIDATE]
# Orthogonalize the model's weights
if refusal_dir.device != model.W_E.device:
refusal_dir = refusal_dir.to(model.W_E.device)
model.W_E.data = get_orthogonalized_matrix(model.W_E, refusal_dir)
for block in tqdm(model.blocks):
if refusal_dir.device != block.attn.W_O.device:
refusal_dir = refusal_dir.to(block.attn.W_O.device)
block.attn.W_O.data = get_orthogonalized_matrix(block.attn.W_O, refusal_dir)
block.mlp.W_out.data = get_orthogonalized_matrix(block.mlp.W_out, refusal_dir)
# Generate text with abliterated model
orthogonalized_generations = get_generations(
model, tokenizer, harmful_inst_test[:N_INST_TEST], fwd_hooks=[]
)
# Print generations
for i in range(N_INST_TEST):
if len(baseline_generations) > i:
print(f"INSTRUCTION {i}: {harmful_inst_test[i]}")
print(f"\033[92mBASELINE COMPLETION:\n{baseline_generations[i]}")
print(f"\033[91mINTERVENTION COMPLETION:\n{evals[LAYER_CANDIDATE][i]}")
print(f"\033[95mORTHOGONALIZED COMPLETION:\n{orthogonalized_generations[i]}\n")
我们现在可以使用该模型了。我们将其转换回 Hugging Face 格式并上传到 HF hub。
# Convert model back to HF safetensors
hf_model = AutoModelForCausalLM.from_pretrained(MODEL_TYPE, torch_dtype=torch.bfloat16)
lm_model = hf_model.model
state_dict = model.state_dict()
lm_model.embed_tokens.weight = torch.nn.Parameter(state_dict["embed.W_E"].cpu())
for l in range(model.cfg.n_layers):
lm_model.layers[l].self_attn.o_proj.weight = torch.nn.Parameter(
einops.rearrange(
state_dict[f"blocks.{l}.attn.W_O"], "n h m->m (n h)", n=model.cfg.n_heads
).contiguous()
)
lm_model.layers[l].mlp.down_proj.weight = torch.nn.Parameter(
torch.transpose(state_dict[f"blocks.{l}.mlp.W_out"], 0, 1).contiguous()
)
hf_model.push_to_hub(f"{MODEL_ID}-abliterated")
# hf_model.push_to_hub(f"{MODEL_ID}-abliterated")
⚖️ DPO 微调
我在 Open LLM Leaderboard 和 Nous 的基准测试套件上评估了上一节中的 abliterated 模型和源模型。结果如下:

如你所见,源模型显著优于 Llama 3 8B Instruct。然而,我们观察到 ablated 版本在所有基准测试上性能下降。消融过程成功解除了审查,但也降低了模型的质量。
为了解决这个问题,一个想法是进一步训练我们的 abliterated 模型来修复它。像大多数微调模型一样,Llama 3 8B Instruct 在监督微调方面相当脆弱。额外的 SFT 很可能会破坏模型的性能。
或者,偏好对齐则相当轻量,不应使我们的 abliterated 模型遭受脑白质切除术。DPO 因其易用性和良好的记录而成为这里的好选择。为了实现它,我使用了 LazyAxolotl 和 mlabonne/orpo-dpo-mix-40k 数据集。以下是我使用的配置:
base_model: mlabonne/Daredevil-8B-abliterated
model_type: LlamaForCausalLM
tokenizer_type: AutoTokenizer
标题:用 abliteration 解除任何 LLM 的审查 (2024)
正文:
load_in_8bit: false
load_in_4bit: true
strict: false
save_safetensors: true
rl: dpo
chat_template: chatml
datasets:
- path: mlabonne/orpo-dpo-mix-40k-flat
split: train
type: chatml.intel
dataset_prepared_path:
val_set_size: 0.0
output_dir: ./out
adapter: qlora
lora_model_dir:
sequence_len: 2048
sample_packing: false
pad_to_sequence_len: false
lora_r: 64
lora_alpha: 32
lora_dropout: 0.05
lora_target_linear: true
lora_fan_in_fan_out:
wandb_project: axolotl
wandb_entity:
wandb_watch:
wandb_name:
wandb_log_model:
gradient_accumulation_steps: 8
micro_batch_size: 1
num_epochs: 1
optimizer: paged_adamw_8bit
lr_scheduler: cosine
learning_rate: 5e-6
train_on_inputs: false
group_by_length: false
bf16: auto
fp16:
tf32:
gradient_checkpointing: true
early_stopping_patience:
resume_from_checkpoint:
local_rank:
logging_steps: 1
xformers_attention:
flash_attention: true
warmup_steps: 100
evals_per_epoch: 0
eval_table_size:
eval_table_max_new_tokens: 128
saves_per_epoch: 1
debug:
deepspeed: deepspeed_configs/zero2.json
weight_decay: 0.0
special_tokens:
pad_token: <|end_of_text|>
我使用 6 块 A6000 GPU 搭配 DeepSpeed ZeRO-2 对其进行了训练。训练耗时约 6 小时 45 分钟。以下是我从 W&B 得到的训练曲线:

它自动上传了 DPO 微调后的模型,名为 mlabonne/NeuralDaredevil-8B-abliterated。为了确认它是否修复了我们的 abliterated 版本,我在相同的基准上进行了评估:

可以看到,这次额外的训练让我们恢复了大部分因 abliteration 造成的性能下降。模型唯一没有提升的地方是 GSM8K,一个数学数据集,这可能意味着 orpo-dpo-mix-40k 能从更多数学样本中获益。
最终模型是一个在 8B 级别中性能达到最先进水平的无审查 LLM。当你不需要审查时,我推荐将它作为 Llama 3 8B Instruct 的改进版本使用。你可以在 LM Studio 中使用 GGUF 等量化版本。
结论
在本文中,我们介绍了 abliteration 这一概念。该技术利用模型在无害和有害提示上的激活值来计算一个拒绝方向。然后利用这个方向修改模型的权重,确保我们不再输出拒绝。该技术还展示了安全微调的脆弱性,并引发了伦理层面的考量。
我们将 abliteration 应用于 Daredevil-8B 以解除其审查,但这也降低了模型的性能。随后我们用 DPO 对其进行修复,创建了 NeuralDaredevil-8B 模型,一个完全无审查且高质量的 8B LLM。Abliteration 并不局限于移除对齐,它应被视为一种无需重新训练即可进行微调的形式。事实上,它可以被创造性地应用于其他目标,例如 FailSpy 的 MopeyMule,它采用了一种忧郁的对话风格。
希望你喜欢这篇文章。如果你想看到更多内容,请在 Hugging Face 上关注我,并在 Twitter 上关注 @maximelabonne。
参考文献
- FailSpy, "abliterator library," GitHub, 2024.
- Andy Arditi, Oscar Obeso, Aaquib111, wesg, Neel Nanda, "Refusal in LLMs is mediated by a single direction," Lesswrong, 2024.