-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsaeval-sparse-control.py
160 lines (127 loc) · 5.82 KB
/
saeval-sparse-control.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import torch
import pandas as pd
from sae_lens import HookedSAETransformer
from tqdm import tqdm
import json
from circuit import IOICircuit
from tasks.ioi.dictionary import supervised_dictionary
device = "cuda"
def logits_diff(logits, correct_answer, incorrect_answer=None):
correct_index = model.to_single_token(correct_answer)
if incorrect_answer is None:
return logits.cpu().numpy()[0, -1, correct_index]
else:
incorrect_index = model.to_single_token(incorrect_answer)
return logits.cpu().numpy()[0, -1, correct_index] - logits.cpu().numpy()[0, -1, incorrect_index]
def logits_score(clean_logits, patched_logits, corr_logits, correct_answer, incorrect_answer=None):
clean_score = logits_diff(clean_logits, correct_answer, incorrect_answer)
patched_score = logits_diff(patched_logits, correct_answer, incorrect_answer)
corr_score = logits_diff(corr_logits, correct_answer, incorrect_answer)
score = (patched_score - clean_score) / (corr_score - clean_score)
return score
# Load task
with open('tasks/ioi/task.json') as f:
task = json.load(f)
# Load model and SAEs
model: HookedSAETransformer = HookedSAETransformer.from_pretrained("gpt2").to(device)
model.eval()
ioi_circuit = IOICircuit(model, task)
ioi_circuit.load_saes('z')
ioi_circuit.load_saes('resid_pre')
# Compute supervised dictionary
bs = 64
prompts = [p['prompt'] for p in task['prompts']]
activations = {i: [] for i in ['q', 'k', 'v', 'z']}
for b in tqdm(range(0, len(prompts), bs)):
tokens = model.to_tokens(prompts[b:b+bs])
with torch.no_grad():
_, cache = model.run_with_cache(tokens)
for key in activations.keys():
activations[key].append(cache.stack_activation(key))
activations = {key: torch.cat(values, 1) for key, values in activations.items()}
task_df = ioi_circuit.create_task_df()
io_vec, s_vec, pos_vec = supervised_dictionary(task_df, activations)
all_nodes_labels = ['bNMH-z', 'bNMH-q', 'bNMH-qk', 'IH+DTH-q', 'SIH-q', 'SIH-v', 'bNMH-z', 'bNMH-q', 'bNMH-qk', 'IH+DTH-q', 'SIH-q', 'SIH-v']
all_nodes = [['bNMH.z'], ['bNMH.q'], ['bNMH.qk'], ['IH.q', 'DTH.q'], ['SIH.q'], ['SIH.v'], ['bNMH.z'], ['bNMH.q'], ['bNMH.qk'], ['IH.q', 'DTH.q'], ['SIH.q'], ['SIH.v']]
attributes = ['IO', 'S', 'S', 'S', 'S', 'S', 'Pos', 'Pos', 'Pos', 'Pos', 'Pos']
for node_names, node_label, attribute in zip(all_nodes, all_nodes_labels, attributes):
scores_df = {
'clean_ld': [],
'corr_ld': [],
'patch_corr_ld': [],
'patch_corr_score': [],
'patch_supervised_ld': [],
'patch_supervised_score': [],
'patch_all_sae_ld': [],
'patch_all_sae_score': [],
'patch_sae_fs_ld': [],
'patch_sae_fs_score': []
}
for idx in tqdm(range(512)):
example = task['prompts'][idx]
io = example['variables']['IO']
s = example['variables']['S2']
pos = example['variables']['Pos']
neg_pos = 'ABB' if pos == 'BAB' else 'BAB'
pos_id = 0 if pos == 'ABB' else 1
### CORRUPTED
new_attr, clean_logits, patched_logits, corr_logits = ioi_circuit.run_with_patch(
example,
node_names=node_names,
attribute=attribute,
method='corr',
verbose=False
)
scores_df['clean_ld'].append(logits_diff(clean_logits, ' '+io, ' '+new_attr).item())
scores_df['corr_ld'].append(logits_diff(corr_logits, ' '+io, ' '+new_attr).item())
scores_df['patch_corr_ld'].append(logits_diff(patched_logits, ' '+io, ' '+new_attr).item())
scores_df['patch_corr_score'].append(logits_score(clean_logits, patched_logits, corr_logits, ' '+io, ' '+new_attr))
### SUPERVISED DICTIONARY
patches = []
for node in node_names:
node, component = node.split('.')
if attribute == 'IO':
in_patch = io_vec[pos][new_attr]
out_patch = s_vec[pos][io]
elif attribute == 'S':
in_patch = io_vec[pos][new_attr]
out_patch = s_vec[pos][s]
else:
in_patch = pos_vec[neg_pos]
out_patch = pos_vec[pos]
patches.append((in_patch, out_patch))
_, clean_logits, patched_logits, _ = ioi_circuit.run_with_patch(
example,
node_names=node_names,
attribute=attribute,
method='feature',
patches=patches,
verbose=False
)
scores_df['patch_supervised_ld'].append(logits_diff(patched_logits, ' '+io, ' '+new_attr).item())
scores_df['patch_supervised_score'].append(logits_score(clean_logits, patched_logits, corr_logits, ' '+io, ' '+new_attr))
### ALL SAE FEATURES
_, clean_logits, patched_logits, corr_logits = ioi_circuit.run_with_patch(
example,
node_names=node_names,
attribute=attribute,
method='sae-all',
verbose=False,
new_attr=new_attr
)
scores_df['patch_all_sae_ld'].append(logits_diff(patched_logits, ' '+io, ' '+new_attr).item())
scores_df['patch_all_sae_score'].append(logits_score(clean_logits, patched_logits, corr_logits, ' '+io, ' '+new_attr))
### SAE FEATURE SEARCH
N = 10
_, clean_logits, patched_logits, corr_logits = ioi_circuit.run_with_patch(
example,
node_names=node_names,
attribute=attribute,
method='sae-fs',
verbose=False,
new_attr=new_attr
)
scores_df['patch_sae_fs_ld'].append(logits_diff(patched_logits, ' '+io, ' '+new_attr).item())
scores_df['patch_sae_fs_score'].append(logits_score(clean_logits, patched_logits, corr_logits, ' '+io, ' '+new_attr))
scores_df = pd.DataFrame(scores_df)
scores_df.to_json(f'tasks/ioi/sc-scores/{attribute}_{node_label}.json')