-
Notifications
You must be signed in to change notification settings - Fork 12
/
causal_tracing_comparison.py
329 lines (276 loc) · 14.5 KB
/
causal_tracing_comparison.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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import numpy as np
import json, jsonlines
import matplotlib.pyplot as plt
from eval_qa import eval_file, eval_items
import os
from transformers import GPT2Config, GPT2LMHeadModel, GPT2Tokenizer, GPTNeoXForCausalLM, GPTNeoXTokenizerFast, GPTNeoXConfig
from tqdm import tqdm
import torch
import torch.nn.functional as F
import pandas as pd
from copy import deepcopy
import random
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dataset", default=None, type=str, required=True, help="dataset name")
parser.add_argument("--model_dir", default=None, type=str, help="parent directory of saved model checkpoints")
parser.add_argument("--save_path", default=None, type=str, help="path to save result")
parser.add_argument("--num_layer", default=8, type=int, help="number of layer of the model")
parser.add_argument("--wd", default=0.1, type=float, help="weight decay being used")
args = parser.parse_args()
dataset, model_dir = args.dataset, args.model_dir
directory = os.path.join(model_dir, "{}_{}_{}".format(dataset, args.wd, args.num_layer))
device = torch.device('cuda:7')
all_atomic = set()
atomic_dict = dict()
with open("data/{}/train.json".format(dataset)) as f:
train_items = json.load(f)
for item in tqdm(train_items):
temp = item['target_text'].strip("><").split("><")
if len(temp) != 4:
continue
h,r,t = temp[:3]
atomic_dict[(h,r)] = t
all_atomic.add((h,r,t))
train_atomic = set()
for item in tqdm(train_items):
temp = item['target_text'].strip("><").split("><")
if len(temp) == 4:
continue
r, e1, e2 = temp[0], temp[2], temp[4]
val1 = atomic_dict[(e1, r)]
val2 = atomic_dict[(e2, r)]
train_atomic.add((e1, r, val1))
train_atomic.add((e2, r, val2))
test_atomic = all_atomic - train_atomic
print(len(train_atomic), len(test_atomic))
r2ht_train = dict()
for (h,r,t) in train_atomic:
if r not in r2ht_train:
r2ht_train[r] = []
r2ht_train[r].append((h,t))
def return_rank(hd, word_embedding_, token, metric='dot', token_list=None, position=None):
if metric == 'dot':
word_embedding = word_embedding_
elif metric == 'cos':
word_embedding = F.normalize(word_embedding_, p=2, dim=1)
else:
assert False
logits_ = torch.matmul(hd, word_embedding.T)
if position is None:
rank = []
for j in range(len(logits_)):
log = logits_[j].cpu().numpy()
if token_list is None:
temp = [[i, log[i]] for i in range(len(log))]
else:
temp = [[i, log[i]] for i in token_list]
temp.sort(key=lambda var: var[1], reverse=True)
rank.append([var[0] for var in temp].index(token))
return rank
j = position
log = logits_[j]
log = log.cpu().numpy()
if token_list is None:
temp = [[i, log[i]] for i in range(len(log))]
else:
temp = [[i, log[i]] for i in token_list]
temp.sort(key=lambda var: var[1], reverse=True)
return [var[0] for var in temp].index(token)
with open("data/{}/test.json".format(dataset)) as f:
pred_data = json.load(f)
d = dict()
for item in pred_data:
t = item['type']
if t not in d:
d[t] = []
d[t].append(item)
all_checkpoints = [checkpoint for checkpoint in os.listdir(directory) if checkpoint.startswith("checkpoint")]
all_checkpoints.sort(key=lambda var: int(var.split("-")[1]))
results = []
np.random.seed(0)
split = 'train_inferred'
rand_inds = np.random.choice(len(d[split]), 300, replace=False).tolist()
for checkpoint in tqdm(all_checkpoints):
print("now checkpoint", checkpoint)
model_path = os.path.join(directory, checkpoint)
model = GPT2LMHeadModel.from_pretrained(model_path).to(device)
word_embedding = model.lm_head.weight.data
tokenizer = GPT2Tokenizer.from_pretrained(model_path)
tokenizer.padding_side = "left"
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
model.config.pad_token_id = model.config.eos_token_id
full_list = []
for index in tqdm(rand_inds):
random.seed(index)
res_dict = dict()
temp = d[split][index]['target_text'].strip("><").split("><")
r, e1, e2, t = temp[0], temp[2], temp[4], temp[5]
val_1, val_2 = atomic_dict[(e1, r)], atomic_dict[(e2, r)]
query = "<{}><q><{}><mask><{}>".format(r, e1, e2)
decoder_temp = tokenizer([query], return_tensors="pt", padding=True)
decoder_input_ids, decoder_attention_mask = decoder_temp["input_ids"], decoder_temp["attention_mask"]
decoder_input_ids, decoder_attention_mask = decoder_input_ids.to(device), decoder_attention_mask.to(device)
with torch.no_grad():
outputs = model(
input_ids=decoder_input_ids,
attention_mask=decoder_attention_mask,
output_hidden_states=True
)
all_hidden_states = outputs['hidden_states']
rank_before = return_rank(all_hidden_states[8][0, :, :], word_embedding, tokenizer("<"+t+">")['input_ids'][0], position=-1)
res_dict['rank_before'] = rank_before
# MRRs
for layer_to_intervene in range(1, 8):
hidden_states_orig = all_hidden_states[layer_to_intervene]
with torch.no_grad():
temp = model.transformer.ln_f(hidden_states_orig)
val1_rank_pos2 = return_rank(temp[0, :, :], word_embedding, tokenizer("<"+val_1+">")['input_ids'][0], position=2)
val2_rank_pos4 = return_rank(temp[0, :, :], word_embedding, tokenizer("<"+val_2+">")['input_ids'][0], position=4)
label0_rank = return_rank(temp[0, :, :], word_embedding, tokenizer("<{}_0>".format(r))['input_ids'][0], position=0)
label1_rank = return_rank(temp[0, :, :], word_embedding, tokenizer("<{}_1>".format(r))['input_ids'][0], position=0)
label2_rank = return_rank(temp[0, :, :], word_embedding, tokenizer("<{}_2>".format(r))['input_ids'][0], position=0)
res_dict['val1_rank_pos2_'+str(layer_to_intervene)] = val1_rank_pos2
res_dict['val2_rank_pos4_'+str(layer_to_intervene)] = val2_rank_pos4
res_dict['label0_rank_pos0_'+str(layer_to_intervene)] = label0_rank
res_dict['label1_rank_pos0_'+str(layer_to_intervene)] = label1_rank
res_dict['label2_rank_pos0_'+str(layer_to_intervene)] = label2_rank
# perturb the 1st entity
val_1_int, val_2_int = int(val_1), int(val_2)
if val_1_int == val_2_int:
closest = {val_2_int-1, val_2_int+1}
else:
closest = {val_2_int}
all_ = set()
for (entity, value) in r2ht_train[r]:
if entity != e1 and int(value) in closest:
all_.add(entity)
query = "<{}><q><{}><mask><{}>".format(r, random.choice(list(all_)), e2)
decoder_temp = tokenizer([query], return_tensors="pt", padding=True)
decoder_input_ids_, decoder_attention_mask = decoder_temp["input_ids"], decoder_temp["attention_mask"]
decoder_input_ids_, decoder_attention_mask = decoder_input_ids_.to(device), decoder_attention_mask.to(device)
with torch.no_grad():
outputs_ctft = model(
input_ids=decoder_input_ids_,
attention_mask=decoder_attention_mask,
output_hidden_states=True
)
all_hidden_states_ctft = outputs_ctft['hidden_states']
for layer_to_intervene in range(1, 8):
hidden_states = all_hidden_states[layer_to_intervene].clone()
hidden_states_ctft = all_hidden_states_ctft[layer_to_intervene]
# intervene
hidden_states[0, 2, :] = hidden_states_ctft[0, 2, :]
hidden_states[0, 3, :] = hidden_states_ctft[0, 3, :]
with torch.no_grad():
for i in range(layer_to_intervene, 8):
f_layer = model.transformer.h[i]
# attn
residual = hidden_states
hidden_states = f_layer.ln_1(hidden_states)
attn_output = f_layer.attn(hidden_states)[0]
hidden_states = attn_output + residual
# mlp
residual = hidden_states
hidden_states = f_layer.ln_2(hidden_states)
feed_forward_hidden_states = f_layer.mlp.c_proj(f_layer.mlp.act(f_layer.mlp.c_fc(hidden_states)))
hidden_states = residual + feed_forward_hidden_states
# final ln
hidden_states = model.transformer.ln_f(hidden_states)
# print("--------")
rank_after = return_rank(hidden_states[0, :, :], word_embedding, tokenizer("<"+t+">")['input_ids'][0], position=-1)
res_dict['e1_'+str(layer_to_intervene)] = rank_after
# perturb the 2nd entity
val_1_int, val_2_int = int(val_1), int(val_2)
if val_1_int == val_2_int:
closest = {val_1_int-1, val_1_int+1}
else:
closest = {val_1_int}
all_ = set()
ht_list = r2ht_train[r]
for (entity, value) in ht_list:
if entity != e2 and int(value) in closest:
all_.add(entity)
query = "<{}><q><{}><mask><{}>".format(r, e1, random.choice(list(all_)))
decoder_temp = tokenizer([query], return_tensors="pt", padding=True)
decoder_input_ids_, decoder_attention_mask = decoder_temp["input_ids"], decoder_temp["attention_mask"]
decoder_input_ids_, decoder_attention_mask = decoder_input_ids_.to(device), decoder_attention_mask.to(device)
with torch.no_grad():
outputs_ctft = model(
input_ids=decoder_input_ids_,
attention_mask=decoder_attention_mask,
output_hidden_states=True
)
all_hidden_states_ctft = outputs_ctft['hidden_states']
for layer_to_intervene in range(1, 8):
hidden_states = all_hidden_states[layer_to_intervene].clone()
hidden_states_ctft = all_hidden_states_ctft[layer_to_intervene]
# intervene
hidden_states[0, 4, :] = hidden_states_ctft[0, 4, :]
with torch.no_grad():
for i in range(layer_to_intervene, 8):
f_layer = model.transformer.h[i]
# attn
residual = hidden_states
hidden_states = f_layer.ln_1(hidden_states)
attn_output = f_layer.attn(hidden_states)[0]
hidden_states = attn_output + residual
# mlp
residual = hidden_states
hidden_states = f_layer.ln_2(hidden_states)
feed_forward_hidden_states = f_layer.mlp.c_proj(f_layer.mlp.act(f_layer.mlp.c_fc(hidden_states)))
hidden_states = residual + feed_forward_hidden_states
# final ln
hidden_states = model.transformer.ln_f(hidden_states)
# print("--------")
rank_after = return_rank(hidden_states[0, :, :], word_embedding, tokenizer("<"+t+">")['input_ids'][0], position=-1)
res_dict['e2_'+str(layer_to_intervene)] = rank_after
# intervene on the attr
all_ = set()
for attr in r2ht_train.keys():
if attr != r:
all_.add(attr)
query = "<{}><q><{}><mask><{}>".format(random.choice(list(all_)), e1, e2)
decoder_temp = tokenizer([query], return_tensors="pt", padding=True)
decoder_input_ids_, decoder_attention_mask = decoder_temp["input_ids"], decoder_temp["attention_mask"]
decoder_input_ids_, decoder_attention_mask = decoder_input_ids_.to(device), decoder_attention_mask.to(device)
with torch.no_grad():
outputs_ctft = model(
input_ids=decoder_input_ids_,
attention_mask=decoder_attention_mask,
output_hidden_states=True
)
all_hidden_states_ctft = outputs_ctft['hidden_states']
for layer_to_intervene in range(1, 8):
hidden_states = all_hidden_states[layer_to_intervene].clone()
hidden_states_ctft = all_hidden_states_ctft[layer_to_intervene]
# intervene
hidden_states[0, 0, :] = hidden_states_ctft[0, 0, :]
hidden_states[0, 1, :] = hidden_states_ctft[0, 1, :]
with torch.no_grad():
for i in range(layer_to_intervene, 8):
f_layer = model.transformer.h[i]
# attn
residual = hidden_states
hidden_states = f_layer.ln_1(hidden_states)
attn_output = f_layer.attn(hidden_states)[0]
hidden_states = attn_output + residual
# mlp
residual = hidden_states
hidden_states = f_layer.ln_2(hidden_states)
feed_forward_hidden_states = f_layer.mlp.c_proj(f_layer.mlp.act(f_layer.mlp.c_fc(hidden_states)))
hidden_states = residual + feed_forward_hidden_states
# final ln
hidden_states = model.transformer.ln_f(hidden_states)
# print("--------")
rank_after = return_rank(hidden_states[0, :, :], word_embedding, tokenizer("<"+t+">")['input_ids'][0], position=-1)
res_dict['a_'+str(layer_to_intervene)] = rank_after
# print(res_dict)
full_list.append(res_dict)
results.append(full_list)
with open(args.save_path, "w", encoding='utf-8') as f:
json.dump(results, f)
if __name__ == '__main__':
main()