Project a unit refusal direction out of the residual-stream writes (attention, linear-attention and MLP outputs, and token embeddings) at runtime, enabled by VLLM_ABLITERATION pointing to a JSON or safetensors file with a refusal_direction vector. A bare name resolves to VLLM_ABLITERATION_DIR, default /opt/vllm/abliteration. For one direction this equals the weight edit W' = W - r(r^T W), so a base checkpoint reproduces its abliterated release with no extra weights. Unset, the path loads nothing and adds no work. Co-Authored-By: Hinata <hinata@idihore.id> Signed-off-by: MOVZX <movzx@yahoo.com>
150 lines
5.0 KiB
Python
150 lines
5.0 KiB
Python
# SPDX-License-Identifier: Apache-2.0
|
|
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
|
|
"""Optional refusal-direction removal ("abliteration"), applied at runtime.
|
|
|
|
``VLLM_ABLITERATION`` names a JSON file holding a ``refusal_direction`` list,
|
|
or a safetensors file holding a ``refusal_direction`` tensor, of length
|
|
``hidden_size``. A bare name such as ``orcarouter`` resolves to
|
|
``$VLLM_ABLITERATION_DIR/<name>.json``, defaulting to
|
|
``/opt/vllm/abliteration/<name>.json``. With it set, every residual-stream
|
|
write loses its component along the unit direction r:
|
|
|
|
x <- x - r (r . x)
|
|
|
|
It is applied to the attention, linear-attention and MLP block outputs, and to
|
|
the text token embeddings. For one direction that equals the weight edit
|
|
``W' = W - r (r^T W)`` on ``self_attn.o_proj``, ``linear_attn.out_proj``,
|
|
``mlp.down_proj`` and the rows of ``embed_tokens`` (Arditi et al., 2024), so a
|
|
base checkpoint behaves like its abliterated release with no extra weights.
|
|
The Flash-Next runtime overlay uses the same rule. Unset, nothing loads and no
|
|
work is added.
|
|
"""
|
|
|
|
import functools
|
|
import json
|
|
import math
|
|
import os
|
|
|
|
import torch
|
|
|
|
from vllm.distributed import (
|
|
get_tensor_model_parallel_rank,
|
|
get_tensor_model_parallel_world_size,
|
|
)
|
|
from vllm.logger import init_logger
|
|
|
|
logger = init_logger(__name__)
|
|
|
|
ENV = "VLLM_ABLITERATION"
|
|
BUILTIN_DIR = "/opt/vllm/abliteration"
|
|
|
|
|
|
def direction_path() -> str | None:
|
|
"""The direction file to load, None when the switch is off."""
|
|
from vllm.envs import VLLM_ABLITERATION, VLLM_ABLITERATION_DIR
|
|
|
|
value = (VLLM_ABLITERATION or "").strip()
|
|
if value in ("", "0"):
|
|
return None
|
|
if os.sep not in value and not value.endswith((".json", ".safetensors")):
|
|
root = (VLLM_ABLITERATION_DIR or "").strip() or BUILTIN_DIR
|
|
value = os.path.join(root, f"{value}.json")
|
|
return value
|
|
|
|
|
|
@functools.lru_cache(maxsize=8)
|
|
def _load_unit_direction(path: str, hidden_size: int) -> torch.Tensor:
|
|
if path.endswith(".safetensors"):
|
|
from safetensors import safe_open
|
|
|
|
with safe_open(path, framework="pt", device="cpu") as f:
|
|
r = f.get_tensor("refusal_direction")
|
|
else:
|
|
with open(path) as f:
|
|
r = torch.tensor(json.load(f)["refusal_direction"], dtype=torch.float32)
|
|
r = r.to(torch.float32).flatten()
|
|
if r.numel() != hidden_size:
|
|
raise ValueError(
|
|
f"{ENV}: {path} holds {r.numel()} values; "
|
|
f"the model's hidden size is {hidden_size}"
|
|
)
|
|
norm = float(r.norm())
|
|
if not math.isfinite(norm) or norm == 0.0:
|
|
raise ValueError(f"{ENV}: {path} holds a zero direction")
|
|
return r / norm
|
|
|
|
|
|
def load_direction(hidden_size: int) -> torch.Tensor | None:
|
|
"""The unit refusal direction as float32 on CPU, None when the switch is off."""
|
|
path = direction_path()
|
|
if path is None:
|
|
return None
|
|
r = _load_unit_direction(path, hidden_size)
|
|
logger.info_once(
|
|
"Abliteration: removing the refusal direction in %s (%d values).",
|
|
path,
|
|
hidden_size,
|
|
)
|
|
return r
|
|
|
|
|
|
def _slice_for(r: torch.Tensor, width: int) -> torch.Tensor:
|
|
"""r, or the slice of it that a width-wide tensor covers."""
|
|
if width == r.shape[-1]:
|
|
return r
|
|
tp = get_tensor_model_parallel_world_size()
|
|
if width * tp != r.shape[-1]:
|
|
raise ValueError(
|
|
f"abliteration: width {width} matches neither the hidden size "
|
|
f"{r.shape[-1]} nor its {tp}-way shard"
|
|
)
|
|
return r.narrow(0, get_tensor_model_parallel_rank() * width, width)
|
|
|
|
|
|
def _ready(r: torch.Tensor, x: torch.Tensor) -> torch.Tensor:
|
|
"""r, sliced and cast for x. The cast result is cached on the shared copy."""
|
|
width = x.shape[-1]
|
|
copies = r.__dict__.setdefault("_vllm_copies", {})
|
|
key = (x.device, x.dtype, width)
|
|
part = copies.get(key)
|
|
if part is None:
|
|
part = _slice_for(r, width).to(device=x.device, dtype=x.dtype)
|
|
copies[key] = part
|
|
return part
|
|
|
|
|
|
def project_(x: torch.Tensor, r: torch.Tensor | None) -> torch.Tensor:
|
|
"""In place: drop the component of x along r. No-op when r is None."""
|
|
if r is None:
|
|
return x
|
|
width = x.shape[-1]
|
|
part = _ready(r, x)
|
|
if x.is_contiguous():
|
|
flat = x.view(-1, width)
|
|
# rank-1 update, no full-size temporary
|
|
flat.addr_(flat @ part, part, alpha=-1.0)
|
|
else:
|
|
x.sub_(part * x.matmul(part).unsqueeze(-1))
|
|
return x
|
|
|
|
|
|
def projector(hidden_size: int):
|
|
"""Return ``project(x)``: in-place projection of x, a no-op when switched off.
|
|
|
|
Model code stores the callable on the module, so torch.compile treats it as
|
|
an opaque custom op, and no device-dependent tensor is built at construction.
|
|
"""
|
|
state: dict[str, object] = {}
|
|
|
|
def direction() -> torch.Tensor | None:
|
|
if "loaded" not in state:
|
|
state["loaded"] = True
|
|
state["r"] = load_direction(hidden_size)
|
|
return state["r"]
|
|
|
|
def project(x: torch.Tensor) -> torch.Tensor:
|
|
r = direction()
|
|
return x if r is None else project_(x, r)
|
|
|
|
return project
|