-
Notifications
You must be signed in to change notification settings - Fork 0
/
ga_fuzzing.py
executable file
·1643 lines (1249 loc) · 69.3 KB
/
ga_fuzzing.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
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
from importlib_metadata import version
from customized_utils import parse_fuzzing_arguments
sys.path.append('pymoo')
sys.path.append('fuzzing_utils')
fuzzing_arguments = parse_fuzzing_arguments()
if not fuzzing_arguments.debug:
import warnings
warnings.filterwarnings("ignore")
if fuzzing_arguments.simulator in ['carla_op']:
carla_root = os.path.expanduser('~/Documents/self-driving-cars/carla_0911_rss')
if not os.path.exists(carla_root):
carla_root = os.path.expanduser('~/Documents/self-driving-cars/carla_0911_no_rss')
fuzzing_arguments.carla_path = os.path.join(carla_root, "CarlaUE4.sh")
sys.path.append(carla_root+'/PythonAPI/carla/dist/carla-0.9.11-py3.7-linux-x86_64.egg')
sys.path.append(carla_root+'/PythonAPI/carla')
sys.path.append(carla_root+'/PythonAPI')
# TBD: change to relative paths
sys.path.append(os.path.expanduser('~/openpilot'))
sys.path.append(os.path.expanduser('~/openpilot/tools/sim'))
if version('carla') != '0.9.11':
egg_path = os.path.join(carla_root, 'PythonAPI/carla/dist/carla-0.9.11-py3.7-linux-x86_64.egg')
# os.system('pip uninstall carla')
os.system('easy_install '+egg_path)
import json
import re
import time
import pathlib
import pickle
import copy
import atexit
import traceback
import math
from datetime import datetime
from distutils.dir_util import copy_tree
import numpy as np
from sklearn.preprocessing import StandardScaler
from scipy.stats import rankdata
from multiprocessing import Process, Manager, set_start_method
from pymoo.model.problem import Problem
from pymoo.model.sampling import Sampling
from pymoo.model.crossover import Crossover
from pymoo.model.mutation import Mutation
from pymoo.model.population import Population
from pymoo.model.evaluator import Evaluator
from pymoo.algorithms.nsga2 import NSGA2, binary_tournament
from pymoo.operators.selection.tournament_selection import TournamentSelection
from pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover
from pymoo.model.termination import Termination
from pymoo.util.termination.default import MultiObjectiveDefaultTermination, SingleObjectiveDefaultTermination
from pymoo.model.repair import Repair
from pymoo.operators.mixed_variable_operator import MixedVariableMutation, MixedVariableCrossover
from pymoo.factory import get_crossover, get_mutation, get_termination
from pymoo.model.mating import Mating
from pymoo.model.initialization import Initialization
from pymoo.model.duplicate import NoDuplicateElimination
from pymoo.model.survival import Survival
from pymoo.model.individual import Individual
# disable pymoo optimization warning
from pymoo.configuration import Configuration
Configuration.show_compile_hint = False
from pgd_attack import pgd_attack, train_net, train_regression_net, VanillaDataset
from acquisition import map_acquisition
from customized_utils import rand_real, make_hierarchical_dir, exit_handler, is_critical_region, if_violate_constraints, filter_critical_regions, encode_fields, remove_fields_not_changing, get_labels_to_encode, customized_fit, customized_standardize, customized_inverse_standardize, decode_fields, encode_bounds, recover_fields_not_changing, process_X, inverse_process_X, calculate_rep_d, select_batch_max_d_greedy, if_violate_constraints_vectorized, is_distinct_vectorized, eliminate_repetitive_vectorized, get_sorted_subfolders, load_data, get_F, set_general_seed, emptyobject, get_job_results, choose_farthest_offs
# eliminate some randomness
set_general_seed(seed=fuzzing_arguments.random_seed)
# random_seeds = [0, 10, 20]
rng = np.random.default_rng(fuzzing_arguments.random_seed)
def fun(obj, x, launch_server, counter, port, return_dict):
dt = obj.dt
estimator = obj.estimator
critical_unique_leaves = obj.critical_unique_leaves
customized_constraints = obj.customized_constraints
labels = obj.labels
default_objectives = obj.fuzzing_arguments.default_objectives
run_simulation = obj.run_simulation
fuzzing_content = obj.fuzzing_content
fuzzing_arguments = obj.fuzzing_arguments
sim_specific_arguments = obj.sim_specific_arguments
dt_arguments = obj.dt_arguments
not_critical_region = dt and not is_critical_region(x, estimator, critical_unique_leaves)
violate_constraints, _ = if_violate_constraints(x, customized_constraints, labels, verbose=True)
if not_critical_region or violate_constraints:
returned_data = [default_objectives, None, 0]
else:
objectives, run_info = run_simulation(x, fuzzing_content, fuzzing_arguments, sim_specific_arguments, dt_arguments, launch_server, counter, port)
print('\n'*3)
print("counter, run_info['is_bug'], run_info['bug_type'], objectives", counter, run_info['is_bug'], run_info['bug_type'], objectives)
print('\n'*3)
# correct_travel_dist(x, labels, customized_data['tmp_travel_dist_file'])
returned_data = [objectives, run_info, 1]
if return_dict is not None:
return_dict['returned_data'] = returned_data
return returned_data
class MyProblem(Problem):
def __init__(self, fuzzing_arguments, sim_specific_arguments, fuzzing_content, run_simulation, dt_arguments):
self.fuzzing_arguments = fuzzing_arguments
self.sim_specific_arguments = sim_specific_arguments
self.fuzzing_content = fuzzing_content
self.run_simulation = run_simulation
self.dt_arguments = dt_arguments
self.ego_car_model = fuzzing_arguments.ego_car_model
#self.scheduler_port = fuzzing_arguments.scheduler_port
#self.dashboard_address = fuzzing_arguments.dashboard_address
self.ports = fuzzing_arguments.ports
self.episode_max_time = fuzzing_arguments.episode_max_time
self.objective_weights = fuzzing_arguments.objective_weights
self.check_unique_coeff = fuzzing_arguments.check_unique_coeff
self.consider_interested_bugs = fuzzing_arguments.consider_interested_bugs
self.record_every_n_step = fuzzing_arguments.record_every_n_step
self.use_single_objective = fuzzing_arguments.use_single_objective
self.simulator = fuzzing_arguments.simulator
if self.fuzzing_arguments.sample_avoid_ego_position and hasattr(self.sim_specific_arguments, 'ego_start_position'):
self.ego_start_position = self.sim_specific_arguments.ego_start_position
else:
self.ego_start_position = None
self.call_from_dt = dt_arguments.call_from_dt
self.dt = dt_arguments.dt
self.estimator = dt_arguments.estimator
self.critical_unique_leaves = dt_arguments.critical_unique_leaves
self.cumulative_info = dt_arguments.cumulative_info
cumulative_info = dt_arguments.cumulative_info
if cumulative_info:
self.counter = cumulative_info['counter']
self.has_run = cumulative_info['has_run']
self.start_time = cumulative_info['start_time']
self.time_list = cumulative_info['time_list']
self.bugs = cumulative_info['bugs']
self.unique_bugs = cumulative_info['unique_bugs']
self.interested_unique_bugs = cumulative_info['interested_unique_bugs']
self.bugs_type_list = cumulative_info['bugs_type_list']
self.bugs_inds_list = cumulative_info['bugs_inds_list']
self.bugs_num_list = cumulative_info['bugs_num_list']
self.unique_bugs_num_list = cumulative_info['unique_bugs_num_list']
self.has_run_list = cumulative_info['has_run_list']
else:
self.counter = 0
self.has_run = 0
self.start_time = time.time()
self.time_list = []
self.bugs = []
self.unique_bugs = []
self.interested_unique_bugs = []
self.bugs_type_list = []
self.bugs_inds_list = []
self.bugs_num_list = []
self.unique_bugs_num_list = []
self.has_run_list = []
self.labels = fuzzing_content.labels
self.mask = fuzzing_content.mask
self.parameters_min_bounds = fuzzing_content.parameters_min_bounds
self.parameters_max_bounds = fuzzing_content.parameters_max_bounds
self.parameters_distributions = fuzzing_content.parameters_distributions
self.customized_constraints = fuzzing_content.customized_constraints
self.customized_center_transforms = fuzzing_content.customized_center_transforms
xl = [pair[1] for pair in self.parameters_min_bounds.items()]
xu = [pair[1] for pair in self.parameters_max_bounds.items()]
n_var = fuzzing_content.n_var
self.p, self.c, self.th = self.check_unique_coeff
self.launch_server = True
self.objectives_list = []
self.trajectory_vector_list = []
self.x_list = []
self.y_list = []
self.F_list = []
super().__init__(n_var=n_var, n_obj=4, n_constr=0, xl=xl, xu=xu)
def _evaluate(self, X, out, *args, **kwargs):
objective_weights = self.objective_weights
customized_center_transforms = self.customized_center_transforms
episode_max_time = self.episode_max_time
default_objectives = self.fuzzing_arguments.default_objectives
standardize_objective = self.fuzzing_arguments.standardize_objective
normalize_objective = self.fuzzing_arguments.normalize_objective
traj_dist_metric = self.fuzzing_arguments.traj_dist_metric
all_final_generated_transforms_list = []
# non-dask subprocess implementation
# rng = np.random.default_rng(random_seeds[1])
tmp_run_info_list = []
x_sublist = []
objectives_sublist_non_traj = []
trajectory_vector_sublist = []
for i in range(X.shape[0]):
if self.counter == 0:
launch_server = True
else:
launch_server = False
cur_i = i
total_i = self.counter
port = self.ports[0]
x = X[cur_i]
# No need to use subprocess when no simulation is running
if self.fuzzing_arguments.simulator == 'no_simulation':
return_dict = {}
fun(self, x, launch_server, self.counter, port, return_dict)
else:
manager = Manager()
return_dict = manager.dict()
try:
p = Process(target=fun, args=(self, x, launch_server, self.counter, port, return_dict))
p.start()
p.join(240)
if p.is_alive():
print("Function is hanging!")
p.terminate()
print("Kidding, just terminated!")
except:
traceback.print_exc()
objectives, run_info, has_run = default_objectives, None, 0
if 'returned_data' in return_dict:
objectives, run_info, has_run = return_dict['returned_data']
else:
# TBD: add an error log
print('\n'*3, 'returned_data is missing', '\n'*3)
objectives, run_info, has_run = default_objectives, None, 0
print('get job result for', total_i)
if run_info and 'all_final_generated_transforms' in run_info:
all_final_generated_transforms_list.append(run_info['all_final_generated_transforms'])
self.has_run_list.append(has_run)
self.has_run += has_run
# record bug
if run_info and run_info['is_bug']:
self.bugs.append(X[cur_i].astype(float))
self.bugs_inds_list.append(total_i)
self.bugs_type_list.append(run_info['bug_type'])
self.y_list.append(run_info['bug_type'])
else:
self.y_list.append(0)
self.counter += 1
tmp_run_info_list.append(run_info)
x_sublist.append(x)
objectives_sublist_non_traj.append(objectives)
if run_info and 'trajectory_vector' in run_info:
trajectory_vector_sublist.append(run_info['trajectory_vector'])
else:
trajectory_vector_sublist.append(None)
job_results, self.x_list, self.objectives_list, self.trajectory_vector_list = get_job_results(tmp_run_info_list, x_sublist, objectives_sublist_non_traj, trajectory_vector_sublist, self.x_list, self.objectives_list, self.trajectory_vector_list, traj_dist_metric)
# print('self.objectives_list', self.objectives_list)
# hack:
if run_info and 'all_final_generated_transforms' in run_info:
with open('carla_lbc/tmp_folder/total.pickle', 'wb') as f_out:
pickle.dump(all_final_generated_transforms_list, f_out)
# record time elapsed and bug numbers
time_elapsed = time.time() - self.start_time
self.time_list.append(time_elapsed)
current_F = get_F(job_results, self.objectives_list, objective_weights, self.use_single_objective, standardize=standardize_objective, normalize=normalize_objective)
out["F"] = current_F
self.F_list.append(current_F)
print('\n'*3, 'self.F_list', len(self.F_list), self.F_list, '\n'*3)
print('\n'*10, '+'*100)
bugs_type_list_tmp = self.bugs_type_list
bugs_tmp = self.bugs
bugs_inds_list_tmp = self.bugs_inds_list
self.unique_bugs, unique_bugs_inds_list, self.interested_unique_bugs, bugcounts = get_unique_bugs(self.x_list, self.objectives_list, self.mask, self.xl, self.xu, self.check_unique_coeff, objective_weights, return_mode='unique_inds_and_interested_and_bugcounts', consider_interested_bugs=1, bugs_type_list=bugs_type_list_tmp, bugs=bugs_tmp, bugs_inds_list=bugs_inds_list_tmp, trajectory_vector_list=self.trajectory_vector_list)
time_elapsed = time.time() - self.start_time
num_of_bugs = len(self.bugs)
num_of_unique_bugs = len(self.unique_bugs)
num_of_interested_unique_bugs = len(self.interested_unique_bugs)
self.bugs_num_list.append(num_of_bugs)
self.unique_bugs_num_list.append(num_of_unique_bugs)
mean_objectives_this_generation = np.mean(np.array(self.objectives_list[-X.shape[0]:]), axis=0)
with open(self.fuzzing_arguments.mean_objectives_across_generations_path, 'a') as f_out:
info_dict = {
'counter': self.counter,
'has_run': self.has_run,
'time_elapsed': time_elapsed,
'num_of_bugs': num_of_bugs,
'num_of_unique_bugs': num_of_unique_bugs,
'num_of_interested_unique_bugs': num_of_interested_unique_bugs,
'bugcounts and unique bug counts': bugcounts, 'mean_objectives_this_generation': mean_objectives_this_generation.tolist(),
'current_F': current_F
}
f_out.write(str(info_dict))
f_out.write(';'.join([str(ind) for ind in unique_bugs_inds_list])+' objective_weights : '+str(self.objective_weights)+'\n')
print(info_dict)
print('+'*100, '\n'*10)
class GridSampling(Sampling):
def __init__(self, grid_start_index, grid_dict):
self.grid_start_index = grid_start_index
import itertools
gird_value_list = list(itertools.product(*list(grid_dict.values())))
print('total combinations:', len(gird_value_list))
gird_value_list = list(zip(*gird_value_list))
self.grid_value_dict = {k:gird_value_list[i] for i, k in enumerate(grid_dict.keys())}
def _do(self, problem, n_samples, **kwargs):
xl = problem.xl
xu = problem.xu
mask = np.array(problem.mask)
labels = problem.labels
parameters_distributions = problem.parameters_distributions
print('\n', 'self.grid_start_index:', self.grid_start_index, '\n')
def subroutine(X):
def sample_one_feature(typ, lower, upper, dist, label, size=1):
assert lower <= upper, label+','+str(lower)+'>'+str(upper)
if typ == 'int':
val = rng.integers(lower, upper+1, size=size)
elif typ == 'real':
if dist[0] == 'normal':
if dist[1] == None:
mean = (lower+upper)/2
else:
mean = dist[1]
val = rng.normal(mean, dist[2], size=size)
else: # default is uniform
val = rng.random(size=size) * (upper - lower) + lower
val = np.clip(val, lower, upper)
return val
n_samples_sampling = n_samples
while len(X) < n_samples:
cur_X = []
for i, dist in enumerate(parameters_distributions):
typ = mask[i]
lower = xl[i]
upper = xu[i]
label = labels[i]
if label in self.grid_value_dict:
assert self.grid_start_index+n_samples_sampling <= len(self.grid_value_dict[label]), str(self.grid_start_index+n_samples_sampling)+'>'+str(len(self.grid_value_dict[label]))
val = self.grid_value_dict[label][self.grid_start_index:self.grid_start_index+n_samples_sampling]
else:
val = sample_one_feature(typ, lower, upper, dist, label, size=n_samples_sampling)
cur_X.append(val)
cur_X = np.swapaxes(np.stack(cur_X),0,1)
remaining_inds = if_violate_constraints_vectorized(cur_X, problem.customized_constraints, problem.labels, problem.ego_start_position, verbose=False)
if len(remaining_inds) == 0:
continue
cur_X = cur_X[remaining_inds]
X.extend(cur_X)
self.grid_start_index += n_samples
n_samples_sampling = n_samples - len(X)
return X
X = []
X = subroutine(X)
if len(X) > 0:
X = np.stack(X)
else:
X = np.array([])
return X
class MySamplingVectorized(Sampling):
def __init__(self, use_unique_bugs, check_unique_coeff, sample_multiplier=500):
self.use_unique_bugs = use_unique_bugs
self.check_unique_coeff = check_unique_coeff
self.sample_multiplier = sample_multiplier
assert len(self.check_unique_coeff) == 3
def _do(self, problem, n_samples, **kwargs):
p, c, th = self.check_unique_coeff
xl = problem.xl
xu = problem.xu
mask = np.array(problem.mask)
labels = problem.labels
parameters_distributions = problem.parameters_distributions
if self.sample_multiplier >= 50:
max_sample_times = self.sample_multiplier // 50
n_samples_sampling = n_samples * 50
else:
max_sample_times = self.sample_multiplier
n_samples_sampling = n_samples
algorithm = kwargs['algorithm']
tmp_off = algorithm.tmp_off
tmp_off_and_X = []
if len(tmp_off) > 0:
tmp_off = [off.X for off in tmp_off]
tmp_off_and_X = tmp_off
def subroutine(X, tmp_off_and_X):
def sample_one_feature(typ, lower, upper, dist, label, size=1):
assert lower <= upper, label+','+str(lower)+'>'+str(upper)
if typ == 'int':
val = rng.integers(lower, upper+1, size=size)
elif typ == 'real':
if dist[0] == 'normal':
if dist[1] == None:
mean = (lower+upper)/2
else:
mean = dist[1]
val = rng.normal(mean, dist[2], size=size)
else: # default is uniform
val = rng.random(size=size) * (upper - lower) + lower
val = np.clip(val, lower, upper)
return val
# TBD: temporary
sample_time = 0
while sample_time < max_sample_times and len(X) < n_samples:
print('sample_time / max_sample_times', sample_time, '/', max_sample_times, 'len(X)', len(X))
sample_time += 1
cur_X = []
for i, dist in enumerate(parameters_distributions):
typ = mask[i]
lower = xl[i]
upper = xu[i]
label = labels[i]
val = sample_one_feature(typ, lower, upper, dist, label, size=n_samples_sampling)
cur_X.append(val)
cur_X = np.swapaxes(np.stack(cur_X),0,1)
remaining_inds = if_violate_constraints_vectorized(cur_X, problem.customized_constraints, problem.labels, problem.ego_start_position, verbose=False)
if len(remaining_inds) == 0:
continue
cur_X = cur_X[remaining_inds]
if not self.use_unique_bugs:
X.extend(cur_X)
if len(X) > n_samples:
X = X[:n_samples]
else:
if len(tmp_off_and_X) > 0 and len(problem.interested_unique_bugs) > 0:
prev_X = np.concatenate([problem.interested_unique_bugs, tmp_off_and_X])
elif len(tmp_off_and_X) > 0:
prev_X = tmp_off_and_X
else:
prev_X = problem.interested_unique_bugs
remaining_inds = is_distinct_vectorized(cur_X, prev_X, mask, xl, xu, p, c, th, verbose=False)
if len(remaining_inds) == 0:
continue
else:
cur_X = cur_X[remaining_inds]
X.extend(cur_X)
if len(X) > n_samples:
X = X[:n_samples]
if len(tmp_off) > 0:
tmp_off_and_X = tmp_off + X
else:
tmp_off_and_X = X
return X, sample_time
X = []
X, sample_time_1 = subroutine(X, tmp_off_and_X)
if len(X) > 0:
X = np.stack(X)
else:
X = np.array([])
print('\n'*3, 'We sampled', X.shape[0], '/', n_samples, 'samples', 'by sampling', sample_time_1, 'times' '\n'*3)
return X
def do_emcmc(parents, off, n_gen, objective_weights, default_objectives):
base_val = np.sum(np.array(default_objectives[:len(objective_weights)])*np.array(objective_weights))
filtered_off = []
F_list = []
for i in off:
for p in parents:
print(i.F, p.F)
i_val = np.sum(np.array(i.F) * np.array(objective_weights))
p_val = np.sum(np.array(p.F) * np.array(objective_weights))
print('1', base_val, i_val, p_val)
i_val = np.abs(base_val-i_val)
p_val = np.abs(base_val-p_val)
prob = np.min([i_val / p_val, 1])
print('2', base_val, i_val, p_val, prob)
if np.random.uniform() < prob:
filtered_off.append(i.X)
F_list.append(i.F)
pop = Population(len(filtered_off), individual=Individual())
pop.set("X", filtered_off, "F", F_list, "n_gen", n_gen, "CV", [0 for _ in range(len(filtered_off))], "feasible", [[True] for _ in range(len(filtered_off))])
return Population.merge(parents, off)
class MyMatingVectorized(Mating):
def __init__(self,
selection,
crossover,
mutation,
use_unique_bugs,
emcmc,
mating_max_iterations,
**kwargs):
super().__init__(selection, crossover, mutation, **kwargs)
self.use_unique_bugs = use_unique_bugs
self.mating_max_iterations = mating_max_iterations
self.emcmc = emcmc
def do(self, problem, pop, n_offsprings, **kwargs):
if self.mating_max_iterations >= 5:
mating_max_iterations = self.mating_max_iterations // 5
n_offsprings_sampling = n_offsprings * 5
else:
mating_max_iterations = self.mating_max_iterations
n_offsprings_sampling = n_offsprings
# the population object to be used
off = pop.new()
parents = pop.new()
# infill counter - counts how often the mating needs to be done to fill up n_offsprings
n_infills = 0
# iterate until enough offsprings are created
while len(off) < n_offsprings:
n_infills += 1
print('n_infills / mating_max_iterations', n_infills, '/', mating_max_iterations, 'len(off)', len(off))
# if no new offsprings can be generated within a pre-specified number of generations
if n_infills >= mating_max_iterations:
break
# how many offsprings are remaining to be created
n_remaining = n_offsprings - len(off)
# do the mating
_off, _parents = self._do(problem, pop, n_offsprings_sampling, **kwargs)
# repair the individuals if necessary - disabled if repair is NoRepair
_off_first = self.repair.do(problem, _off, **kwargs)
# Vectorized
_off_X = np.array([x.X for x in _off_first])
remaining_inds = if_violate_constraints_vectorized(_off_X, problem.customized_constraints, problem.labels, problem.ego_start_position, verbose=False)
_off_X = _off_X[remaining_inds]
_off = _off_first[remaining_inds]
_parents = _parents[remaining_inds]
# Vectorized
if self.use_unique_bugs:
if len(_off) == 0:
continue
elif len(off) > 0 and len(problem.interested_unique_bugs) > 0:
prev_X = np.concatenate([problem.interested_unique_bugs, np.array([x.X for x in off])])
elif len(off) > 0:
prev_X = np.array([x.X for x in off])
else:
prev_X = problem.interested_unique_bugs
print('\n', 'MyMating len(prev_X)', len(prev_X), '\n')
remaining_inds = is_distinct_vectorized(_off_X, prev_X, problem.mask, problem.xl, problem.xu, problem.p, problem.c, problem.th, verbose=False)
if len(remaining_inds) == 0:
continue
_off = _off[remaining_inds]
_parents = _parents[remaining_inds]
assert len(_parents)==len(_off)
# if more offsprings than necessary - truncate them randomly
if len(off) + len(_off) > n_offsprings:
# IMPORTANT: Interestingly, this makes a difference in performance
n_remaining = n_offsprings - len(off)
_off = _off[:n_remaining]
_parents = _parents[:n_remaining]
# add to the offsprings and increase the mating counter
off = Population.merge(off, _off)
parents = Population.merge(parents, _parents)
# assert len(parents)==len(off)
print('Mating finds', len(off), 'offsprings after doing', n_infills, '/', mating_max_iterations, 'mating iterations')
return off, parents
# only to get parents
def _do(self, problem, pop, n_offsprings, parents=None, **kwargs):
# if the parents for the mating are not provided directly - usually selection will be used
if parents is None:
# how many parents need to be select for the mating - depending on number of offsprings remaining
n_select = math.ceil(n_offsprings / self.crossover.n_offsprings)
# select the parents for the mating - just an index array
parents = self.selection.do(pop, n_select, self.crossover.n_parents, **kwargs)
parents_obj = pop[parents].reshape([-1, 1]).squeeze()
else:
parents_obj = parents
# do the crossover using the parents index and the population - additional data provided if necessary
_off = self.crossover.do(problem, pop, parents, **kwargs)
# do the mutation on the offsprings created through crossover
_off = self.mutation.do(problem, _off, **kwargs)
return _off, parents_obj
# from pymoo.model.selection import Selection
# class RouletteSelection(Selection):
#
# def _do(self, pop, n_select, n_parents, **kwargs):
#
# prob = []
# for p in pop:
# prob.append(p.F)
# (n_select, prob)
#
# # number of random individuals needed
# n_random = n_select * n_parents
#
# # number of permutations needed
# n_perms = math.ceil(n_random / len(pop))
#
# # get random permutations and reshape them
# P = random_permuations(n_perms, len(pop))[:n_random]
#
# return np.reshape(P, (n_select, n_parents))
class NSGA2_CUSTOMIZED(NSGA2):
def __init__(self, dt=False, X=None, F=None, fuzzing_arguments=None, plain_sampling=None, local_mating=None, **kwargs):
self.dt = dt
self.X = X
self.F = F
self.plain_sampling = plain_sampling
self.sampling = kwargs['sampling']
self.pop_size = fuzzing_arguments.pop_size
self.n_offsprings = fuzzing_arguments.n_offsprings
self.survival_multiplier = fuzzing_arguments.survival_multiplier
self.algorithm_name = fuzzing_arguments.algorithm_name
self.emcmc = fuzzing_arguments.emcmc
self.initial_fit_th = fuzzing_arguments.initial_fit_th
self.rank_mode = fuzzing_arguments.rank_mode
self.min_bug_num_to_fit_dnn = fuzzing_arguments.min_bug_num_to_fit_dnn
self.ranking_model = fuzzing_arguments.ranking_model
self.use_unique_bugs = fuzzing_arguments.use_unique_bugs
self.pgd_eps = fuzzing_arguments.pgd_eps
self.adv_conf_th = fuzzing_arguments.adv_conf_th
self.attack_stop_conf = fuzzing_arguments.attack_stop_conf
self.uncertainty = fuzzing_arguments.uncertainty
self.warm_up_path = fuzzing_arguments.warm_up_path
self.warm_up_len = fuzzing_arguments.warm_up_len
self.regression_nn_use_running_data = fuzzing_arguments.regression_nn_use_running_data
self.only_run_unique_cases = fuzzing_arguments.only_run_unique_cases
super().__init__(pop_size=self.pop_size, n_offsprings=self.n_offsprings, **kwargs)
self.plain_initialization = Initialization(self.plain_sampling, individual=Individual(), repair=self.repair, eliminate_duplicates= NoDuplicateElimination())
# heuristic: we keep up about 1 times of each generation's population
self.survival_size = self.pop_size * self.survival_multiplier
self.all_pop_run_X = []
# hack: defined separately w.r.t. MyMating
self.mating_max_iterations = 1
self.tmp_off = []
self.tmp_off_type_1_len = 0
# self.tmp_off_type_1and2_len = 0
self.high_conf_configs_stack = []
self.high_conf_configs_ori_stack = []
self.device_name = 'cuda'
# avfuzzer variables
self.best_y_gen = []
self.global_best_y = [None, 10000]
self.restart_best_y = [None, 10000]
self.local_best_y = [None, 10000]
self.pop_before_local = None
self.local_gen = -1
self.restart_gen = 0
self.cur_gen = -1
self.local_mating = local_mating
self.mutation = kwargs['mutation']
self.minLisGen = 2
def set_off(self):
self.tmp_off = []
if self.algorithm_name == 'avfuzzer':
cur_best_y = [None, 10000]
if self.cur_gen >= 0:
# local search
if 0 <= self.local_gen <= 4:
with open('tmp_log.txt', 'a') as f_out:
f_out.write(str(self.cur_gen)+' local '+str(self.local_gen)+'\n')
cur_pop = self.pop[-self.pop_size:]
for p in cur_pop:
if p.F < self.local_best_y[1]:
self.local_best_y = [p, p.F]
if self.local_gen == 4:
self.local_gen = -1
if self.local_best_y[1] < self.global_best_y[1]:
self.global_best_y = self.local_best_y
if self.local_best_y[1] < self.best_y_gen[-1][1]:
self.best_y_gen[-1] = self.local_best_y
# if self.local_best_y[1] < self.restart_best_y[1]:
# self.restart_best_y = self.local_best_y
tmp_best_ind = 0
tmp_best_y = [None, 10000]
for i, p in enumerate(self.pop_before_local):
if p.F < tmp_best_y[1]:
tmp_best_y = [p, p.F]
tmp_best_ind = i
self.pop_before_local[tmp_best_ind] = self.local_best_y[0]
self.tmp_off, _ = self.mating.do(self.problem, self.pop_before_local, self.n_offsprings, algorithm=self)
self.cur_gen += 1
else:
self.local_gen += 1
self.tmp_off, _ = self.local_mating.do(self.problem, self.pop, self.n_offsprings, algorithm=self)
# global search
else:
cur_pop = self.pop[-self.pop_size:]
for p in cur_pop:
if p.F < cur_best_y[1]:
cur_best_y = [p, p.F]
if cur_best_y[1] < self.global_best_y[1]:
self.global_best_y = cur_best_y
if len(self.best_y_gen) == self.cur_gen:
self.best_y_gen.append(cur_best_y)
else:
if cur_best_y[1] < self.best_y_gen[-1][1]:
self.best_y_gen[-1] = cur_best_y
if self.cur_gen - self.restart_gen <= self.minLisGen:
if cur_best_y[1] < self.restart_best_y[1]:
self.restart_best_y = cur_best_y
with open('tmp_log.txt', 'a') as f_out:
f_out.write('self.global_best_y: '+ str(self.global_best_y[1])+', cur_best_y[1]: '+str(cur_best_y[1])+', self.restart_best_y[1]: '+str(self.restart_best_y[1])+'\n')
normal = True
# restart
if self.cur_gen - self.restart_gen > 4:
last_5_mean = np.mean([v for _, v in self.best_y_gen[-5:]])
with open('tmp_log.txt', 'a') as f_out:
f_out.write('last_5_mean: '+str(last_5_mean)+', cur_best_y[1]: '+str(cur_best_y[1])+'\n')
if cur_best_y[1] >= last_5_mean:
with open('tmp_log.txt', 'a') as f_out:
f_out.write(str(self.cur_gen)+' restart'+'\n')
tmp_off_candidates = self.plain_initialization.do(self.problem, 1000, algorithm=self)
tmp_off_candidates_X = np.stack([p.X for p in tmp_off_candidates])
chosen_inds = choose_farthest_offs(tmp_off_candidates_X, self.all_pop_run_X, self.pop_size)
self.tmp_off = tmp_off_candidates[chosen_inds]
self.restart_best_y = [None, 10000]
normal = False
self.cur_gen += 1
self.restart_gen = self.cur_gen
# enter local
if normal and self.cur_gen - self.restart_gen > self.minLisGen and cur_best_y[1] < self.restart_best_y[1]:
with open('tmp_log.txt', 'a') as f_out:
f_out.write(str(self.cur_gen)+'enter local'+'\n')
self.restart_best_y[1] = cur_best_y[1]
self.pop_before_local = copy.deepcopy(self.pop)
pop = Population(self.pop_size, individual=Individual())
pop.set("X", [self.global_best_y[0].X for _ in range(self.pop_size)])
pop.set("F", [self.global_best_y[1] for _ in range(self.pop_size)])
self.tmp_off = self.mutation.do(self.problem, pop)
self.local_best_y = [None, 10000]
self.local_gen = 0
normal = False
# not increasing cur_gen in this case
if normal:
with open('tmp_log.txt', 'a') as f_out:
f_out.write(str(self.cur_gen)+' normal'+'\n')
self.tmp_off, _ = self.mating.do(self.problem, self.pop, self.pop_size, algorithm=self)
self.cur_gen += 1
else:
# initialization
self.tmp_off = self.plain_initialization.do(self.problem, self.n_offsprings, algorithm=self)
self.cur_gen += 1
elif self.algorithm_name in ['random', 'grid']:
self.tmp_off = self.plain_initialization.do(self.problem, self.n_offsprings, algorithm=self)
else:
if self.algorithm_name == 'random-un':
self.tmp_off, parents = [], []
else:
print('len(self.pop)', len(self.pop))
# do the mating using the current population
if len(self.pop) > 0:
self.tmp_off, parents = self.mating.do(self.problem, self.pop, self.n_offsprings, algorithm=self)
print('\n'*3, 'after mating len 0', len(self.tmp_off), 'self.n_offsprings', self.n_offsprings, '\n'*3)
if len(self.tmp_off) < self.n_offsprings:
remaining_num = self.n_offsprings - len(self.tmp_off)
remaining_off = self.initialization.do(self.problem, remaining_num, algorithm=self)
remaining_parrents = remaining_off
if len(self.tmp_off) == 0:
self.tmp_off = remaining_off
parents = remaining_parrents
else:
self.tmp_off = Population.merge(self.tmp_off, remaining_off)
parents = Population.merge(parents, remaining_parrents)
print('\n'*3, 'unique after random generation len 1', len(self.tmp_off), '\n'*3)
self.tmp_off_type_1_len = len(self.tmp_off)
if len(self.tmp_off) < self.n_offsprings:
remaining_num = self.n_offsprings - len(self.tmp_off)
remaining_off = self.plain_initialization.do(self.problem, remaining_num, algorithm=self)
remaining_parrents = remaining_off
self.tmp_off = Population.merge(self.tmp_off, remaining_off)
parents = Population.merge(parents, remaining_parrents)
print('\n'*3, 'random generation len 2', len(self.tmp_off), '\n'*3)
# if the mating could not generate any new offspring (duplicate elimination might make that happen)
if len(self.tmp_off) == 0 or (not self.problem.call_from_dt and self.problem.fuzzing_arguments.finish_after_has_run and self.problem.has_run >= self.problem.fuzzing_arguments.has_run_num):
self.termination.force_termination = True
print("Mating cannot generate new springs, terminate earlier.")
print('self.tmp_off', len(self.tmp_off), self.tmp_off)
return
# if not the desired number of offspring could be created
elif len(self.tmp_off) < self.n_offsprings:
if self.verbose:
print("WARNING: Mating could not produce the required number of (unique) offsprings!")
# additional step to rank and select self.off after gathering initial population
if (self.rank_mode == 'none') or (self.rank_mode in ['nn', 'adv_nn'] and (len(self.problem.objectives_list) < self.initial_fit_th or np.sum(determine_y_upon_weights(self.problem.objectives_list, self.problem.objective_weights)) < self.min_bug_num_to_fit_dnn)) or (self.rank_mode in ['regression_nn'] and len(self.problem.objectives_list) < self.pop_size):
self.off = self.tmp_off[:self.pop_size]
else:
if self.rank_mode in ['regression_nn']:
# only consider collision case for now
from customized_utils import pretrain_regression_nets
if self.regression_nn_use_running_data:
initial_X = self.all_pop_run_X
initial_objectives_list = self.problem.objectives_list
cutoff = len(initial_X)
cutoff_end = cutoff
else:
subfolders = get_sorted_subfolders(self.warm_up_path)
initial_X, _, initial_objectives_list, _, _, _ = load_data(subfolders)
cutoff = self.warm_up_len
cutoff_end = self.warm_up_len + 100
if cutoff == 0:
cutoff = len(initial_X)
if cutoff_end > len(initial_X):
cutoff_end = len(initial_X)
clfs, confs, chosen_weights, standardize_prev = pretrain_regression_nets(initial_X, initial_objectives_list, self.problem.objective_weights, self.problem.xl, self.problem.xu, self.problem.labels, self.problem.customized_constraints, cutoff, cutoff_end, self.problem.fuzzing_content.keywords_dict, choose_weight_inds)
else:
standardize_prev = None
X_train_ori = self.all_pop_run_X
X_test_ori = self.tmp_off.get("X")
initial_X = np.concatenate([X_train_ori, X_test_ori])
cutoff = X_train_ori.shape[0]
cutoff_end = initial_X.shape[0]
partial = True
X_train, X_test, xl, xu, labels_used, standardize, one_hot_fields_len, param_for_recover_and_decode = process_X(initial_X, self.problem.labels, self.problem.xl, self.problem.xu, cutoff, cutoff_end, partial, len(self.problem.interested_unique_bugs), self.problem.fuzzing_content.keywords_dict, standardize_prev=standardize_prev)
(X_removed, kept_fields, removed_fields, enc, inds_to_encode, inds_non_encode, encoded_fields, _, _, unique_bugs_len) = param_for_recover_and_decode