worthant commited on
Commit
814d662
·
1 Parent(s): 46dd82d

:hammer: feat(tools): Add abliteration script

Browse files
Files changed (1) hide show
  1. tools/abliterate.py +203 -0
tools/abliterate.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Abliteration tool for Hugging Face transformers models.
4
+ Collects activations on refusal and compliant examples, computes the
5
+ refusal direction, and modifies the model's forward pass to suppress
6
+ refusal behaviour.
7
+
8
+ Usage:
9
+ python3 abliterate.py --model MODEL_PATH --refusal FILE --compliant FILE --output OUT_DIR
10
+ """
11
+ import os
12
+ import argparse
13
+ import torch
14
+ from transformers import AutoModelForCausalLM, AutoTokenizer
15
+ from torch.utils.data import DataLoader, Dataset
16
+ from tqdm import tqdm
17
+ import json
18
+ import numpy as np
19
+
20
+ class TextDataset(Dataset):
21
+ def __init__(self, texts, tokenizer, max_length=512):
22
+ self.texts = texts
23
+ self.tokenizer = tokenizer
24
+ self.max_length = max_length
25
+
26
+ def __len__(self):
27
+ return len(self.texts)
28
+
29
+ def __getitem__(self, idx):
30
+ enc = self.tokenizer(
31
+ self.texts[idx],
32
+ truncation=True,
33
+ max_length=self.max_length,
34
+ return_tensors="pt"
35
+ )
36
+ return enc.input_ids.squeeze(0), enc.attention_mask.squeeze(0)
37
+
38
+ def collect_activations(model, dataloader, device, layers=None):
39
+ """
40
+ Collect hidden states from specified layers (or all decoder layers) for each sample.
41
+ Returns a list of dicts: {layer_index: tensor_of_hidden_states}
42
+ """
43
+ activations = []
44
+ hooks = []
45
+ layer_outputs = {}
46
+
47
+ def hook_fn(layer_idx):
48
+ def fn(module, input, output):
49
+ # output is a tuple; first element is hidden states
50
+ layer_outputs[layer_idx] = output[0].detach().cpu()
51
+ return fn
52
+
53
+ # Register hooks for all decoder layers by default
54
+ if layers is None:
55
+ # Assume model.model.layers exists for most transformers
56
+ for i, layer in enumerate(model.model.layers):
57
+ hook = layer.register_forward_hook(hook_fn(i))
58
+ hooks.append(hook)
59
+ else:
60
+ for i in layers:
61
+ hook = model.model.layers[i].register_forward_hook(hook_fn(i))
62
+ hooks.append(hook)
63
+
64
+ model.eval()
65
+ with torch.no_grad():
66
+ for input_ids, attn_mask in tqdm(dataloader, desc="Collecting activations"):
67
+ input_ids = input_ids.to(device)
68
+ attn_mask = attn_mask.to(device)
69
+ _ = model(input_ids, attention_mask=attn_mask)
70
+ # copy the layer outputs
71
+ batch_acts = {idx: layer_outputs.pop(idx) for idx in list(layer_outputs.keys())}
72
+ activations.append(batch_acts)
73
+
74
+ for hook in hooks:
75
+ hook.remove()
76
+
77
+ return activations
78
+
79
+ def compute_refusal_direction(refusal_acts, compliant_acts):
80
+ """
81
+ Compute the mean difference vector (refusal direction) per layer.
82
+ Both inputs are lists of dicts {layer: tensor (batch, seq, hidden)}.
83
+ We pool over the sequence dimension (mean) and then over batch.
84
+ """
85
+ layer_dirs = {}
86
+ # assume all dicts have the same layers
87
+ all_layers = set(refusal_acts[0].keys())
88
+
89
+ for layer in all_layers:
90
+ # Stack and pool over sequence (mean) for each sample
91
+ ref_stack = torch.cat(
92
+ [act[layer].mean(dim=1, keepdim=False) for act in refusal_acts], dim=0
93
+ ) # (total_samples, hidden)
94
+ comp_stack = torch.cat(
95
+ [act[layer].mean(dim=1, keepdim=False) for act in compliant_acts], dim=0
96
+ )
97
+ ref_mean = ref_stack.mean(dim=0, keepdim=True) # (1, hidden)
98
+ comp_mean = comp_stack.mean(dim=0, keepdim=True)
99
+ direction = ref_mean - comp_mean
100
+ # Normalize to unit vector
101
+ direction = direction / direction.norm()
102
+ layer_dirs[layer] = direction
103
+
104
+ return layer_dirs
105
+
106
+ def apply_abliteration(model, layer_dirs, alpha=1.0):
107
+ """
108
+ Modify the model's forward pass by subtracting the refusal direction
109
+ from the hidden states after each layer.
110
+ This is done via a permanent forward hook that subtracts the direction
111
+ from the layer's output (residual stream).
112
+ """
113
+ for layer_idx, direction in layer_dirs.items():
114
+ layer = model.model.layers[layer_idx]
115
+ # Store direction in model's attribute for reference
116
+ if not hasattr(model, '_abliteration_dirs'):
117
+ model._abliteration_dirs = {}
118
+ model._abliteration_dirs[layer_idx] = direction.to(model.device) * alpha
119
+
120
+ def make_hook(idx, dir_vec):
121
+ def hook(module, input, output):
122
+ # output is a tuple (hidden_states, ...) for most layers
123
+ if isinstance(output, tuple):
124
+ hidden = output[0]
125
+ batch_size, seq_len, hidden_dim = hidden.shape
126
+ # Expand direction to (1,1,hidden_dim) and subtract
127
+ shifted = hidden - dir_vec.unsqueeze(0).unsqueeze(0)
128
+ return (shifted,) + output[1:]
129
+ else:
130
+ hidden = output
131
+ shifted = hidden - dir_vec.unsqueeze(0).unsqueeze(0)
132
+ return shifted
133
+ return hook
134
+
135
+ layer.register_forward_hook(make_hook(layer_idx, direction.to(model.device)))
136
+
137
+ return model
138
+
139
+ def main():
140
+ parser = argparse.ArgumentParser()
141
+ parser.add_argument('--model', required=True, help='HF model path or name')
142
+ parser.add_argument('--refusal', required=True, help='Text file with refusal examples (one per line)')
143
+ parser.add_argument('--compliant', required=True, help='Text file with compliant examples (one per line)')
144
+ parser.add_argument('--output', required=True, help='Output directory for modified model')
145
+ parser.add_argument('--alpha', type=float, default=1.0, help='Scaling factor for direction')
146
+ parser.add_argument('--batch_size', type=int, default=4, help='Batch size for activation collection')
147
+ parser.add_argument('--max_length', type=int, default=512, help='Max sequence length')
148
+ parser.add_argument('--device', default='cuda', help='Device to use')
149
+ args = parser.parse_args()
150
+
151
+ device = torch.device(args.device if torch.cuda.is_available() else 'cpu')
152
+ print(f"Loading model from {args.model}")
153
+ tokenizer = AutoTokenizer.from_pretrained(args.model, trust_remote_code=True)
154
+ model = AutoModelForCausalLM.from_pretrained(
155
+ args.model,
156
+ torch_dtype=torch.bfloat16,
157
+ device_map="auto",
158
+ trust_remote_code=True
159
+ )
160
+ model = model.to(device)
161
+
162
+ # Load texts
163
+ with open(args.refusal, 'r', encoding='utf-8') as f:
164
+ refusal_texts = [line.strip() for line in f if line.strip()]
165
+ with open(args.compliant, 'r', encoding='utf-8') as f:
166
+ compliant_texts = [line.strip() for line in f if line.strip()]
167
+
168
+ print(f"Refusal examples: {len(refusal_texts)}, Compliant: {len(compliant_texts)}")
169
+
170
+ # Prepare dataloaders
171
+ ref_dataset = TextDataset(refusal_texts, tokenizer, args.max_length)
172
+ comp_dataset = TextDataset(compliant_texts, tokenizer, args.max_length)
173
+ ref_dataloader = DataLoader(ref_dataset, batch_size=args.batch_size, shuffle=False)
174
+ comp_dataloader = DataLoader(comp_dataset, batch_size=args.batch_size, shuffle=False)
175
+
176
+ # Collect activations
177
+ print("Collecting activations for refusal examples...")
178
+ refusal_acts = collect_activations(model, ref_dataloader, device)
179
+ print("Collecting activations for compliant examples...")
180
+ compliant_acts = collect_activations(model, comp_dataloader, device)
181
+
182
+ # Compute direction
183
+ print("Computing refusal direction per layer...")
184
+ layer_dirs = compute_refusal_direction(refusal_acts, compliant_acts)
185
+
186
+ # Apply abliteration
187
+ print("Applying abliteration...")
188
+ model = apply_abliteration(model, layer_dirs, alpha=args.alpha)
189
+
190
+ # Save the modified model
191
+ print(f"Saving modified model to {args.output}")
192
+ model.save_pretrained(args.output)
193
+ tokenizer.save_pretrained(args.output)
194
+
195
+ # Also save the directions for reference
196
+ dirs_to_save = {str(k): v.cpu().tolist() for k, v in layer_dirs.items()}
197
+ with open(os.path.join(args.output, 'refusal_directions.json'), 'w') as f:
198
+ json.dump(dirs_to_save, f)
199
+
200
+ print("Done.")
201
+
202
+ if __name__ == '__main__':
203
+ main()