Skip to content

Search wahloon.net

Search models, news, guides and FAQs.

All guides
Guides#abliteration#guide#pytorch#methodology#advanced

How to abliterate a model yourself

A working sketch of the abliteration loop: build a prompt set, collect activations, estimate a refusal direction, edit the writers, and evaluate before you quantize.

8 min readMarkdown
On this page

Abliteration sounds like a trick until you see the whole loop. It is four operations: collect activations, estimate a direction, project it out of a few weight matrices, and measure what changed. You can reproduce it on a small model in an afternoon.

The hard part is not the projection. It is building a prompt set that measures what you think it measures, and evaluating the result honestly. This guide walks the loop in the order you should actually run it, with a minimal PyTorch sketch. It is a sketch, not a library: the APIs around it move, and a real run needs more care than 40 lines.

What you are building

You are not retraining the model. You are editing a small number of weight matrices so that the component of their output along a chosen direction is reduced:

W' = W − s · r̂ r̂ᵀ W

r̂ is a unit vector in the residual stream — the direction associated with refusal. s is a strength. W is a writer whose output is added back to the residual stream, usually o_proj in attention and down_proj in the MLP. Projecting the direction out of those outputs means the model still has the same weights and the same architecture; it just produces less of that direction.

The abliteration explainer covers why this works and how it differs from a fine-tune. This guide is the mechanical version.

What you need

  • A base model you can load in Transformers, ideally in BF16 on one GPU.
  • A prompt set with refused and complied examples, plus a held-out set.
  • Enough memory to run the unquantized model for activation collection. If the model does not fit, collect on a smaller proxy or a subset of layers, and expect the direction to transfer less cleanly.
  • A way to score refusals. Manual grading of 100 prompts is fine; a classifier is faster but needs its own validation.

Do not start from a quantized GGUF. The direction is estimated in the unquantized activation space, and the edit is applied to the unquantized weights. Quantize after you have evaluated the edit.

Step 1: pick the base and the target behavior

Pick a base model with a chat template you understand. The template matters: a direction estimated on raw completions may not match the model's behavior when the template is applied.

Decide what "refusal" means for your target. A hard refusal ("I can't help with that"), a hedge that still answers, and a partial answer are different outcomes. Write the rubric down before you look at outputs, or you will grade toward the result you expect.

If the model has separate chat and reasoning modes, measure them separately. The Hy4-flash build found two directions with cosine similarity as low as 0.2 between chat and think prompts. Averaging them would have produced a direction that fit neither.

Step 2: build the prompt set

You want three groups:

  1. Harmful or normally refused prompts. 100–200, spread across categories rather than clustered on one.
  2. Benign prompts that are structurally similar. Same length and style, no refusal expected. These are your controls.
  3. Held-out prompts. Do not use these to estimate the direction or tune the strength. They are how you find out whether you overfit.

Run the base model on the first two groups and label each response as refused or complied. Keep the raw outputs. You will want them again when you evaluate the edit.

A useful prompt set is boring: it covers the behaviors you care about, it is large enough that one odd prompt does not move the mean, and it is fixed before you start tuning.

Step 3: collect activations

Hook the residual stream at each layer you might edit, and take the last token of the prompt before generation. That is the state the model uses to decide what to say next.

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
 
model_id = "Qwen/Qwen3.5-9B"
tok = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(
    model_id, torch_dtype=torch.bfloat16, device_map="auto"
)
model.eval()
 
def collect(prompts, layers):
    acts = {layer: [] for layer in layers}
    handles = []
    for layer in layers:
        def hook(_module, _inputs, output, layer=layer):
            hidden = output[0] if isinstance(output, tuple) else output
            acts[layer].append(hidden[:, -1, :].detach().float().cpu())
        handles.append(model.model.layers[layer].register_forward_hook(hook))
    for prompt in prompts:
        ids = tok.apply_chat_template(
            [{"role": "user", "content": prompt}],
            return_tensors="pt",
            add_generation_prompt=True,
        ).to(model.device)
        with torch.no_grad():
            model(ids)
    for handle in handles:
        handle.remove()
    return {layer: torch.cat(chunks) for layer, chunks in acts.items()}

Collect on the same prompts you labeled, and keep the refused and complied sets separate. A subset of layers is usually enough: refusal behavior tends to separate in the middle-to-late layers, and scanning every layer is expensive on a large model.

Step 4: estimate the direction

The simplest estimator is the difference in means between refused and complied activations:

def direction(refused, complied):
    r = refused.mean(dim=0) - complied.mean(dim=0)
    return r / r.norm()

This is the "difference-in-means" direction. It is cheap, it is easy to explain, and it works well enough to start. Alternatives:

  • PCA on the refused set. The first principal component often captures the refusal direction and is less sensitive to a few outliers.
  • Top singular vector of the difference matrix. This is what several published builds use when they want a rank-1 direction from paired data.
  • A subspace rather than one vector. If refusal behavior is spread across several directions, a rank-2 or rank-3 basis can remove more without pushing a single direction too hard.

Normalize the result. The strength parameter only means something if the direction is unit length.

Step 5: choose layers and strength

Do not guess. Scan.

For each candidate layer or layer range, apply the edit at a few strengths and measure:

  • Refusal rate on the held-out prompts.
  • KL divergence on benign prompts, if you can compute it. First-token KL is a common cheap proxy.
  • A small capability check: a handful of tasks where you know the base model's score.

Plot refusal rate against drift. There is usually a knee: refusals fall quickly, then drift rises faster than refusals fall. Pick a point before the knee, not at the lowest refusal number you can reach.

Typical strengths are in the 0.5–2.0 range, but the right value depends on the layer, the norm, and how the direction was estimated. A strength that works on one model can be destructive on another.

Step 6: apply the edit

The direction lives in the residual stream, which is the output space of o_proj and down_proj. To remove it, subtract the component of each output row along r̂:

@torch.no_grad()
def abliterate(model, r, layers, strength=1.0):
    r = r / r.norm()
    for layer in layers:
        block = model.model.layers[layer]
        for module in (block.self_attn.o_proj, block.mlp.down_proj):
            W = module.weight
            rr = r.to(device=W.device, dtype=W.dtype)
            # W: [out, in]; remove r from the output space
            W -= strength * torch.outer(rr, W.T @ rr)

A few details that matter:

  • Which writers. o_proj and down_proj are the standard pair because both write directly to the residual stream. Some builds also touch q_proj, k_proj or v_proj; that is a different edit with different risks.
  • Learned-gain norms. If the block applies an RMSNorm with a learned gain after the writer, the direction that reaches the residual is g ⊙ r, not r. Build the basis from the gain-corrected vector, or the edit will remove the wrong thing.
  • Rank. The code above is rank-1. For a subspace, replace r with a matrix P whose columns are orthonormal and use W -= strength * P @ (P.T @ W).
  • Rounding. Keeping the edit in BF16 and re-saving can snap part of it back. Check the edit after saving, not just after applying it in memory.

Step 7: evaluate before you quantize

Run the held-out prompts through the edited model. Compare against the base model on the same prompts, with the same decoding settings.

At minimum, measure:

  • Refusal rate, with your rubric.
  • Capability on a few tasks you care about.
  • Repetition and truncation.
  • Output length. Aggressive edits often make models talk longer.

Then quantize and re-run a smaller version of the same evaluation. Quantization can change refusal behavior, and a build that looked clean in BF16 can regress at Q4. The evaluation guide has a fuller harness.

Pitfalls

  • Evaluating on the prompts you trained on. The direction will look better than it is. Hold out a set.
  • One direction for chat and think. If the modes behave differently, measure them separately.
  • Skipping the chat template. A direction estimated without the template may not match deployment.
  • Over-editing. Lower refusal is not free. Watch capability and coherence, not just the refusal count.
  • Quantizing first. Estimate and apply in BF16, then quantize.
  • Publishing without the recipe. A refusal number with no method, layer list or evaluation set is not reproducible.

Tools

Heretic automates the search over layers and strengths, and is the fastest way to get a reasonable edit without writing the loop yourself. The original abliterator scripts are a good reference for the activation and projection steps. Read the repository you use rather than copying commands from a post: the interfaces change, and a stale flag is a silent failure.

If you publish a build, include the base model and revision, the method, the layers and strengths, the prompt set or its source, and the evaluation numbers. That is what makes an abliterated model useful to anyone else.

Responsibility

Abliteration changes model behavior; it does not change the law or the license. You are responsible for how you use the model and for what you generate or distribute with it. Check the base model license before commercial use, and keep application-level guardrails where they belong: in your product, not only in the weights.

5 minGuide

How we benchmark abliterated models

Four axes, one runtime, published prompts, and a 24 GB laptop. The full method behind the benchmark table, including what it cannot tell you.

#benchmark#evaluation#methodology
Read
6 minGuide

How to evaluate an abliterated model before you trust it

A model card's refusal number is a claim about a prompt set, not a property of the model. Here is a small harness you can run in an hour: refusal rate, capability, coherence and drift.

#evaluation#abliteration#methodology
Read