mutation_executor.py 8.9 KB

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