-
Notifications
You must be signed in to change notification settings - Fork 0
/
run_rumour_neuron_exp_lite.py
297 lines (227 loc) · 8.35 KB
/
run_rumour_neuron_exp_lite.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
"""Run all the extraction for a model across many templates.
"""
import argparse
import os
from datetime import datetime
import torch
from transformers import (
GPT2Tokenizer, TransfoXLTokenizer, XLNetTokenizer,
BertTokenizer, DistilBertTokenizer, RobertaTokenizer
)
import pandas as pd
from rumourexplitee import Model
from rumourObj import Tweet, TweetLite, Intervention, RumourIntervention,RumourInterventionBASE,RumourTokenIntervention,RumourComboIntervention
from utils import convert_results_to_pd
parser = argparse.ArgumentParser(description="Run a set of neuron experiments.")
parser.add_argument(
"-model",
type=str,
default="bert",
help="""Model type [bert, roberta, etc.].""",
)
parser.add_argument(
"-out_dir", default=".", type=str, help="""Path of the result folder."""
)
parser.add_argument(
"--randomize", default=False, action="store_true", help="Randomize model weights."
)
parser.add_argument(
"-pretrained_model",
type=str,
default="res/roberta_causal/",)
parser.add_argument(
"-pretrained_tok",
type=str,
default="res/roberta_tok/")
parser.add_argument(
"-load_pretrained_model",
default=True,
help="whether to load pretrained model")
parser.add_argument(
"-load_pretrained_tok",
default=False,
help="whether to load pretrained tokenizer")
parser.add_argument(
"-debug_mode",
default=False)
parser.add_argument(
"-input_data_dir",
type=str,
default="../pheme.pkl",
)
parser.add_argument(
"-rumour_veracity",
default=False
)
parser.add_argument(
'-base_model',
default=False)
parser.add_argument(
'-tok_mode',
default=False)
parser.add_argument(
'-combo_mode', default=False)
parser.add_argument(
'-combo_test_mode', default=False)
opt = parser.parse_args()
def get_intervention_types():
return ["direct","indirect"]
def construct_interventions(tweet_obj_lst, tokenizer, DEVICE):
interventions = {}
label_lst = ['rumour','nonrumour']
print('len og lst', len(tweet_obj_lst))
print('starting to construct interventions')
for t in tweet_obj_lst:
total_reply = len(t.reply_text_lst)
for alt_loc in range(0,total_reply):
internvention_id = t.source_id + '_' +str(alt_loc)
try:
interventions[internvention_id] = RumourIntervention(tokenizer, t.source_text, t.reply_text_lst, alt_loc,t.is_rumour, device=DEVICE)
except:
pass
print('########FINISH INTERVENTION CONSTRUCTION WITH NUMBER OF INTERVENTIONS ',len(interventions))
return interventions
def construct_debug_interventions(tweet_obj_lst, tokenizer, DEVICE):
interventions = {}
label_lst = ['rumour','nonrumour']
for t in tweet_obj_lst:
internvention_id = t.source_id + '_' +str(alt_loc)
try:
interventions[internvention_id] = RumourIntervention(tokenizer, t.source_text, t.reply_text_lst, alt_loc,t.is_rumour, device=DEVICE)
except:
pass
return interventions
def construct_token_interventions(tweet_obj_lst, tokenizer, DEVICE):
interventions = {}
print('starting to construct token level interventions')
for t in tweet_obj_lst:
total_reply = len(t.reply_text_lst)
for alt_loc in range(0, total_reply):
total_token_len = len(t.reply_text_lst[alt_loc].split())
print('total_token_len ',total_token_len)
for token_alt_loc in range(0, total_token_len):
internvention_id = t.source_id + '_' + str(alt_loc) + '_tok_'+str(token_alt_loc)
try:
interventions[internvention_id] = RumourTokenIntervention(tokenizer, t.source_text, t.reply_text_lst, alt_loc, token_alt_loc, device=DEVICE)
except Exception as e:
print(e)
pass
print('########FINISH TOKEN LEVEL INTERVENTION CONSTRUCTION WITH NUMBER OF INTERVENTIONS ',len(interventions))
return interventions
def construct_base_interventions(tweet_obj_lst, tokenizer, DEVICE):
interventions = {}
label_lst = ['rumour','nonrumour']
for t in tweet_obj_lst:
for alt_loc in range(0,total_reply):
internvention_id = t.source_id + '_' +str(alt_loc)
try:
interventions[internvention_id] = RumourInterventionBASE(tokenizer, t.source_text, t.reply_text_lst, alt_loc,t.is_rumour, device=DEVICE)
except:
pass
return interventions
def construct_combo_interventions(tweet_obj_lst, tokenizer, DEVICE):
interventions = {}
print('starting to construct token level interventions')
for t in tweet_obj_lst:
total_reply = len(t.reply_text_lst)
for alt_loc in range(0, total_reply):
internvention_id = t.source_id + '_' +str(alt_loc)
try:
interventions[internvention_id] = RumourComboIntervention(tokenizer, t.source_text, t.reply_text_lst, alt_loc, device=DEVICE)
except Exception as e:
print(e)
print('########FINISH COMBO LEVEL INTERVENTION CONSTRUCTION WITH NUMBER OF INTERVENTIONS ',len(interventions))
return interventions
def construct_story_intervention(story_lst, tokenizer, DEVICE):
interventions = {}
for s in story_lst:
total_source = len(s.source_text_lst)
print('s.story_id,', s.story_id)
for alt_loc in range(0, total_source):
intervention_id = str(s.story_id) + '_' + str(alt_loc)
try:
interventions[intervention_id] = PairIntervention(tokenizer, source_sentence=s.story_content, reaction_lst=s.source_text_lst, alt_loc=alt_loc, gold_label=s.is_rumour, turnaround_label_lst=s.source_turnaround_lst,max_len=256,device=DEVICE)
except Exception as e:
print(e)
print('########FINISH INTERVENTION CONSTRUCTION WITH NUMBER OF INTERVENTIONS ',len(interventions))
return interventions
def run_all(
model_type='roberta-base',
device="cuda",
out_dir=".",
random_weights=False,
load_pretrained_model=True,
pretrained_model='res/roberta_causal/',
debug_mode=False,
input_data_dir='',
rumour_veracity=False,
base_model=False,
tok_mode=False,
combo_test_mode=False,
):
# Set up all the potential combinations
intervention_types = get_intervention_types()
# Initialize Model and Tokenizer.
model = Model(device=device, model_version=model_type, random_weights=random_weights,load_pretrained_model=load_pretrained_model,pretrained_model=pretrained_model)
tokenizer = model.tokenizer
# Set up folder if it does not exist.
dt_string = datetime.now().strftime("%Y%m%d")
folder_name = dt_string + "_neuron_intervention"
base_path = os.path.join(out_dir, "results", folder_name)
if random_weights:
base_path = os.path.join(base_path, "random")
if not os.path.exists(base_path):
os.makedirs(base_path)
data_df = pd.read_pickle(input_data_dir)
listofTweets = [(TweetLite(row.source_id,row.source_text, row.reply_text_lst, row.is_rumour)) for index, row in data_df.iterrows() ]
if not combo_test_mode:
if not tok_mode:
if not base_model:
if not debug_mode:
interventions = construct_interventions(listofTweets, tokenizer, device)
else:
interventions = construct_debug_interventions(listofTweets, tokenizer, device)
else:
interventions = construct_base_interventions(listofTweets, tokenizer, device)
else:
interventions = construct_token_interventions(listofTweets, tokenizer, device)
else:
interventions = construct_combo_interventions(listofTweets, tokenizer, device)
print('number of interventions constructed ', len(interventions.keys()))
# Consider all the intervention types
for itype in intervention_types:
print("\t Running with intervention: {}".format(itype), flush=True)
# Run actual exp.
print('current intervention type ', itype)
if not base_model:
intervention_results = model.neuron_intervention_experiment(
interventions, intervention_type=itype, alpha=1.0,rumour_veracity=rumour_veracity
)
else:
intervention_results = model.base_neuron_intervention_experiment(
interventions
)
itype = 'base'
df = pd.DataFrame.from_dict(intervention_results,orient='index')
temp_string = "_".join('rumour_test_{}'.replace("{}", "X").split())
model_type_string = model_type
fname = "_".join([temp_string, itype, model_type_string])
# Finally, save each exp separately.
df.to_csv(os.path.join(base_path, fname + ".csv"))
df.to_pickle(os.path.join(base_path, fname + ".pkl"))
if __name__ == "__main__":
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
run_all(
model_type=opt.model,
device=device,
out_dir = opt.out_dir,
random_weights=opt.randomize,
load_pretrained_model=opt.load_pretrained_model,
pretrained_model = opt.pretrained_model,
debug_mode = opt.debug_mode,
input_data_dir = opt.input_data_dir,
rumour_veracity = opt.rumour_veracity,
base_model=opt.base_model,
tok_mode=opt.tok_mode,
combo_test_mode=opt.combo_test_mode,
)