mutation_executor.py 9.0 KB

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