You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

profiling.py 27 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Profiling api file."""
  16. import os
  17. import re
  18. import stat
  19. import time
  20. import json
  21. from enum import Enum
  22. from mindspore import log as logger, context
  23. from mindspore.communication.management import release, get_rank
  24. from mindspore.profiler.common.exceptions.exceptions import ProfilerFileNotFoundException, \
  25. ProfilerIOException, ProfilerException, ProfilerRawFileException
  26. from mindspore.profiler.common.util import get_file_names, fwrite_format
  27. from mindspore.profiler.common.validator.validate_path import \
  28. validate_and_normalize_path
  29. from mindspore.profiler.parser.aicpu_data_parser import DataPreProcessParser
  30. from mindspore.profiler.parser.framework_parser import FrameworkParser
  31. from mindspore.profiler.parser.hwts_log_parser import HWTSLogParser
  32. from mindspore.profiler.parser.integrator import Integrator
  33. from mindspore.profiler.parser.integrator import GpuTimelineGenerator, AscendTimelineGenerator
  34. from mindspore.profiler.parser.memory_usage_parser import MemoryUsageParser
  35. from mindspore.profiler.parser.minddata_parser import MinddataParser
  36. from mindspore.profiler.parser.minddata_pipeline_parser import \
  37. MinddataPipelineParser
  38. from mindspore.profiler.parser.optime_parser import OPComputeTimeParser
  39. from mindspore.profiler.parser.step_trace_parser import GpuStepTraceParser, AscendStepTraceParser
  40. from mindspore.nn.cell import Cell
  41. INIT_OP_NAME = 'Default/InitDataSetQueue'
  42. class ProfileOption(Enum):
  43. """
  44. Profile Option Enum which be used in Profiler.profile.
  45. """
  46. trainable_parameters = 0
  47. class Profiler:
  48. """
  49. Performance profiling API.
  50. This API enables MindSpore users to profile the performance of neural network.
  51. Profiler supports Ascend and GPU, both of them are used in the same way,
  52. but only output_path in args works on GPU.
  53. Args:
  54. output_path (str): Output data path.
  55. optypes_not_deal (str): (Ascend only) Op type names, determine the data of which optype should be collected
  56. and analysed,will deal with all op if null; Different op types should be separated by comma.
  57. ascend_job_id (str): (Ascend only) The directory where the profiling files to be parsed are located;
  58. This parameter is used to support offline parsing.
  59. Examples:
  60. >>> from mindspore.profiler import Profiler
  61. >>> import mindspore.context
  62. >>> context.set_context(mode=context.GRAPH_MODE, device_target="Ascend",
  63. >>> device_id=int(os.environ["DEVICE_ID"]))
  64. >>> profiler = Profiler()
  65. >>> model = Model()
  66. >>> model.train()
  67. >>> profiler.analyse()
  68. """
  69. _hwts_output_filename_target = "output_format_data_hwts_"
  70. _opcompute_output_filename_target = "output_op_compute_time_"
  71. _aicpu_op_output_filename_target = "output_data_preprocess_aicpu_"
  72. def __init__(self, **kwargs):
  73. # get device_id and device_target
  74. self._get_devid_and_devtarget()
  75. self._get_output_path(kwargs)
  76. os.environ['PROFILING_MODE'] = 'true'
  77. os.environ['MINDDATA_PROFILING_DIR'] = self._output_path
  78. if self._device_target:
  79. from mindspore._c_expression import CPUProfiler
  80. self._cpu_profiler = CPUProfiler.get_instance()
  81. self._cpu_profiler.init(self._output_path)
  82. self._cpu_profiler.step_profiling_enable(True)
  83. if self._device_target and self._device_target == "GPU":
  84. from mindspore._c_expression import GPUProfiler
  85. self._gpu_profiler = GPUProfiler.get_instance()
  86. self._gpu_profiler.init(self._output_path)
  87. self._gpu_profiler.step_profiling_enable(True)
  88. if context.get_auto_parallel_context('device_num') > 1:
  89. self._dev_id = get_rank()
  90. os.environ['DEVICE_ID'] = str(self._dev_id)
  91. if kwargs:
  92. logger.warning("Params not be supported yet on GPU.")
  93. elif self._device_target and self._device_target == "Ascend":
  94. optypes_not_deal = kwargs.pop("optypes_not_deal", "Variable")
  95. if not isinstance(optypes_not_deal, str):
  96. raise TypeError("The parameter optypes_not_deal must be str.")
  97. job_dir = kwargs.pop("ascend_job_id", "")
  98. if job_dir:
  99. job_dir = validate_and_normalize_path(job_dir)
  100. if not os.path.exists(job_dir):
  101. msg = f"Invalid ascend_job_id: {job_dir}, Please pass the absolute path of the JOB dir"
  102. logger.error(msg)
  103. raise ValueError(msg)
  104. self._output_path, _ = os.path.split(job_dir)
  105. if kwargs:
  106. logger.warning("There are invalid params which don't work.")
  107. os.environ['DEVICE_ID'] = self._dev_id
  108. fp_point = os.environ.get("PROFILING_FP_START", "")
  109. bp_point = os.environ.get("PROFILING_BP_END", "")
  110. profiling_options = {
  111. "output": self._output_path,
  112. "fp_point": fp_point,
  113. "bp_point": bp_point,
  114. "training_trace": "on",
  115. "task_trace": "on",
  116. "aic_metrics": "PipeUtilization",
  117. "aicpu": "on"
  118. }
  119. profiling_options = json.dumps(profiling_options)
  120. # Characters longer than 2048 are ignored, resulting in profiling option resolution errors
  121. if len(profiling_options) > 2048:
  122. msg = "The parameter length exceeds the limit (2048), please input valid parameters."
  123. logger.error(msg)
  124. raise ValueError(msg)
  125. # use context interface to open profiling, for the new mindspore version(after 2020.5.21)
  126. context.set_context(enable_profiling=True, profiling_options=profiling_options)
  127. base_profiling_container_path = os.path.join(self._output_path, "container")
  128. container_path = os.path.join(base_profiling_container_path, self._dev_id)
  129. data_path = os.path.join(container_path, "data")
  130. data_path = validate_and_normalize_path(data_path)
  131. if not os.path.exists(data_path):
  132. os.makedirs(data_path, exist_ok=True)
  133. self._filt_optype_names = optypes_not_deal.split(",") if optypes_not_deal else []
  134. # add job id env through user input later
  135. self._job_id_env = 0
  136. self._start_time = int(time.time() * 10000000)
  137. logger.info("Profiling: profiling start time: %d", self._start_time)
  138. def analyse(self):
  139. """
  140. Collect and analyse performance data, called after training or during training.
  141. Examples:
  142. >>> from mindspore.profiler import Profiler
  143. >>> import mindspore.context
  144. >>> context.set_context(mode=context.GRAPH_MODE, device_target="Ascend",
  145. >>> device_id=int(os.environ["DEVICE_ID"]))
  146. >>> profiler = Profiler()
  147. >>> model = Model()
  148. >>> model.train()
  149. >>> profiler.analyse()
  150. """
  151. self._cpu_profiler.stop()
  152. if self._device_target and self._device_target == "GPU":
  153. self._gpu_analyse()
  154. elif self._device_target and self._device_target == "Ascend":
  155. self._ascend_analyse()
  156. def _ascend_analyse(self):
  157. """Collect and analyse ascend performance data"""
  158. release()
  159. job_id = self._get_profiling_job_id()
  160. logger.info("Profiling: job id is %s ", job_id)
  161. source_path = os.path.join(self._output_path, job_id)
  162. # parse hwts.log.data.45.dev file, and get task profiling data
  163. hwts_output_filename = self._hwts_output_filename_target + self._dev_id + ".txt"
  164. hwts_output_filename = os.path.join(self._output_path, hwts_output_filename)
  165. source_path = validate_and_normalize_path(source_path)
  166. hwts_output_filename = validate_and_normalize_path(hwts_output_filename)
  167. hwtslog_parser = HWTSLogParser(source_path, hwts_output_filename)
  168. hwtslog_parser.execute()
  169. # parse Framework file, and get the relation of op and tasks
  170. framework_parser = FrameworkParser(job_id, self._dev_id, self._output_path)
  171. framework_parser.parse()
  172. op_task_dict = framework_parser.to_task_id_full_op_name_dict()
  173. if not op_task_dict:
  174. logger.error("Profiling: fail to parse framework files.")
  175. return
  176. # get op compute time from hwts data and framework data, write output_op_compute_time.txt
  177. opcompute_output_filename = self._opcompute_output_filename_target + self._dev_id + ".txt"
  178. opcompute_output_filename = os.path.join(self._output_path, opcompute_output_filename)
  179. opcompute_output_filename = validate_and_normalize_path(opcompute_output_filename)
  180. optime_parser = OPComputeTimeParser(
  181. hwts_output_filename, opcompute_output_filename,
  182. op_task_dict, self._output_path, self._dev_id
  183. )
  184. optime_parser.execute()
  185. # parse DATA_PREPROCESS.dev.AICPU file, write output_data_preprocess_aicpu_x.txt
  186. output_data_preprocess_aicpu = self._aicpu_op_output_filename_target + self._dev_id + ".txt"
  187. output_data_preprocess_aicpu = os.path.join(self._output_path, output_data_preprocess_aicpu)
  188. output_data_preprocess_aicpu = validate_and_normalize_path(output_data_preprocess_aicpu)
  189. aicpu_data_parser = DataPreProcessParser(source_path, output_data_preprocess_aicpu)
  190. aicpu_data_parser.execute()
  191. # Parsing minddata AICPU profiling
  192. MinddataParser.execute(source_path, self._output_path, self._dev_id)
  193. # parse minddata pipeline operator and queue
  194. try:
  195. pipeline_parser = MinddataPipelineParser(self._output_path, self._dev_id, self._output_path)
  196. pipeline_parser.parse()
  197. except ProfilerException as err:
  198. logger.warning(err.message)
  199. # analyse op compute time info
  200. try:
  201. self._analyser_op_info()
  202. except ProfilerException as err:
  203. logger.warning(err.message)
  204. # analyse step trace info
  205. points = None
  206. try:
  207. points = self._analyse_step_trace(source_path, framework_parser)
  208. except ProfilerException as err:
  209. logger.warning(err.message)
  210. # analyse timeline info
  211. try:
  212. self._analyse_timeline(aicpu_data_parser, optime_parser, source_path)
  213. except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err:
  214. logger.warning('Fail to write timeline data: %s', err)
  215. # analyse memory usage info
  216. try:
  217. self._analyse_memory_usage(points)
  218. except (ProfilerIOException, ProfilerFileNotFoundException, ProfilerRawFileException) as err:
  219. logger.warning(err.message)
  220. os.environ['PROFILING_MODE'] = str("false")
  221. context.set_context(enable_profiling=False)
  222. def _gpu_analyse(self):
  223. """Collect and analyse gpu performance data"""
  224. if context.get_auto_parallel_context('device_num') > 1 and self._dev_id != get_rank():
  225. self._dev_id = get_rank()
  226. logger.error('Please check the Profiler object initialized after set_auto_parallel_context() '
  227. 'and init(). Profiler should be initialized after these code. ')
  228. self._gpu_profiler.stop()
  229. timeline_generator = self._generate_timeline()
  230. # parse minddata pipeline operator and queue for GPU
  231. try:
  232. pipeline_parser = MinddataPipelineParser(self._output_path, self._dev_id, self._output_path)
  233. pipeline_parser.parse()
  234. except ProfilerException as err:
  235. logger.warning(err.message)
  236. # analyse step trace info
  237. try:
  238. self._analyse_step_trace(is_training_mode_flag=timeline_generator.check_op_name('Gradients'))
  239. except ProfilerException as err:
  240. logger.warning(err.message)
  241. os.environ['PROFILING_MODE'] = str("false")
  242. logger.warning(
  243. '\nMemory Usage is not supported on GPU currently.\n'
  244. 'Please running on Ascend if you would like to see memory analysis, '
  245. 'otherwise, this warning can be ignored.'
  246. )
  247. def _analyse_step_trace(self, source_path=None, framework_parser=None, is_training_mode_flag=True):
  248. """
  249. Analyse step trace data and save the result.
  250. Args:
  251. source_path (str): The directory that contains the step trace original data.
  252. framework_parser (FrameworkParser): The framework parse instance.
  253. is_training_mode_flag (bool): Whether in training mode or not.
  254. """
  255. logger.info("Begin to parse step trace.")
  256. # construct output path
  257. step_trace_intermediate_file_path = os.path.join(
  258. self._output_path,
  259. f'step_trace_raw_{self._dev_id}_detail_time.csv'
  260. )
  261. point_info_file_path = os.path.join(
  262. self._output_path,
  263. 'step_trace_point_info.json'
  264. )
  265. step_trace_intermediate_file_path = validate_and_normalize_path(step_trace_intermediate_file_path)
  266. point_info_file_path = validate_and_normalize_path(point_info_file_path)
  267. if self._device_target and self._device_target == 'GPU':
  268. input_file_path = os.path.join(
  269. self._output_path,
  270. f'step_trace_profiling_{self._dev_id}.txt'
  271. )
  272. parser = GpuStepTraceParser(input_dir=input_file_path,
  273. output_file_path=step_trace_intermediate_file_path,
  274. is_training_mode=is_training_mode_flag)
  275. parser.parse_and_save()
  276. point_info = parser.record_point_info(input_file_path, point_info_file_path)
  277. else:
  278. # whether keep the first step
  279. skip_first_step_flag = framework_parser.check_op_name(INIT_OP_NAME)
  280. point_info = framework_parser.point_info
  281. # recognize inference or traning mode
  282. is_traning_mode_flag = framework_parser.check_op_name("Gradients")
  283. # parser the step trace files and save the result to disk
  284. source_path = validate_and_normalize_path(source_path)
  285. parser = AscendStepTraceParser(input_dir=source_path,
  286. output_file_path=step_trace_intermediate_file_path,
  287. job_id=self._job_id_env,
  288. skip_first_step=skip_first_step_flag,
  289. is_training_mode=is_traning_mode_flag)
  290. parser.update_tag_op_type_map(point_info)
  291. parser.parse_and_save()
  292. point_info = parser.record_point_info(point_info, point_info_file_path)
  293. # print parser result
  294. parser.show()
  295. logger.info("Finish saving the intermediate result: %s", step_trace_intermediate_file_path)
  296. logger.info("The point info is: %s", point_info)
  297. return point_info
  298. def _analyse_timeline(self, aicpu_parser, optime_parser, source_path):
  299. """
  300. Analyse and parse timeline info.
  301. Args:
  302. aicpu_parser (DataPreProcessParser): The parser instance for AI CPU operator
  303. execution time calculation.
  304. optime_parser (OPComputeTimeParserParser): The parser instance for AI Core
  305. operator execution time calculation.
  306. """
  307. timeline_analyser = AscendTimelineGenerator(self._output_path, self._dev_id)
  308. # Get framework info
  309. integrator = Integrator(self._output_path, self._dev_id)
  310. aicore_detail_data = integrator.get_aicore_detail_data()
  311. aicore_detail_data_size = len(aicore_detail_data)
  312. col_names = ['op_name', 'op_type', 'avg_execution_time', 'subgraph',
  313. 'full_op_name', 'op_info']
  314. framework_info = {
  315. 'col_name': col_names,
  316. 'object': aicore_detail_data,
  317. 'size': aicore_detail_data_size
  318. }
  319. all_reduce_info = integrator.query_for_all_reduce()
  320. # Get timeline info
  321. logger.info('Start writing timeline info...')
  322. logger.info('Warm Prompt: It could take a few minutes if you are training '
  323. 'with a complex network or more than 10 steps.')
  324. # Add info into timeline, such as AI CPU, AllReduce, framework info.
  325. aicpu_info = aicpu_parser.query_aicpu_data()
  326. min_cycle_counter = min(aicpu_parser.min_cycle_counter, optime_parser.min_cycle_counter)
  327. timeline_analyser.init_timeline(all_reduce_info, framework_info, aicpu_info,
  328. min_cycle_counter, source_path)
  329. size_limit = 20 * 1024 * 1024 # 20MB
  330. timeline_analyser.write_timeline(size_limit)
  331. timeline_analyser.write_timeline_summary()
  332. def _generate_timeline(self):
  333. """Used for gpu, generate timeline info, write to json format file."""
  334. try:
  335. size_limit = 100 * 1024 * 1024 # 100MB
  336. timeline_generator = GpuTimelineGenerator(self._output_path, self._dev_id)
  337. timeline_generator.init_timeline()
  338. timeline_generator.write_timeline(size_limit)
  339. timeline_generator.write_timeline_summary()
  340. return timeline_generator
  341. except (ProfilerIOException, ProfilerFileNotFoundException, RuntimeError) as err:
  342. logger.warning('Fail to write timeline data: %s', err)
  343. raise RuntimeError('Fail to write timeline data.')
  344. def _analyse_memory_usage(self, points):
  345. """Analyse memory usage data."""
  346. integrator = Integrator(self._output_path, self._dev_id)
  347. aicore_detail_data = integrator.get_aicore_detail_data()
  348. memory_parser = MemoryUsageParser(self._output_path, self._dev_id)
  349. memory_parser.init_memory_usage_info(aicore_detail_data, points)
  350. memory_parser.write_memory_files()
  351. def _get_profiling_job_id(self):
  352. """Get profiling job id, which was generated by ada service.
  353. Returns:
  354. str, profiling job id.
  355. """
  356. job_id = ""
  357. for item in os.listdir(self._output_path):
  358. if item.startswith('JOB'):
  359. path = os.path.join(self._output_path, item)
  360. log_file = get_file_names(path, "host_start.log")
  361. if not log_file:
  362. logger.error("Profiling: job path %s, host_start.log not exist.", path)
  363. break
  364. log_file = os.path.join(path, log_file[0])
  365. item_dict = self._parse_host_start_log(log_file)
  366. if not item_dict:
  367. logger.error("Profiling: job path %s, fail to get job start info.", path)
  368. break
  369. job_id = item
  370. if self._dev_id != item_dict["device_id"]:
  371. logger.info("Profiling: job path %s, dev id %s, training device id %s.",
  372. path, item_dict["device_id"], self._dev_id)
  373. if self._start_time > int(item_dict["start_time"]):
  374. logger.info("Profiling: job path %s, start_time %s, training start_time %d.",
  375. path, item_dict["start_time"], self._start_time)
  376. break
  377. if not job_id:
  378. msg = "Fail to get profiling job, please check whether job dir was generated"
  379. raise RuntimeError(msg)
  380. return job_id
  381. def _parse_host_start_log(self, input_file):
  382. """
  383. Parse host start log file, get the device id and start time of the job.
  384. Args:
  385. input_file (str): The file path of the host start log file.
  386. Returns:
  387. dict, job start time and device id.
  388. """
  389. item_dict = {}
  390. for line in open(input_file):
  391. if "Device" in line:
  392. item_dict["device_id"] = line[7:len(line)-2]
  393. elif "clock_realtime" in line:
  394. item_dict["start_time"] = line[16:len(line)-3]
  395. return item_dict
  396. def _analyser_op_info(self):
  397. """Analyse the operator information."""
  398. integrator = Integrator(self._output_path, self._dev_id)
  399. integrator.integrate()
  400. aicore_type_result = self._query_op_type_info()
  401. detail_file_path = os.path.join(
  402. self._output_path,
  403. 'output_op_compute_time_detail_{}.txt'.format(self._dev_id)
  404. )
  405. fwrite_format(detail_file_path, data_source='title:op compute time')
  406. display_names = [
  407. 'optype_name', 'compute_time(ms, per-step)',
  408. 'called_times(per-step)', 'percent'
  409. ]
  410. fwrite_format(detail_file_path, data_source=" ".join(display_names), is_print=True)
  411. fwrite_format(detail_file_path, data_source=aicore_type_result, is_print=True)
  412. op_type_order = [item[0] for item in aicore_type_result]
  413. aicore_detail_result = self._query_op_detail_info(op_type_order)
  414. fwrite_format(detail_file_path, data_source='', is_print=True)
  415. fwrite_format(detail_file_path, data_source='Detail:', is_print=True)
  416. fwrite_format(detail_file_path, data_source=" ".join(aicore_detail_result.get('col_name_detail')),
  417. is_print=True)
  418. fwrite_format(detail_file_path, data_source=aicore_detail_result.get('object'), is_print=True)
  419. def _query_op_type_info(self):
  420. """
  421. Query AICORE operator type information.
  422. Returns:
  423. list[list], the AICORE operator type and execution time information.
  424. """
  425. integrator = Integrator(self._output_path, self._dev_id)
  426. return integrator.get_aicore_data()
  427. def _query_op_detail_info(self, op_type_order):
  428. """
  429. Query AICORE operator detail information.
  430. Args:
  431. op_type_order(list): The name of the op type in order.
  432. Returns:
  433. dict, the AICORE operator detail information.
  434. """
  435. op_type_condition = {}
  436. if self._filt_optype_names:
  437. op_type_condition['not_in'] = self._filt_optype_names
  438. filter_condition = {
  439. 'op_type': op_type_condition,
  440. 'is_display_detail': False,
  441. }
  442. integrator = Integrator(self._output_path, self._dev_id)
  443. return integrator.query_and_sort_by_op_type(filter_condition, op_type_order)
  444. def _get_devid_and_devtarget(self):
  445. """Get device id and target of this training."""
  446. device_target = ""
  447. dev_id = ""
  448. try:
  449. dev_id = str(context.get_context("device_id"))
  450. device_target = context.get_context("device_target")
  451. except ValueError as err:
  452. logger.error("Profiling: fail to get context, %s", err)
  453. if not dev_id or not dev_id.isdigit():
  454. dev_id = os.getenv('DEVICE_ID')
  455. if not dev_id or not dev_id.isdigit():
  456. dev_id = "0"
  457. logger.error("Fail to get DEVICE_ID, use 0 instead.")
  458. if device_target and device_target not in ["Ascend", "GPU"]:
  459. msg = "Profiling: unsupported backend: %s" % device_target
  460. raise RuntimeError(msg)
  461. self._dev_id = dev_id
  462. self._device_target = device_target
  463. def _get_output_path(self, kwargs):
  464. """Get output path of profiling data."""
  465. current_time = int(time.time())
  466. # to avoid getting different timestamp from different process in multi-card training,
  467. # set the timestamp as exist timestamp if it's difference is less than 6 seconds.
  468. def _select_timestamp(dir_name, re_pattern, input_time):
  469. """select the timestamp from current_time and exist timestamp."""
  470. timestamp_diff_threshold = 6
  471. exist_timestamp_list = []
  472. select_time = input_time
  473. if not os.path.exists(dir_name):
  474. os.makedirs(dir_name, exist_ok=True)
  475. for file_name in os.listdir(dir_name):
  476. match_res = re_pattern.match(file_name)
  477. if match_res:
  478. exist_timestamp_list.append(int(match_res.group(1)))
  479. if exist_timestamp_list:
  480. time_diff_list = [input_time - timestamp for timestamp in exist_timestamp_list]
  481. min_time_diff = min(time_diff_list)
  482. if min_time_diff <= timestamp_diff_threshold:
  483. select_time = exist_timestamp_list[time_diff_list.index(min_time_diff)]
  484. return select_time
  485. if "output_path" not in kwargs:
  486. selected_timestamp = _select_timestamp(os.getcwd(), re.compile(r'data-(\d+)'), current_time)
  487. output_path = f"data-{selected_timestamp}"
  488. self._output_path = validate_and_normalize_path(output_path)
  489. else:
  490. output_path = kwargs.pop("output_path")
  491. self._output_path = validate_and_normalize_path(output_path)
  492. selected_timestamp = _select_timestamp(self._output_path,
  493. re.compile(r'profiler-(\d+)'), current_time)
  494. self._output_path = os.path.join(self._output_path, f"profiler-{selected_timestamp}")
  495. if not os.path.exists(self._output_path):
  496. os.makedirs(self._output_path, exist_ok=True)
  497. os.chmod(self._output_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
  498. else:
  499. logger.warning("The target dir already exists. "
  500. "There may be some old profiling data, and they will be rewrote in the end.")
  501. @staticmethod
  502. def profile(network=None, profile_option=None):
  503. """
  504. Get the number of trainable parameters in the training network.
  505. Args:
  506. network (Cell): The training network.
  507. profile_option (ProfileOption): The profile option.
  508. Returns:
  509. dict, the key is the option name, the value is the result of option.
  510. """
  511. result = dict()
  512. if not profile_option:
  513. raise ValueError("The parameter profile_option must pass a value using ProfileOption.")
  514. if profile_option == ProfileOption.trainable_parameters:
  515. if not isinstance(network, Cell):
  516. msg = "Profiling: The network should be an object of nn.Cell"
  517. raise ValueError(msg)
  518. param_nums = len(network.parameters_dict())
  519. result = {"trainable_parameters": param_nums}
  520. else:
  521. raise ValueError("Wrong options.")
  522. return result