forked from sed-inf-u-szeged/DeepBugHunter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
runner.py
593 lines (496 loc) · 22.5 KB
/
runner.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#
# This file just serves to give a better intuition of how we conducted batch experiments
# It is not strictly a part of the DBH infrastructure, just an automation layer one level above it
#
import re
import os
import copy
import pickle
from pathlib import Path
from bayes_opt import BayesianOptimization, UtilityFunction
import dbh
shared = {
'csv': 'dataset_vuln_full.csv',
'label': 'bug',
'clean': False,
'seed': 1337,
'output': os.path.abspath('output'),
'device': '/device:CPU:0',
'log_device': False,
'calc_completeness': True
}
data_steps = [
{
'preprocess': [['features', 'standardize'], ['labels', 'binarize']],
'resample': 'none',
'resample_amount': 0
},
]
basic_strategy = [
['keras', '--layers 5 --neurons 1024 --batch 16 --epochs 10 --lr 0.1 --save'],
# ['sdnnc', '--layers 5 --neurons 1024 --batch 16 --epochs 10 --lr 0.1'],
# ['forest', '--max-depth 10 --criterion entropy --n-estimators 5'],
]
def main():
for data_step in data_steps:
params = copy.deepcopy(shared)
params = {**params, **data_step, 'strategy': basic_strategy}
res = dbh.main(params)
return res[0][7]
def only_train(csv="dataset_vuln_full.csv", l=5, n=1024, b=512, e=10, lr=0.1, r='none', ra=0, save=False,
pretrain_conf=None):
train_conf = f'--layers {l} --neurons {n} --batch {b} --epochs {e} --lr {lr}'
if save:
train_conf = f"{train_conf} --save"
if pretrain_conf:
train_conf = f"{train_conf} --pretrain {pretrain_conf}"
data_step = {
'preprocess': [['labels', 'binarize']],
'resample': r,
'resample_amount': ra
}
basic_strategy[0][1] = train_conf
data_steps[0] = data_step
shared["csv"] = csv
return main(), f'{train_conf}_{r}_{ra}'
def do_train(csv, l, n, b, e, lr, r, ra, save=False, pretrain_conf=None):
train_f1, train_conf = only_train(csv, l, n, b, e, lr, r, ra, save, pretrain_conf)
with open("results_train.csv", 'a') as f:
f.write(f"{train_f1},{train_conf} {csv}\n")
return train_f1
def only_pretrain(csv="dataset_warn_full.csv", layers=5, neurons=1024, batch=512, epochs=10, lr=0.1, resample='none',
r_amount=0):
pre_train_conf = f'--layers {layers} --neurons {neurons} --batch {batch} --epochs {epochs} --lr {lr}'
data_step = {
'preprocess': [['features', 'standardize'], ['labels', 'binarize']],
'resample': resample,
'resample_amount': r_amount
}
basic_strategy[0][1] = pre_train_conf
data_steps[0] = data_step
shared["csv"] = csv
return main(), f'{pre_train_conf}_{resample}_{r_amount}'
def full_train(csv, l, n, b, e, lr, r, ra):
train_conf = f'--layers {l} --neurons {n} --batch {b} --epochs {e} --lr {lr}'
pre_train_id = f'layers-{l}_neurons-{n}_batch-{b}_epochs-{e}_lr-{lr}_beta-0.0_save-True_{r}_{ra}_1337_{csv[:-4]}'
train_conf_with_pretrain = f'{train_conf} --pretrain {pre_train_id}'
data_step = {
'preprocess': [],
'resample': r,
'resample_amount': ra
}
basic_strategy[0][1] = f'{train_conf} --save'
data_steps[0] = data_step
shared["csv"] = csv
pretrain_f_measure = main()
basic_strategy[0][1] = train_conf_with_pretrain
data_steps[0] = data_step
shared["csv"] = "graphcodebert_vuln_dataset.csv"
pretrained_f_measure = main()
basic_strategy[0][1] = train_conf
data_steps[0] = data_step
shared["csv"] = "graphcodebert_vuln_dataset.csv"
not_pretrained_f_measure = main()
return pretrain_f_measure, pretrained_f_measure, not_pretrained_f_measure, train_conf_with_pretrain
def do_full_train(csv, l, n, b, e, lr, r, ra):
pretrain_f1, pretrained_f1, not_pretrained_f1, train_conf = full_train(csv, l, n, b, e, lr, r, ra)
with open("results2.csv", 'a') as f:
f.write(f"{pretrain_f1},{pretrained_f1},{not_pretrained_f1},{train_conf}\n")
return pretrained_f1 - not_pretrained_f1
def touch_path(path):
path.parent.mkdir(exist_ok=True)
path.touch(exist_ok=True)
return path
def full_train_test():
layers = [7, 5, 3]
neurons = [2048, 1024, 512]
batches = [512, 256, 128]
epochs = [5, 10, 15, 20]
lrs = [.0001]
resample = ['down']
r_amount = [100]
csvs = ["dataset_warn_full.csv", "dataset_warn_without_minor.csv", "dataset_warn_without_minor_and_major.csv"]
for l in layers:
for n in neurons:
for b in batches:
for e in epochs:
for lr in lrs:
for r in resample:
for ra in r_amount:
for csv in csvs:
if (r == 'none' and ra != 0) or (r != 'none' and ra == 0):
continue
pickle_file = Path("pickles") / Path(
"_".join(map(lambda x: str(x), [csv, l, n, b, e, lr, r, ra])))
if pickle_file.exists():
continue
do_full_train(csv, l, n, b, e, lr, r, ra)
touch_path(pickle_file)
def set_fix_values(d, p, names):
for name in names:
p[name] = d[f"{name}_list"][int(round(p[name]))]
def set_round_values(p, names):
for name in names:
p[name] = int(round(p[name]))
def full_train_bayesian():
d = {
"csv_list": ["graphcodebert_warn_dataset_without_minor_and_major.csv",
"graphcodebert_warn_dataset_without_minor.csv", "graphcodebert_warn_dataset_full.csv"],
"n_list": [128, 256, 512, 1024, 2048, 4096, 8192, 16384],
"b_list": [128, 256, 512, 1024, 2048, 4096],
"r_list": ["none", "up", "down"]
}
# Create the optimizer. The black box function to optimize is not
# specified here, as we will call that function directly later on.
optimizer = BayesianOptimization(f=None,
pbounds={
"csv": [0, 2],
"l": [1, 20],
"n": [0, 7],
"b": [0, 5],
"e": [1, 100],
"lr": [.000001, .1],
"r": [0, 2],
"ra": [1, 100]
},
verbose=2, random_state=1337)
# Specify the acquisition function (bayes_opt uses the term
# utility function) to be the upper confidence bounds "ucb".
# We set kappa = 1.96 to balance exploration vs exploitation.
# xi = 0.01 is another hyper parameter which is required in the
# arguments, but is not used by "ucb". Other acquisition functions
# such as the expected improvement "ei" will be affected by xi.
utility = UtilityFunction(kind="ucb", kappa=1.96, xi=0.01)
# Optimization for loop.
for i in range(25):
# Get optimizer to suggest new parameter values to try using the
# specified acquisition function.
next_point = optimizer.suggest(utility)
# Force degree from float to int.
set_fix_values(d, next_point, ["csv", "n", "b", "r"])
set_round_values(next_point, ["l", "e"])
if (next_point['r'] == 'none' and next_point['ra'] != 0) or (
next_point['r'] != 'none' and next_point['ra'] == 0):
continue
next_point_values = [next_point[k] for k in ['csv', 'l', 'n', 'b', 'e', 'lr', 'r', 'ra']]
pickle_file = Path("pickles") / "bayes" / Path("_".join(map(lambda x: str(x), next_point_values)))
if pickle_file.exists():
with open(pickle_file, 'rb') as f:
target = pickle.load(f)
try:
optimizer.register(params=next_point, target=target)
except:
pass
print(f"Best result so far:")
print(optimizer.max)
continue
# Evaluate the output of the black_box_function using
# the new parameter values.
target = do_full_train(**next_point)
with open(pickle_file, 'wb') as f:
pickle.dump(target, f)
try:
# Update the optimizer with the evaluation results.
# This should be in try-except to catch any errors!
optimizer.register(params=next_point, target=target)
except:
pass
print(f"Best result so far:")
print(optimizer.max)
# def run_train_bayesian(train_type="train", dataset="dataset_vuln_full.csv", n=100):
# d = {
# "n_list": [128, 256, 512, 1024, 2048, 4096],
# "b_list": [128, 256, 512, 1024, 2048],
# "r_list": ["none", "up", "down"]
# }
#
# # Create the optimizer. The black box function to optimize is not
# # specified here, as we will call that function directly later on.
# optimizer = BayesianOptimization(f=None,
# pbounds={
# "l": [3, 7],
# "n": [0, 5],
# "b": [0, 4],
# "e": [1, 20],
# "lr": [.000001, .1],
# "r": [0, 2],
# "ra": [0, 100]
# },
# verbose=2, random_state=1337)
#
# # Specify the acquisition function (bayes_opt uses the term
# # utility function) to be the upper confidence bounds "ucb".
# # We set kappa = 1.96 to balance exploration vs exploitation.
# # xi = 0.01 is another hyper parameter which is required in the
# # arguments, but is not used by "ucb". Other acquisition functions
# # such as the expected improvement "ei" will be affected by xi.
# utility = UtilityFunction(kind="ucb", kappa=1.96, xi=0.01)
#
# best_f1_score = -1
#
# # Optimization for loop.
# for i in range(n):
# print(f'{i + 1}. iter')
# # Get optimizer to suggest new parameter values to try using the
# # specified acquisition function.
# next_point = optimizer.suggest(utility)
# # Force degree from float to int.
# set_fix_values(d, next_point, ["n", "b", "r"])
# set_round_values(next_point, ["l", "e"])
#
# if next_point['r'] == 'none' or next_point['ra'] == 0:
# next_point['r'] = 'none'
# next_point['ra'] = 0
#
# next_point_values = [next_point[k] for k in ['l', 'n', 'b', 'e', 'lr', 'r', 'ra']]
# pickle_file = Path("pickles") / f"bayes_{train_type}" / Path(
# f"{dataset}_" + "_".join(map(lambda x: str(x), next_point_values)))
# if pickle_file.exists():
# with open(pickle_file, 'rb') as f:
# target = pickle.load(f)
#
# else:
# # Evaluate the output of the black_box_function using
# # the new parameter values.
# target = do_train(csv=dataset, **next_point)
# with open(pickle_file, 'wb') as f:
# pickle.dump(target, f)
#
# if target > best_f1_score:
# best_f1_score = target
#
# try:
# # Update the optimizer with the evaluation results.
# # This should be in try-except to catch any errors!
# optimizer.register(params=next_point, target=target)
#
# except:
# pass
#
# print(f"Best result so far:")
# print(optimizer.max)
#
# return best_f1_score
def run_fine_tune_bayesian(train_type="fine_tune", pretrain_conf=None, dataset="dataset_vuln_full.csv", n=100):
d = {
"b_list": [128, 256, 512, 1024, 2048],
"r_list": ["none", "up", "down"]
}
# Create the optimizer. The black box function to optimize is not
# specified here, as we will call that function directly later on.
optimizer = BayesianOptimization(f=None,
pbounds={
"b": [0, 4],
"e": [1, 20],
"lr": [.000001, .1],
"r": [0, 2],
"ra": [0, 100]
},
verbose=2, random_state=1337)
# Specify the acquisition function (bayes_opt uses the term
# utility function) to be the upper confidence bounds "ucb".
# We set kappa = 1.96 to balance exploration vs exploitation.
# xi = 0.01 is another hyper parameter which is required in the
# arguments, but is not used by "ucb". Other acquisition functions
# such as the expected improvement "ei" will be affected by xi.
utility = UtilityFunction(kind="ucb", kappa=1.96, xi=0.01)
best_f1_score = -1
# Optimization for loop.
for i in range(n):
print(f'{i + 1}. iter')
# Get optimizer to suggest new parameter values to try using the
# specified acquisition function.
next_point = optimizer.suggest(utility)
# Force degree from float to int.
set_fix_values(d, next_point, ["b", "r"])
set_round_values(next_point, ["e"])
if next_point['r'] == 'none' or next_point['ra'] == 0:
next_point['r'] = 'none'
next_point['ra'] = 0
next_point['l'] = 0
next_point['n'] = 0
next_point_values = [next_point[k] for k in ['b', 'e', 'lr', 'r', 'ra']]
pre_train_conf_values = re.split(r'[-_]', pretrain_conf)
values = [v for i, v in enumerate(pre_train_conf_values) if
i in ([1, 3, 5, 7, 9, 11] + list(range(14, len(pre_train_conf_values))))]
pickle_file_name = Path(f"{dataset}_" + "_".join(map(lambda x: str(x), next_point_values)) + "_".join(values))
pickle_file = Path("pickles") / f"bayes_{train_type}" / pickle_file_name
if pickle_file.exists():
with open(pickle_file, 'rb') as f:
target = pickle.load(f)
else:
# Evaluate the output of the black_box_function using
# the new parameter values.
target = do_train(csv=dataset, **next_point, pretrain_conf=pretrain_conf)
with open(pickle_file, 'wb') as f:
pickle.dump(target, f)
if target > best_f1_score:
best_f1_score = target
try:
# Update the optimizer with the evaluation results.
# This should be in try-except to catch any errors!
optimizer.register(params=next_point, target=target)
except:
pass
print(f"Best result so far:")
print(optimizer.max)
return best_f1_score
def get_pre_train_conf_id(l, n, b, e, lr, r, ra, csv):
return f'layers-{l}_neurons-{n}_batch-{b}_epochs-{e}_lr-{lr}_beta-0.0_save-True_{r}_{ra}_1337_{csv[:-4]}'
def run_transfer_learning_bayesian(train_type="transfer_learning", dataset="graphcodebert_warn_dataset_full.csv",
fine_tune_dataset="", n=100):
d = {
"n_list": [128, 256, 512, 1024, 2048, 4096],
"b_list": [128, 256, 512, 1024, 2048],
"r_list": ["none", "up", "down"]
}
# Create the optimizer. The black box function to optimize is not
# specified here, as we will call that function directly later on.
optimizer = BayesianOptimization(f=None,
pbounds={
"l": [3, 7],
"n": [0, 5],
"b": [0, 4],
"e": [1, 20],
"lr": [.000001, .1],
"r": [0, 2],
"ra": [0, 100]
},
verbose=2, random_state=1337)
# Specify the acquisition function (bayes_opt uses the term
# utility function) to be the upper confidence bounds "ucb".
# We set kappa = 1.96 to balance exploration vs exploitation.
# xi = 0.01 is another hyper parameter which is required in the
# arguments, but is not used by "ucb". Other acquisition functions
# such as the expected improvement "ei" will be affected by xi.
utility = UtilityFunction(kind="ucb", kappa=1.96, xi=0.01)
best_f1 = -1
# Optimization for loop.
for i in range(n):
print(f'{i + 1}. iter')
# Get optimizer to suggest new parameter values to try using the
# specified acquisition function.
next_point = optimizer.suggest(utility)
# Force degree from float to int.
set_fix_values(d, next_point, ["n", "b", "r"])
set_round_values(next_point, ["l", "e"])
if next_point['r'] == 'none' or next_point['ra'] == 0:
next_point['r'] = 'none'
next_point['ra'] = 0
next_point_values = [next_point[k] for k in ['l', 'n', 'b', 'e', 'lr', 'r', 'ra']]
pickle_file = Path("pickles") / f"bayes_{train_type}" / Path(
f"{dataset}_" + "_".join(map(lambda x: str(x), next_point_values)))
if pickle_file.exists():
with open(pickle_file, 'rb') as f:
target = pickle.load(f)
else:
# Evaluate the output of the black_box_function using
# the new parameter values.
pre_train_f1 = do_train(csv=dataset, **next_point, save=True)
pre_train_id = get_pre_train_conf_id(csv=dataset, **next_point)
best_fine_tune_f1 = run_fine_tune_bayesian(pretrain_conf=pre_train_id, dataset=fine_tune_dataset)
target = best_fine_tune_f1
with open(pickle_file, 'wb') as f:
pickle.dump(target, f)
if target > best_f1:
best_f1 = target
try:
# Update the optimizer with the evaluation results.
# This should be in try-except to catch any errors!
optimizer.register(params=next_point, target=target)
except:
pass
print(f"Best result so far:")
print(optimizer.max)
def pre_train_test():
layers = [3, 5, 7]
neurons = [512, 1024, 2048]
batches = [128, 256, 512]
epochs = [10, 15, 20]
lrs = [.0001]
resample = ['none']
r_amount = [0]
csvs = ["dataset_warn_full.csv"]
for l in layers:
for n in neurons:
for b in batches:
for e in epochs:
for lr in lrs:
for r in resample:
for ra in r_amount:
for csv in csvs:
pickle_file = Path("pickles") / Path(
"_".join(map(lambda x: str(x), [csv, l, n, b, e, lr, r, ra])))
if pickle_file.exists():
continue
res, conf = only_pretrain(csv, l, n, b, e, lr, r, ra)
with open("results_pretrain.csv", 'a') as f:
f.write(f"{res},{conf} {csv}\n")
with open(touch_path(pickle_file), "wb") as f:
pickle.dump(pickle_file, f)
def run_train_bayesian(train_type="ossf_test", dataset="graphcodebert_warn_dataset_full.csv", n=100):
d = {
"n_list": [128, 256, 512, 1024, 2048, 4096],
"b_list": [128, 256, 512, 1024, 2048],
"r_list": ["none", "up", "down"]
}
# Create the optimizer. The black box function to optimize is not
# specified here, as we will call that function directly later on.
optimizer = BayesianOptimization(f=None,
pbounds={
"l": [3, 7],
"n": [0, 5],
"b": [0, 4],
"e": [1, 20],
"lr": [.000001, .1],
"r": [0, 2],
"ra": [0, 100]
},
verbose=2, random_state=1337)
# Specify the acquisition function (bayes_opt uses the term
# utility function) to be the upper confidence bounds "ucb".
# We set kappa = 1.96 to balance exploration vs exploitation.
# xi = 0.01 is another hyper parameter which is required in the
# arguments, but is not used by "ucb". Other acquisition functions
# such as the expected improvement "ei" will be affected by xi.
utility = UtilityFunction(kind="ucb", kappa=1.96, xi=0.01)
best_f1 = -1
# Optimization for loop.
for i in range(n):
print(f'{i + 1}. iter')
# Get optimizer to suggest new parameter values to try using the
# specified acquisition function.
next_point = optimizer.suggest(utility)
# Force degree from float to int.
set_fix_values(d, next_point, ["n", "b", "r"])
set_round_values(next_point, ["l", "e"])
if next_point['r'] == 'none' or next_point['ra'] == 0:
next_point['r'] = 'none'
next_point['ra'] = 0
next_point_values = [next_point[k] for k in ['l', 'n', 'b', 'e', 'lr', 'r', 'ra']]
pickle_file = Path("pickles") / f"bayes_{train_type}" / f'{dataset}_{"_".join(map(lambda x: str(x), next_point_values))}'
if pickle_file.exists():
with open(pickle_file, 'rb') as f:
target = pickle.load(f)
else:
# Evaluate the output of the black_box_function using
# the new parameter values.
target = do_train(csv=dataset, **next_point, save=True)
with open(pickle_file, 'wb') as f:
pickle.dump(target, f)
if target > best_f1:
best_f1 = target
try:
# Update the optimizer with the evaluation results.
# This should be in try-except to catch any errors!
optimizer.register(params=next_point, target=target)
except:
pass
print(f"Best result so far:")
print(optimizer.max)
if __name__ == '__main__':
# main()
# full_train_test()
# run_train_bayesian(train_type="pretrain", dataset="dataset_warn_full.csv", n=200)
run_train_bayesian(dataset="train_balanced_features_data.csv", n=100)
# pre_train_test()