mutation_executor.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. # -*-coding:UTF-8-*-
  2. import argparse
  3. import sys
  4. import os
  5. sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  6. sys.path.append("../")
  7. from scripts.logger.lemon_logger import Logger
  8. import warnings
  9. import datetime
  10. import configparser
  11. from scripts.tools import utils
  12. """Init cuda"""
  13. warnings.filterwarnings("ignore")
  14. os.environ["KERAS_BACKEND"] = "tensorflow"
  15. os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" # 只显示 warning 和 Error
  16. os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
  17. os.environ["CUDA_VISIBLE_DEVICES"] = ""
  18. """Setting random seed"""
  19. def lemon_process(exp, root_dir, output_dir, mutate_num, config_name):
  20. lemon_cfg = configparser.ConfigParser()
  21. cfg_path = os.path.join(root_dir, "config", config_name)
  22. print(cfg_path)
  23. lemon_cfg.read(cfg_path)
  24. parameters = lemon_cfg["parameters"]
  25. flags = argparse.Namespace(
  26. mutate_ops=parameters["mutate_ops"],
  27. exps=exp.lstrip().rstrip().split(" "),
  28. origin_model_dir=os.path.join(root_dir, parameters["origin_model_dir"]),
  29. output_dir=output_dir,
  30. backend=parameters["backend"],
  31. mutate_num=mutate_num,
  32. mutate_ratio=parameters.getfloat("mutate_ratio"),
  33. test_size=parameters.getint("test_size"),
  34. threshold=parameters.getfloat("threshold"),
  35. redis_db=lemon_cfg["parameters"].getint("redis_db"),
  36. python_prefix=parameters["python_prefix"].rstrip("/"),
  37. )
  38. if not os.path.exists(flags.output_dir):
  39. os.makedirs(flags.output_dir)
  40. main_log = Logger()
  41. """Lemon process"""
  42. main_log.logger.info("Success: Lemon start successfully!")
  43. start_time = datetime.datetime.now()
  44. for exp_identifier in flags.exps:
  45. """Make directory"""
  46. experiment_dir = os.path.join(
  47. flags.output_dir, exp_identifier
  48. ) # exp : like lenet5-mnist
  49. mut_dir = os.path.join(experiment_dir, "mut_model")
  50. crash_dir = os.path.join(experiment_dir, "crash")
  51. nan_dir = os.path.join(experiment_dir, "nan")
  52. inner_output_dir = os.path.join(experiment_dir, "inner_output")
  53. metrics_result_dir = os.path.join(experiment_dir, "metrics_result")
  54. print(experiment_dir)
  55. if not os.path.exists(experiment_dir):
  56. os.makedirs(experiment_dir)
  57. if not os.path.exists(mut_dir):
  58. os.makedirs(mut_dir)
  59. if not os.path.exists(crash_dir):
  60. os.makedirs(crash_dir)
  61. if not os.path.exists(nan_dir):
  62. os.makedirs(nan_dir)
  63. if not os.path.exists(inner_output_dir):
  64. os.makedirs(inner_output_dir)
  65. if not os.path.exists(metrics_result_dir):
  66. os.makedirs(metrics_result_dir)
  67. try:
  68. """Mutate and get output of different backends"""
  69. main_log.info("INFO:Lemon mutation starting!")
  70. main_log.info("INFO:Lemon for exp: {}".format(exp_identifier))
  71. if "svhn" in exp_identifier or "fashion2" in exp_identifier:
  72. origin_model_name = "{}_origin.hdf5".format(exp_identifier)
  73. else:
  74. origin_model_name = "{}_origin.h5".format(exp_identifier)
  75. origin_model_file = os.path.join(flags.origin_model_dir, origin_model_name)
  76. # print(os.getcwd())
  77. run_dir = os.path.join(root_dir, "run")
  78. mutate_lemon = (
  79. "cd {} && ".format(run_dir)+
  80. "{}/lemon/bin/python -u -m mutate_lemon --mutate_op {} --model {} --output_dir {}"
  81. " --backends {} --mutate_num {} --mutate_ratio {} --exp {} --test_size {} --redis_db {} --config_name {}".format(
  82. flags.python_prefix,
  83. flags.mutate_ops,
  84. origin_model_file,
  85. flags.output_dir,
  86. flags.backend,
  87. flags.mutate_num,
  88. flags.mutate_ratio,
  89. exp_identifier,
  90. flags.test_size,
  91. flags.redis_db,
  92. config_name,
  93. )
  94. )
  95. os.system(mutate_lemon)
  96. print(mutate_lemon)
  97. except Exception:
  98. main_log.error("Error: Lemon for exp:{} Failed!".format(exp_identifier))
  99. main_log.exception(sys.exc_info())
  100. end_time = datetime.datetime.now()
  101. time_delta = end_time - start_time
  102. h, m, s = utils.ToolUtils.get_HH_mm_ss(time_delta)
  103. main_log.info(
  104. "INFO:Lemon is done: Time used: {} hour,{} min,{} sec".format(h, m, s)
  105. )
  106. if __name__ == "__main__":
  107. # config_name = sys.argv[1]
  108. config_name = "demo.conf"
  109. parse = argparse.ArgumentParser()
  110. parse.add_argument(
  111. "--exp",
  112. type=str,
  113. choices=[
  114. "lexnet-cifar10",
  115. "lenet5-fashion-mnist",
  116. "fashion2",
  117. "svhn",
  118. "lenet5-mnist",
  119. "alexnet-cifar10",
  120. "mobilenet.1.00.224-imagenet",
  121. "vgg16-imagenet",
  122. ],
  123. help="experiments identifiers",
  124. )
  125. parse.add_argument("--root_dir", type=str, help="root dir")
  126. parse.add_argument(
  127. "--output_dir", type=str, help="relative path of output dir(from root dir)"
  128. )
  129. parse.add_argument(
  130. "--mutate_num",
  131. type=int,
  132. help="number of variant models generated by each mutation operator",
  133. )
  134. parse.add_argument("--config_name", type=str, help="config name,like demo.conf")
  135. flags_input, unparsed = parse.parse_known_args(sys.argv[1:])
  136. lemon_cfg = configparser.ConfigParser()
  137. cfg_path = os.path.join(flags_input.root_dir, "config", flags_input.config_name)
  138. print(cfg_path)
  139. lemon_cfg.read(cfg_path)
  140. parameters = lemon_cfg["parameters"]
  141. flags = argparse.Namespace(
  142. mutate_ops=parameters["mutate_ops"],
  143. exps=flags_input.exp.lstrip().rstrip().split(" "),
  144. origin_model_dir=os.path.join(
  145. flags_input.root_dir, parameters["origin_model_dir"]
  146. ),
  147. output_dir=flags_input.output_dir,
  148. backend=parameters["backend"],
  149. mutate_num=flags_input.mutate_num,
  150. mutate_ratio=parameters.getfloat("mutate_ratio"),
  151. test_size=parameters.getint("test_size"),
  152. threshold=parameters.getfloat("threshold"),
  153. redis_db=lemon_cfg["parameters"].getint("redis_db"),
  154. python_prefix=parameters["python_prefix"].rstrip("/"),
  155. )
  156. parse = argparse.ArgumentParser()
  157. if not os.path.exists(flags.output_dir):
  158. os.makedirs(flags.output_dir)
  159. main_log = Logger()
  160. """Lemon process"""
  161. main_log.logger.info("Success: Lemon start successfully!")
  162. start_time = datetime.datetime.now()
  163. for exp_identifier in flags.exps:
  164. """Make directory"""
  165. experiment_dir = os.path.join(
  166. flags.output_dir, exp_identifier
  167. ) # exp : like lenet5-mnist
  168. mut_dir = os.path.join(experiment_dir, "mut_model")
  169. crash_dir = os.path.join(experiment_dir, "crash")
  170. nan_dir = os.path.join(experiment_dir, "nan")
  171. inner_output_dir = os.path.join(experiment_dir, "inner_output")
  172. metrics_result_dir = os.path.join(experiment_dir, "metrics_result")
  173. print(experiment_dir)
  174. if not os.path.exists(experiment_dir):
  175. os.makedirs(experiment_dir)
  176. if not os.path.exists(mut_dir):
  177. os.makedirs(mut_dir)
  178. if not os.path.exists(crash_dir):
  179. os.makedirs(crash_dir)
  180. if not os.path.exists(nan_dir):
  181. os.makedirs(nan_dir)
  182. if not os.path.exists(inner_output_dir):
  183. os.makedirs(inner_output_dir)
  184. if not os.path.exists(metrics_result_dir):
  185. os.makedirs(metrics_result_dir)
  186. try:
  187. """Mutate and get output of different backends"""
  188. main_log.info("INFO:Lemon mutation starting!")
  189. main_log.info("INFO:Lemon for exp: {}".format(exp_identifier))
  190. if "svhn" in exp_identifier or "fashion2" in exp_identifier:
  191. origin_model_name = "{}_origin.hdf5".format(exp_identifier)
  192. else:
  193. origin_model_name = "{}_origin.h5".format(exp_identifier)
  194. origin_model_file = os.path.join(flags.origin_model_dir, origin_model_name)
  195. mutate_lemon = (
  196. "{}/lemon/bin/python -u -m mutate_lemon --mutate_op {} --model {} --output_dir {}"
  197. " --backends {} --mutate_num {} --mutate_ratio {} --exp {} --test_size {} --redis_db {} --config_name {}".format(
  198. flags.python_prefix,
  199. flags.mutate_ops,
  200. origin_model_file,
  201. flags.output_dir,
  202. flags.backend,
  203. flags.mutate_num,
  204. flags.mutate_ratio,
  205. exp_identifier,
  206. flags.test_size,
  207. flags.redis_db,
  208. config_name,
  209. )
  210. )
  211. os.system(mutate_lemon)
  212. print(mutate_lemon)
  213. except Exception:
  214. main_log.error("Error: Lemon for exp:{} Failed!".format(exp_identifier))
  215. main_log.exception(sys.exc_info())
  216. end_time = datetime.datetime.now()
  217. time_delta = end_time - start_time
  218. h, m, s = utils.ToolUtils.get_HH_mm_ss(time_delta)
  219. main_log.info(
  220. "INFO:Lemon is done: Time used: {} hour,{} min,{} sec".format(h, m, s)
  221. )