mindspore 2.4.1__cp311-cp311-win_amd64.whl → 2.5.0__cp311-cp311-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of mindspore might be problematic. Click here for more details.

Files changed (395) hide show
  1. mindspore/.commit_id +1 -1
  2. mindspore/Microsoft.VisualStudio.Telemetry.dll +0 -0
  3. mindspore/Newtonsoft.Json.dll +0 -0
  4. mindspore/__init__.py +8 -3
  5. mindspore/_c_dataengine.cp311-win_amd64.pyd +0 -0
  6. mindspore/_c_expression.cp311-win_amd64.pyd +0 -0
  7. mindspore/_c_mindrecord.cp311-win_amd64.pyd +0 -0
  8. mindspore/_checkparam.py +0 -5
  9. mindspore/_extends/parallel_compile/akg_compiler/gen_custom_op_files.py +1 -1
  10. mindspore/_extends/parse/compile_config.py +64 -0
  11. mindspore/_extends/parse/deprecated/__init__.py +0 -0
  12. mindspore/_extends/parse/deprecated/deprecated_tensor_method.py +375 -0
  13. mindspore/_extends/parse/parser.py +23 -5
  14. mindspore/_extends/parse/standard_method.py +123 -27
  15. mindspore/_extends/pijit/pijit_func_white_list.py +1 -1
  16. mindspore/amp.py +7 -1
  17. mindspore/atlprov.dll +0 -0
  18. mindspore/avcodec-59.dll +0 -0
  19. mindspore/avdevice-59.dll +0 -0
  20. mindspore/avfilter-8.dll +0 -0
  21. mindspore/avformat-59.dll +0 -0
  22. mindspore/avutil-57.dll +0 -0
  23. mindspore/boost/boost_cell_wrapper.py +136 -41
  24. mindspore/c1.dll +0 -0
  25. mindspore/c1xx.dll +0 -0
  26. mindspore/c2.dll +0 -0
  27. mindspore/common/__init__.py +3 -1
  28. mindspore/common/_register_for_tensor.py +0 -1
  29. mindspore/common/_stub_tensor.py +25 -4
  30. mindspore/common/_tensor_cpp_method.py +17 -0
  31. mindspore/common/_tensor_docs.py +6132 -0
  32. mindspore/common/api.py +99 -25
  33. mindspore/common/dtype.py +34 -34
  34. mindspore/common/dump.py +2 -1
  35. mindspore/common/file_system.py +8 -1
  36. mindspore/common/generator.py +2 -0
  37. mindspore/common/hook_handle.py +3 -1
  38. mindspore/common/initializer.py +3 -4
  39. mindspore/common/lazy_inline.py +8 -2
  40. mindspore/common/mindir_util.py +10 -2
  41. mindspore/common/parameter.py +30 -27
  42. mindspore/common/tensor.py +713 -1337
  43. mindspore/communication/__init__.py +1 -1
  44. mindspore/communication/_comm_helper.py +10 -0
  45. mindspore/communication/comm_func.py +215 -173
  46. mindspore/communication/management.py +23 -20
  47. mindspore/context.py +292 -193
  48. mindspore/dataset/__init__.py +23 -19
  49. mindspore/dataset/callback/ds_callback.py +2 -1
  50. mindspore/dataset/core/config.py +84 -3
  51. mindspore/dataset/engine/cache_admin.py +3 -3
  52. mindspore/dataset/engine/cache_client.py +5 -4
  53. mindspore/dataset/engine/datasets.py +192 -149
  54. mindspore/dataset/engine/datasets_audio.py +14 -0
  55. mindspore/dataset/engine/datasets_standard_format.py +28 -11
  56. mindspore/dataset/engine/datasets_text.py +38 -1
  57. mindspore/dataset/engine/datasets_user_defined.py +125 -65
  58. mindspore/dataset/engine/datasets_vision.py +81 -8
  59. mindspore/dataset/engine/iterators.py +281 -63
  60. mindspore/dataset/engine/obs/util.py +8 -0
  61. mindspore/dataset/engine/queue.py +40 -0
  62. mindspore/dataset/engine/samplers.py +26 -2
  63. mindspore/dataset/engine/serializer_deserializer.py +1 -1
  64. mindspore/dataset/engine/validators.py +43 -11
  65. mindspore/dataset/transforms/py_transforms_util.py +17 -0
  66. mindspore/dataset/transforms/transforms.py +29 -12
  67. mindspore/dataset/vision/validators.py +1 -2
  68. mindspore/device_context/__init__.py +21 -0
  69. mindspore/device_context/ascend/__init__.py +25 -0
  70. mindspore/device_context/ascend/device.py +72 -0
  71. mindspore/device_context/ascend/op_debug.py +94 -0
  72. mindspore/device_context/ascend/op_precision.py +193 -0
  73. mindspore/device_context/ascend/op_tuning.py +127 -0
  74. mindspore/device_context/cpu/__init__.py +25 -0
  75. mindspore/device_context/cpu/device.py +62 -0
  76. mindspore/device_context/cpu/op_tuning.py +43 -0
  77. mindspore/device_context/gpu/__init__.py +21 -0
  78. mindspore/device_context/gpu/device.py +70 -0
  79. mindspore/device_context/gpu/op_precision.py +67 -0
  80. mindspore/device_context/gpu/op_tuning.py +175 -0
  81. mindspore/device_manager.py +134 -0
  82. mindspore/dnnl.dll +0 -0
  83. mindspore/dpcmi.dll +0 -0
  84. mindspore/experimental/llm_boost/__init__.py +3 -2
  85. mindspore/experimental/llm_boost/ascend_native/__init__.py +22 -0
  86. mindspore/experimental/llm_boost/ascend_native/llama_boost_ascend_native.py +211 -0
  87. mindspore/experimental/llm_boost/ascend_native/llm_boost.py +52 -0
  88. mindspore/experimental/llm_boost/atb/boost_base.py +239 -64
  89. mindspore/experimental/llm_boost/atb/llama_boost.py +52 -30
  90. mindspore/experimental/llm_boost/atb/qwen_boost.py +47 -24
  91. mindspore/experimental/llm_boost/register.py +1 -0
  92. mindspore/experimental/optim/adadelta.py +26 -22
  93. mindspore/experimental/optim/adam.py +3 -0
  94. mindspore/experimental/optim/lr_scheduler.py +33 -24
  95. mindspore/experimental/optim/radam.py +33 -30
  96. mindspore/hal/device.py +28 -0
  97. mindspore/hal/event.py +17 -0
  98. mindspore/hal/memory.py +94 -3
  99. mindspore/hal/stream.py +91 -6
  100. mindspore/include/api/context.h +1 -2
  101. mindspore/include/dataset/constants.h +2 -2
  102. mindspore/jpeg62.dll +0 -0
  103. mindspore/log.py +12 -0
  104. mindspore/mindrecord/__init__.py +1 -1
  105. mindspore/mindrecord/config.py +17 -316
  106. mindspore/mindrecord/filereader.py +1 -9
  107. mindspore/mindrecord/filewriter.py +5 -15
  108. mindspore/mindrecord/mindpage.py +1 -9
  109. mindspore/mindspore_backend.dll +0 -0
  110. mindspore/mindspore_common.dll +0 -0
  111. mindspore/mindspore_core.dll +0 -0
  112. mindspore/mindspore_glog.dll +0 -0
  113. mindspore/mindspore_ops.dll +0 -0
  114. mindspore/mint/__init__.py +824 -218
  115. mindspore/mint/distributed/__init__.py +66 -4
  116. mindspore/mint/distributed/distributed.py +2594 -44
  117. mindspore/mint/linalg/__init__.py +6 -0
  118. mindspore/mint/nn/__init__.py +473 -14
  119. mindspore/mint/nn/functional.py +486 -11
  120. mindspore/mint/nn/layer/__init__.py +17 -4
  121. mindspore/mint/nn/layer/_functions.py +330 -0
  122. mindspore/mint/nn/layer/activation.py +169 -1
  123. mindspore/mint/nn/layer/basic.py +123 -0
  124. mindspore/mint/nn/layer/conv.py +727 -0
  125. mindspore/mint/nn/layer/normalization.py +215 -19
  126. mindspore/mint/nn/layer/padding.py +797 -0
  127. mindspore/mint/nn/layer/pooling.py +170 -0
  128. mindspore/mint/optim/__init__.py +2 -1
  129. mindspore/mint/optim/adam.py +223 -0
  130. mindspore/mint/optim/adamw.py +26 -19
  131. mindspore/mint/special/__init__.py +2 -1
  132. mindspore/msobj140.dll +0 -0
  133. mindspore/mspdb140.dll +0 -0
  134. mindspore/mspdbcore.dll +0 -0
  135. mindspore/mspdbst.dll +0 -0
  136. mindspore/mspft140.dll +0 -0
  137. mindspore/msvcdis140.dll +0 -0
  138. mindspore/msvcp140_1.dll +0 -0
  139. mindspore/msvcp140_2.dll +0 -0
  140. mindspore/msvcp140_atomic_wait.dll +0 -0
  141. mindspore/msvcp140_codecvt_ids.dll +0 -0
  142. mindspore/multiprocessing/__init__.py +5 -0
  143. mindspore/nn/__init__.py +2 -0
  144. mindspore/nn/cell.py +142 -21
  145. mindspore/nn/dynamic_lr.py +2 -1
  146. mindspore/nn/layer/activation.py +6 -6
  147. mindspore/nn/layer/basic.py +35 -25
  148. mindspore/nn/layer/channel_shuffle.py +3 -3
  149. mindspore/nn/layer/conv.py +3 -0
  150. mindspore/nn/layer/embedding.py +3 -3
  151. mindspore/nn/layer/normalization.py +8 -7
  152. mindspore/nn/layer/padding.py +4 -3
  153. mindspore/nn/layer/pooling.py +55 -23
  154. mindspore/nn/layer/rnn_cells.py +1 -1
  155. mindspore/nn/layer/rnns.py +2 -1
  156. mindspore/nn/layer/timedistributed.py +5 -5
  157. mindspore/nn/layer/transformer.py +48 -26
  158. mindspore/nn/learning_rate_schedule.py +5 -3
  159. mindspore/nn/loss/loss.py +31 -36
  160. mindspore/nn/optim/ada_grad.py +1 -0
  161. mindspore/nn/optim/adadelta.py +2 -2
  162. mindspore/nn/optim/adam.py +1 -1
  163. mindspore/nn/optim/lars.py +1 -4
  164. mindspore/nn/optim/optimizer.py +1 -1
  165. mindspore/nn/optim/rprop.py +2 -2
  166. mindspore/nn/optim/thor.py +2 -1
  167. mindspore/nn/utils/__init__.py +22 -0
  168. mindspore/nn/utils/init.py +73 -0
  169. mindspore/nn/wrap/cell_wrapper.py +4 -6
  170. mindspore/nn/wrap/loss_scale.py +3 -4
  171. mindspore/numpy/array_creations.py +60 -62
  172. mindspore/numpy/array_ops.py +148 -143
  173. mindspore/numpy/logic_ops.py +41 -42
  174. mindspore/numpy/math_ops.py +361 -359
  175. mindspore/numpy/utils.py +16 -16
  176. mindspore/numpy/utils_const.py +4 -4
  177. mindspore/opencv_core452.dll +0 -0
  178. mindspore/opencv_imgcodecs452.dll +0 -0
  179. mindspore/opencv_imgproc452.dll +0 -0
  180. mindspore/ops/__init__.py +2 -1
  181. mindspore/ops/_grad_experimental/grad_comm_ops.py +107 -8
  182. mindspore/ops/_grad_experimental/grad_debug_ops.py +6 -1
  183. mindspore/ops/_grad_experimental/grad_inner_ops.py +9 -0
  184. mindspore/ops/_grad_experimental/grad_math_ops.py +2 -1
  185. mindspore/ops/_op_impl/cpu/__init__.py +1 -0
  186. mindspore/ops/_op_impl/cpu/raise_op.py +28 -0
  187. mindspore/ops/_vmap/vmap_array_ops.py +20 -19
  188. mindspore/ops/_vmap/vmap_base.py +0 -2
  189. mindspore/ops/_vmap/vmap_grad_nn_ops.py +19 -13
  190. mindspore/ops/_vmap/vmap_math_ops.py +11 -9
  191. mindspore/ops/_vmap/vmap_nn_ops.py +20 -34
  192. mindspore/ops/auto_generate/cpp_create_prim_instance_helper.py +149 -12
  193. mindspore/ops/auto_generate/gen_arg_handler.py +0 -61
  194. mindspore/ops/auto_generate/gen_extend_func.py +554 -60
  195. mindspore/ops/auto_generate/gen_ops_def.py +1621 -115
  196. mindspore/ops/auto_generate/gen_ops_prim.py +8027 -3411
  197. mindspore/ops/auto_generate/pyboost_inner_prim.py +183 -79
  198. mindspore/ops/composite/base.py +1 -1
  199. mindspore/ops/composite/multitype_ops/_compile_utils.py +229 -30
  200. mindspore/ops/composite/multitype_ops/pow_impl.py +0 -29
  201. mindspore/ops/function/__init__.py +12 -0
  202. mindspore/ops/function/array_func.py +561 -159
  203. mindspore/ops/function/clip_func.py +64 -0
  204. mindspore/ops/function/debug_func.py +28 -20
  205. mindspore/ops/function/image_func.py +1 -1
  206. mindspore/ops/function/linalg_func.py +5 -4
  207. mindspore/ops/function/math_func.py +1664 -294
  208. mindspore/ops/function/nn_func.py +988 -317
  209. mindspore/ops/function/parameter_func.py +3 -56
  210. mindspore/ops/function/random_func.py +243 -33
  211. mindspore/ops/function/sparse_unary_func.py +1 -1
  212. mindspore/ops/functional.py +18 -5
  213. mindspore/ops/functional_overload.py +897 -0
  214. mindspore/ops/operations/__init__.py +3 -2
  215. mindspore/ops/operations/_embedding_cache_ops.py +4 -4
  216. mindspore/ops/operations/_grad_ops.py +2 -34
  217. mindspore/ops/operations/_infer_ops.py +2 -1
  218. mindspore/ops/operations/_inner_ops.py +38 -8
  219. mindspore/ops/operations/array_ops.py +45 -303
  220. mindspore/ops/operations/comm_ops.py +23 -17
  221. mindspore/ops/operations/custom_ops.py +7 -49
  222. mindspore/ops/operations/debug_ops.py +42 -47
  223. mindspore/ops/operations/inner_ops.py +6 -4
  224. mindspore/ops/operations/linalg_ops.py +3 -2
  225. mindspore/ops/operations/manually_defined/ops_def.py +185 -104
  226. mindspore/ops/operations/math_ops.py +11 -216
  227. mindspore/ops/operations/nn_ops.py +153 -310
  228. mindspore/ops/primitive.py +23 -21
  229. mindspore/ops/tensor_method.py +1669 -0
  230. mindspore/ops_generate/aclnn_kernel_register_auto_cc_generator.py +110 -0
  231. mindspore/ops_generate/add_tensor_docs_generator.py +54 -0
  232. mindspore/ops_generate/arg_handler.py +0 -61
  233. mindspore/ops_generate/auto_grad_impl_cc_generator.py +135 -0
  234. mindspore/ops_generate/auto_grad_reg_cc_generator.py +93 -0
  235. mindspore/ops_generate/base_generator.py +11 -0
  236. mindspore/ops_generate/cpp_create_prim_instance_helper_generator.py +108 -0
  237. mindspore/ops_generate/functional_map_cpp_generator.py +491 -0
  238. mindspore/ops_generate/functional_overload_py_generator.py +110 -0
  239. mindspore/ops_generate/functions_cc_generator.py +233 -0
  240. mindspore/ops_generate/gen_aclnn_implement.py +110 -114
  241. mindspore/ops_generate/gen_constants.py +157 -3
  242. mindspore/ops_generate/gen_ops.py +245 -990
  243. mindspore/ops_generate/gen_pyboost_func.py +97 -998
  244. mindspore/ops_generate/gen_utils.py +119 -33
  245. mindspore/ops_generate/lite_ops_cpp_generator.py +155 -0
  246. mindspore/ops_generate/op_api_proto.py +206 -0
  247. mindspore/ops_generate/op_def_py_generator.py +131 -0
  248. mindspore/ops_generate/op_prim_py_generator.py +480 -0
  249. mindspore/ops_generate/op_proto.py +373 -108
  250. mindspore/ops_generate/op_template_parser.py +436 -0
  251. mindspore/ops_generate/ops_def_cc_generator.py +288 -0
  252. mindspore/ops_generate/ops_def_h_generator.py +74 -0
  253. mindspore/ops_generate/ops_name_h_generator.py +68 -0
  254. mindspore/ops_generate/ops_primitive_h_generator.py +81 -0
  255. mindspore/ops_generate/pyboost_functions_cpp_generator.py +370 -0
  256. mindspore/ops_generate/pyboost_functions_h_generator.py +68 -0
  257. mindspore/ops_generate/pyboost_functions_py_generator.py +148 -0
  258. mindspore/ops_generate/pyboost_grad_function_cpp_generator.py +154 -0
  259. mindspore/ops_generate/pyboost_inner_prim_generator.py +131 -0
  260. mindspore/ops_generate/pyboost_native_grad_functions_generator.py +268 -0
  261. mindspore/ops_generate/pyboost_op_cpp_code_generator.py +851 -0
  262. mindspore/ops_generate/pyboost_overload_functions_cpp_generator.py +344 -0
  263. mindspore/ops_generate/pyboost_utils.py +92 -33
  264. mindspore/ops_generate/template.py +294 -44
  265. mindspore/ops_generate/tensor_func_reg_cpp_generator.py +422 -0
  266. mindspore/parallel/__init__.py +3 -3
  267. mindspore/parallel/_auto_parallel_context.py +44 -34
  268. mindspore/parallel/_cell_wrapper.py +22 -3
  269. mindspore/parallel/_parallel_serialization.py +13 -2
  270. mindspore/parallel/_utils.py +4 -2
  271. mindspore/parallel/algo_parameter_config.py +1 -1
  272. mindspore/parallel/checkpoint_transform.py +44 -0
  273. mindspore/parallel/cluster/process_entity/_api.py +131 -37
  274. mindspore/parallel/cluster/process_entity/_utils.py +41 -6
  275. mindspore/parallel/cluster/run.py +20 -3
  276. mindspore/parallel/parameter_broadcast.py +1 -1
  277. mindspore/parallel/shard.py +3 -0
  278. mindspore/parallel/transform_safetensors.py +119 -253
  279. mindspore/pgodb140.dll +0 -0
  280. mindspore/pgort140.dll +0 -0
  281. mindspore/profiler/__init__.py +17 -4
  282. mindspore/profiler/analysis/__init__.py +0 -0
  283. mindspore/profiler/analysis/parser/__init__.py +0 -0
  284. mindspore/profiler/analysis/parser/ascend_cann_parser.py +166 -0
  285. mindspore/profiler/analysis/parser/base_parser.py +158 -0
  286. mindspore/profiler/analysis/parser/framework_cann_relation_parser.py +45 -0
  287. mindspore/profiler/analysis/parser/ms_framework_parser.py +142 -0
  288. mindspore/profiler/analysis/parser/ms_minddata_parser.py +145 -0
  289. mindspore/profiler/analysis/parser/timeline_assembly_factory/__init__.py +0 -0
  290. mindspore/profiler/analysis/parser/timeline_assembly_factory/ascend_timeline_assembler.py +261 -0
  291. mindspore/profiler/analysis/parser/timeline_assembly_factory/base_timeline_assembler.py +40 -0
  292. mindspore/profiler/analysis/parser/timeline_assembly_factory/trace_view_container.py +84 -0
  293. mindspore/profiler/analysis/parser/timeline_creator/__init__.py +0 -0
  294. mindspore/profiler/analysis/parser/timeline_creator/base_timeline_creator.py +44 -0
  295. mindspore/profiler/analysis/parser/timeline_creator/cpu_op_timeline_creator.py +90 -0
  296. mindspore/profiler/analysis/parser/timeline_creator/fwk_timeline_creator.py +76 -0
  297. mindspore/profiler/analysis/parser/timeline_creator/msprof_timeline_creator.py +103 -0
  298. mindspore/profiler/analysis/parser/timeline_creator/scope_layer_timeline_creator.py +134 -0
  299. mindspore/profiler/analysis/parser/timeline_event/__init__.py +0 -0
  300. mindspore/profiler/analysis/parser/timeline_event/base_event.py +233 -0
  301. mindspore/profiler/analysis/parser/timeline_event/cpu_op_event.py +47 -0
  302. mindspore/profiler/analysis/parser/timeline_event/flow_event.py +36 -0
  303. mindspore/profiler/analysis/parser/timeline_event/fwk_event.py +260 -0
  304. mindspore/profiler/analysis/parser/timeline_event/msprof_event.py +73 -0
  305. mindspore/profiler/analysis/parser/timeline_event/scope_layer_event.py +53 -0
  306. mindspore/profiler/analysis/parser/timeline_event/timeline_event_pool.py +146 -0
  307. mindspore/profiler/analysis/task_manager.py +131 -0
  308. mindspore/profiler/analysis/time_converter.py +84 -0
  309. mindspore/profiler/analysis/viewer/__init__.py +0 -0
  310. mindspore/profiler/analysis/viewer/ascend_communication_viewer.py +333 -0
  311. mindspore/profiler/analysis/viewer/ascend_integrate_viewer.py +87 -0
  312. mindspore/profiler/analysis/viewer/ascend_kernel_details_viewer.py +252 -0
  313. mindspore/profiler/analysis/viewer/ascend_memory_viewer.py +313 -0
  314. mindspore/profiler/analysis/viewer/ascend_op_memory_viewer.py +322 -0
  315. mindspore/profiler/analysis/viewer/ascend_step_trace_time_viewer.py +265 -0
  316. mindspore/profiler/analysis/viewer/ascend_timeline_viewer.py +58 -0
  317. mindspore/profiler/analysis/viewer/base_viewer.py +26 -0
  318. mindspore/profiler/analysis/viewer/ms_dataset_viewer.py +97 -0
  319. mindspore/profiler/analysis/viewer/ms_minddata_viewer.py +581 -0
  320. mindspore/profiler/analysis/work_flow.py +73 -0
  321. mindspore/profiler/common/ascend_msprof_exporter.py +138 -0
  322. mindspore/profiler/common/command_executor.py +90 -0
  323. mindspore/profiler/common/constant.py +174 -3
  324. mindspore/profiler/common/file_manager.py +208 -0
  325. mindspore/profiler/common/log.py +130 -0
  326. mindspore/profiler/common/msprof_cmd_tool.py +202 -0
  327. mindspore/profiler/common/path_manager.py +371 -0
  328. mindspore/profiler/common/process_bar.py +168 -0
  329. mindspore/profiler/common/process_pool.py +9 -3
  330. mindspore/profiler/common/profiler_context.py +476 -0
  331. mindspore/profiler/common/profiler_info.py +304 -0
  332. mindspore/profiler/common/profiler_output_path.py +284 -0
  333. mindspore/profiler/common/profiler_parameters.py +210 -0
  334. mindspore/profiler/common/profiler_path_manager.py +120 -0
  335. mindspore/profiler/common/record_function.py +76 -0
  336. mindspore/profiler/common/tlv_decoder.py +76 -0
  337. mindspore/profiler/common/util.py +75 -2
  338. mindspore/profiler/dynamic_profiler.py +270 -37
  339. mindspore/profiler/envprofiler.py +138 -0
  340. mindspore/profiler/mstx.py +199 -0
  341. mindspore/profiler/platform/__init__.py +21 -0
  342. mindspore/profiler/platform/base_profiler.py +40 -0
  343. mindspore/profiler/platform/cpu_profiler.py +124 -0
  344. mindspore/profiler/platform/gpu_profiler.py +74 -0
  345. mindspore/profiler/platform/npu_profiler.py +309 -0
  346. mindspore/profiler/profiler.py +580 -93
  347. mindspore/profiler/profiler_action_controller.py +187 -0
  348. mindspore/profiler/profiler_interface.py +114 -0
  349. mindspore/profiler/schedule.py +208 -0
  350. mindspore/rewrite/api/symbol_tree.py +1 -2
  351. mindspore/run_check/_check_version.py +18 -13
  352. mindspore/runtime/__init__.py +37 -0
  353. mindspore/runtime/device.py +27 -0
  354. mindspore/runtime/event.py +209 -0
  355. mindspore/runtime/executor.py +148 -0
  356. mindspore/runtime/memory.py +392 -0
  357. mindspore/runtime/stream.py +460 -0
  358. mindspore/runtime/thread_bind_core.py +401 -0
  359. mindspore/swresample-4.dll +0 -0
  360. mindspore/swscale-6.dll +0 -0
  361. mindspore/tbbmalloc.dll +0 -0
  362. mindspore/tinyxml2.dll +0 -0
  363. mindspore/train/__init__.py +2 -2
  364. mindspore/train/_utils.py +53 -18
  365. mindspore/train/amp.py +8 -4
  366. mindspore/train/callback/_checkpoint.py +32 -18
  367. mindspore/train/callback/_early_stop.py +1 -1
  368. mindspore/train/callback/_flops_collector.py +105 -69
  369. mindspore/train/callback/_history.py +1 -1
  370. mindspore/train/callback/_summary_collector.py +44 -6
  371. mindspore/train/callback/_tft_register.py +37 -15
  372. mindspore/train/dataset_helper.py +11 -11
  373. mindspore/train/metrics/precision.py +4 -5
  374. mindspore/train/mind_ir_pb2.py +167 -46
  375. mindspore/train/model.py +13 -14
  376. mindspore/train/serialization.py +461 -72
  377. mindspore/train/summary/summary_record.py +1 -2
  378. mindspore/train/train_thor/model_thor.py +1 -1
  379. mindspore/turbojpeg.dll +0 -0
  380. mindspore/utils/__init__.py +4 -2
  381. mindspore/utils/dryrun.py +138 -0
  382. mindspore/utils/runtime_execution_order_check.py +550 -0
  383. mindspore/vcmeta.dll +0 -0
  384. mindspore/vcruntime140.dll +0 -0
  385. mindspore/vcruntime140_1.dll +0 -0
  386. mindspore/version.py +1 -1
  387. {mindspore-2.4.1.dist-info → mindspore-2.5.0.dist-info}/METADATA +3 -4
  388. {mindspore-2.4.1.dist-info → mindspore-2.5.0.dist-info}/RECORD +391 -265
  389. {mindspore-2.4.1.dist-info → mindspore-2.5.0.dist-info}/entry_points.txt +1 -1
  390. mindspore/common/_tensor_overload.py +0 -139
  391. mindspore/mindspore_np_dtype.dll +0 -0
  392. mindspore/profiler/envprofiling.py +0 -254
  393. mindspore/profiler/profiling.py +0 -1926
  394. {mindspore-2.4.1.dist-info → mindspore-2.5.0.dist-info}/WHEEL +0 -0
  395. {mindspore-2.4.1.dist-info → mindspore-2.5.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,73 @@
1
+ # Copyright 2024 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
+ """Workflow management for parsers"""
16
+ from typing import Iterator, Optional
17
+ from mindspore.profiler.analysis.parser.base_parser import BaseParser
18
+
19
+
20
+ class WorkFlow:
21
+ """
22
+ Manages a chain of parsers.
23
+ """
24
+ def __init__(self, head_parser: Optional[BaseParser] = None):
25
+ """
26
+ Initialize WorkFlow with an optional head parser.
27
+
28
+ Args:
29
+ head_parser (Optional[BaseParser]): The first parser in the chain.
30
+ """
31
+ self.head_parser = head_parser
32
+
33
+ def add_parser(self, parser: BaseParser) -> None:
34
+ """
35
+ Add a parser to the end of the chain.
36
+
37
+ Args:
38
+ parser (BaseParser): Parser to be added to the chain.
39
+ """
40
+ if not self.head_parser:
41
+ self.head_parser = parser
42
+ return
43
+
44
+ current = self.head_parser
45
+ while current.next_parser:
46
+ current = current.next_parser
47
+ current.next_parser = parser
48
+
49
+ def __iter__(self) -> Iterator[BaseParser]:
50
+ """
51
+ Iterate through the chain of parsers.
52
+
53
+ Yields:
54
+ BaseParser: Each parser in the chain.
55
+ """
56
+ current = self.head_parser
57
+ while current:
58
+ yield current
59
+ current = current.next_parser
60
+
61
+ def __len__(self) -> int:
62
+ """
63
+ Get the length of the parser chain.
64
+
65
+ Returns:
66
+ int: The number of parsers in the chain.
67
+ """
68
+ length = 0
69
+ current = self.head_parser
70
+ while current:
71
+ length += 1
72
+ current = current.next_parser
73
+ return length
@@ -0,0 +1,138 @@
1
+ # Copyright 2024 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
+ """Exporter for Ascend MSPROF data."""
16
+ import os
17
+ import glob
18
+ from collections import defaultdict
19
+ from typing import Dict, List, Optional
20
+
21
+ from mindspore import log as logger
22
+ from mindspore.profiler.common.path_manager import PathManager
23
+ from mindspore.profiler.common.file_manager import FileManager
24
+ from mindspore.profiler.common.msprof_cmd_tool import MsprofCmdTool
25
+
26
+
27
+ class AscendMsprofExporter:
28
+ """Exporter for Ascend MSPROF data."""
29
+
30
+ _DRV_VERSION = 467473
31
+ _DEFAULT_MODEL_ID = 4294967295
32
+ _STEP_TRACE_FILE_PATTERN = "step_trace_*.csv"
33
+ _STEP_TRACE_MODEL_ID_INDEX = 9
34
+ _STEP_TRACE_ITERATION_ID_INDEX = 1
35
+
36
+ def __init__(self, **kwargs):
37
+ """Initialize AscendMsprofExporter."""
38
+ self._msprof_profile_output_path = kwargs.get("msprof_profile_output_path")
39
+ self._msprof_profile_path = kwargs.get("msprof_profile_path")
40
+ self._step_list = kwargs.get("step_list")
41
+ self._msprof_tool = MsprofCmdTool(self._msprof_profile_path)
42
+
43
+ def export(self) -> None:
44
+ """Determine the export strategy and execute the appropriate export method."""
45
+ support_all_export = self._check_drv_version()
46
+ if self._step_list or not support_all_export:
47
+ self._single_export(self._step_list)
48
+ else:
49
+ self._all_export()
50
+ self._msprof_tool.run_ms_analyze_cmd()
51
+
52
+ def _single_export(self, step_list: Optional[List[int]]) -> None:
53
+ """Perform single export for each model and iteration.
54
+
55
+ Args:
56
+ step_list (Optional[List[int]]): iteration IDs.
57
+ """
58
+ if not step_list:
59
+ model_iteration_dict = self._generate_step_trace()
60
+ if not model_iteration_dict:
61
+ return
62
+ else:
63
+ model_iteration_dict = {self._DEFAULT_MODEL_ID: step_list}
64
+
65
+ for model_id, iter_list in model_iteration_dict.items():
66
+ self._msprof_tool.run_ms_py_export_cmd(model_id, iter_list)
67
+
68
+ def _all_export(self) -> None:
69
+ """Perform all-export for all data."""
70
+ self._msprof_tool.run_ms_export_cmd()
71
+
72
+ def _check_drv_version(self) -> bool:
73
+ """Check if the driver version supports all-export.
74
+
75
+ Returns:
76
+ bool: True if driver version supports all-export, False otherwise.
77
+ """
78
+ msprof_info = self._msprof_tool.get_msprof_info()
79
+ status = msprof_info.get("status", 1)
80
+ drv_version = (
81
+ msprof_info.get("data", {}).get("version_info", {}).get("drv_version", 0)
82
+ )
83
+
84
+ if status != 1 and drv_version and drv_version >= self._DRV_VERSION:
85
+ return True
86
+
87
+ logger.warning(
88
+ "Current driver package does not support all-export mode. "
89
+ "Using single export mode, which may affect performance. "
90
+ "Consider upgrading the driver package."
91
+ )
92
+ return False
93
+
94
+ def _generate_step_trace(self) -> Optional[Dict[int, List[int]]]:
95
+ """Generate step trace data.
96
+
97
+ Returns:
98
+ Optional[Dict[int, List[int]]]: Model IDs to iteration IDs mapping, or None if failed.
99
+ """
100
+ try:
101
+ # step1: run msprof command
102
+ self._msprof_tool.run_ms_export_cmd()
103
+ step_trace_file = glob.glob(
104
+ os.path.join(
105
+ self._msprof_profile_output_path, self._STEP_TRACE_FILE_PATTERN
106
+ )
107
+ )
108
+ if not step_trace_file:
109
+ logger.warning(
110
+ f"No step trace csv file found in {self._msprof_profile_output_path}."
111
+ )
112
+ return None
113
+ # step2: parse the step trace file to get model id and iteration id
114
+ model_iteration_dict = self._parse_step_trace_file(step_trace_file[0])
115
+ # step3: remove the unused files
116
+ PathManager.remove_path_safety(self._msprof_profile_output_path)
117
+ return model_iteration_dict
118
+
119
+ except RuntimeError as err:
120
+ logger.warning(f"Failed to get step trace data. Error: {str(err)}")
121
+ return None
122
+
123
+ def _parse_step_trace_file(self, file_path: str) -> Dict[int, List[int]]:
124
+ """Parse the step trace file to extract model and iteration information.
125
+
126
+ Args:
127
+ file_path (str): Path to the step trace file.
128
+
129
+ Returns:
130
+ Dict[int, List[int]]: Model IDs to iteration IDs mapping.
131
+ """
132
+ model_iteration_dict = defaultdict(list)
133
+ step_trace_data = FileManager.read_csv_file(file_path)
134
+ for row in step_trace_data:
135
+ model_id = int(row[self._STEP_TRACE_MODEL_ID_INDEX])
136
+ iteration_id = int(row[self._STEP_TRACE_ITERATION_ID_INDEX])
137
+ model_iteration_dict[model_id].append(iteration_id)
138
+ return model_iteration_dict
@@ -0,0 +1,90 @@
1
+ # Copyright 2020-2024 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
+ """Profiler command executor"""
16
+ import shlex
17
+ import subprocess
18
+ from typing import Union, Tuple
19
+
20
+ from mindspore import log as logger
21
+
22
+
23
+ class CommandExecutor:
24
+ """
25
+ Execute command in subprocess.
26
+ """
27
+ @staticmethod
28
+ def execute(
29
+ cmd: Union[str, list],
30
+ timeout: int = 10 * 60 * 60,
31
+ check: bool = True,
32
+ encoding: str = "utf-8",
33
+ ) -> Tuple[str, str, int]:
34
+ """
35
+ Execute a shell command with improved error handling and logging.
36
+
37
+ Args:
38
+ cmd (Union[str, list]): The command to execute, either as a string or list.
39
+ timeout (int): Maximum execution time in seconds. Defaults to 10 hours.
40
+ check (bool): If True, raise an exception for non-zero exit codes. Defaults to True.
41
+ encoding (str): Specify the encoding for output. Defaults to 'utf-8'.
42
+
43
+ Returns:
44
+ Tuple[str, str, int]: A tuple containing (stdout, stderr, return_code).
45
+
46
+ Raises:
47
+ RuntimeError: If any error occurs during command execution.
48
+ """
49
+ if isinstance(cmd, str):
50
+ cmd = shlex.split(cmd)
51
+
52
+ try:
53
+ result = subprocess.run(
54
+ cmd,
55
+ capture_output=True,
56
+ text=True,
57
+ timeout=timeout,
58
+ check=check,
59
+ shell=False,
60
+ encoding=encoding,
61
+ )
62
+ logger.info(
63
+ f"Command '{cmd}' executed successfully. Return code: {result.returncode}"
64
+ )
65
+ return result.stdout, result.stderr, result.returncode
66
+
67
+ except subprocess.TimeoutExpired as e:
68
+ error_msg = f"Command '{cmd}' timed out after {timeout} seconds"
69
+ logger.error(error_msg)
70
+ raise RuntimeError(error_msg) from e
71
+
72
+ except subprocess.CalledProcessError as e:
73
+ error_msg = (
74
+ f"Command '{cmd}' failed with return code {e.returncode}, "
75
+ f"Standard Error: {e.stderr}"
76
+ )
77
+ logger.error(error_msg)
78
+ raise RuntimeError(error_msg) from e
79
+
80
+ except (FileNotFoundError, PermissionError) as e:
81
+ error_msg = f"Error executing command '{cmd}': {str(e)}"
82
+ logger.error(error_msg)
83
+ raise RuntimeError(error_msg) from e
84
+
85
+ except Exception as e: # pylint: disable=broad-exception-caught
86
+ error_msg = (
87
+ f"Unexpected error occurred while executing command '{cmd}': {str(e)}"
88
+ )
89
+ logger.error(error_msg)
90
+ raise RuntimeError(error_msg) from e
@@ -18,12 +18,183 @@ from enum import Enum
18
18
 
19
19
  class DeviceTarget(Enum):
20
20
  """The device target enum."""
21
- CPU = 'cpu'
22
- GPU = 'gpu'
23
- ASCEND = 'ascend'
21
+
22
+ CPU = "CPU"
23
+ GPU = "GPU"
24
+ NPU = "Ascend"
24
25
 
25
26
 
26
27
  class ProfilerLevel(Enum):
28
+ """The profiler level enum."""
29
+
30
+ LevelNone = "LevelNone"
27
31
  Level0 = "Level0"
28
32
  Level1 = "Level1"
29
33
  Level2 = "Level2"
34
+
35
+
36
+ class ProfilerActivity(Enum):
37
+ """The profiler activity enum."""
38
+
39
+ NPU = "NPU"
40
+ GPU = "GPU"
41
+ CPU = "CPU"
42
+
43
+
44
+ class AicoreMetrics(Enum):
45
+ """The aicore metrics enum."""
46
+
47
+ PipeUtilization = "PipeUtilization"
48
+ ArithmeticUtilization = "ArithmeticUtilization"
49
+ Memory = "Memory"
50
+ MemoryL0 = "MemoryL0"
51
+ MemoryUB = "MemoryUB"
52
+ ResourceConflictRatio = "ResourceConflictRatio"
53
+ L2Cache = "L2Cache"
54
+ AiCoreNone = "None"
55
+
56
+
57
+ class OverlapAnalysisTidName(Enum):
58
+ """The overlap analysis tidName."""
59
+ COMPUTING = "Computing"
60
+ COMMUNICATION = "Communication"
61
+ COMMUNICATION_NOT_OVERLAP = "Communication(Not Overlapped)"
62
+ FREE = "Free"
63
+
64
+
65
+ class OpSummaryHeaders(Enum):
66
+ """The op summary headers."""
67
+ STEP_ID = "Step ID"
68
+ DEVICE_ID = "Device_id"
69
+ MODEL_NAME = "Model Name"
70
+ MODEL_ID = "Model ID"
71
+ TASK_ID = "Task ID"
72
+ STREAM_ID = "Stream ID"
73
+ OP_NAME = "Op Name"
74
+ OP_TYPE = "OP Type"
75
+ TASK_TYPE = "Task Type"
76
+ TASK_START_TIME = "Task Start Time(us)"
77
+ TASK_DURATION = "Task Duration(us)"
78
+ TASK_WAIT_TIME = "Task Wait Time(us)"
79
+ BLOCK_DIM = "Block Dim"
80
+ MIX_BLOCK_DIM = "Mix Block Dim"
81
+ HF32_ELIGIBLE = "HF32 Eligible"
82
+ INPUT_SHAPES = "Input Shapes"
83
+ INPUT_DATA_TYPES = "Input Data Types"
84
+ INPUT_FORMATS = "Input Formats"
85
+ OUTPUT_SHAPES = "Output Shapes"
86
+ OUTPUT_DATA_TYPES = "Output Data Types"
87
+ OUTPUT_FORMATS = "Output Formats"
88
+ CONTEXT_ID = "Context ID"
89
+
90
+
91
+ class EventConstant:
92
+ """Timeline event constant values"""
93
+
94
+ START_FLOW = "s"
95
+ END_FLOW = "f"
96
+ META_EVENT = 'M'
97
+ COMPLETE_EVENT = 'X'
98
+ INSTANT_EVENT = 'i'
99
+ COUNTER_EVENT = 'C'
100
+
101
+ PROCESS_NAME = "process_name"
102
+ PROCESS_LABEL = "process_labels"
103
+ PROCESS_SORT = "process_sort_index"
104
+ THREAD_NAME = "thread_name"
105
+ THREAD_SORT = "thread_sort_index"
106
+
107
+ CPU_LABEL = "CPU"
108
+ ASCEND_LABEL = "NPU"
109
+
110
+ HOST_TO_DEVICE_FLOW_CAT = "HostToDevice"
111
+ MINDSPORE_NPU_FLOW_CAT = "async_npu"
112
+ MINDSPORE_SELF_FLOW_CAT = "async_mindspore"
113
+ MSTX_FLOW_CAT = "MsTx"
114
+ MINDSPORE_SELF_FLOW_NAME = "mindspore_to_self"
115
+ MINDSPORE_NPU_FLOW_NAME = "mindspore_to_npu"
116
+ MSTX_FLOW_NAME = "mindspore_to_mstx"
117
+
118
+ MINDSPORE_PID = 1
119
+ CPU_OP_PID = 2
120
+ SCOPE_LAYER_PID = 3
121
+
122
+ MINDSPORE_SORT_IDX = 1
123
+ CPU_OP_SORT_IDX = 2
124
+ SCOPE_LAYER_SORT_IDX = 12
125
+
126
+ # field name
127
+ SEQUENCE_NUMBER = "Sequence number"
128
+ FORWARD_THREAD_ID = "Fwd thread id"
129
+ OP_NAME = "op_name"
130
+ INPUT_SHAPES = "Input Dims"
131
+ INPUT_DTYPES = "Input type"
132
+ CALL_STACK = "Call stack"
133
+ MODULE_HIERARCHY = "Module Hierarchy"
134
+ FLOPS = "flops"
135
+ NAME = "name"
136
+ CUSTOM_INFO = "custom_info"
137
+ TOP_SCOPE_NAMES = ('Default', 'Gradients', 'recompute_Default')
138
+ KERNEL_LAUNCH_KEYWORDS = ("KernelLaunch", "LaunchTask")
139
+ MSTX_KEYWORD = "Mstx"
140
+
141
+ FLOW_OP = "flow"
142
+ INVALID_FLOW_ID = 18446744073709551615
143
+
144
+
145
+ class TimeConstant:
146
+ """Time constant values"""
147
+
148
+ NS_TO_US = 0.001
149
+ MS_TO_US = 1000
150
+
151
+
152
+ class FileConstant:
153
+ """File constant values"""
154
+
155
+ # tlv constant struct
156
+ FIX_SIZE_DATA = "fix_size_data"
157
+ CANN_FILE_REGEX = r"^PROF_\d+_\d+_[0-9a-zA-Z]+"
158
+ FRAMEWORK_DIR = "FRAMEWORK"
159
+
160
+
161
+ class ProfilerStepNameConstant:
162
+ """Profiler step name."""
163
+
164
+ PROFILER_STEP = "ProfilerStep#"
165
+
166
+
167
+ class TimelineLayerName(Enum):
168
+ """Timeline layer types."""
169
+ MINDSPORE = "MindSpore"
170
+ CPU_OP = "CPU OP"
171
+ MSTX = ["python", "python3"]
172
+ CANN = "CANN"
173
+ SCOPER_LAYER = "Scope Layer"
174
+ ASCEND_HARDWARE = "Ascend Hardware"
175
+ HCCL = "HCCL"
176
+ AI_CORE_FREQ = "AI Core Freq"
177
+ HBM = "HBM"
178
+ PCLE = "PCle"
179
+ HCCS = "HCCS"
180
+ LLC = "LLC"
181
+ NPU_MEM = "NPU MEM"
182
+ STARS_SOC_INFO = "Stars Soc Info"
183
+ STARS_Chip_Trans = "Stars Chip Trans"
184
+ ACC_PMU = "Acc PMU"
185
+ SIO = "SIO"
186
+ QOS = "QoS"
187
+ OVERLAP_ANALYSIS = "Overlap Analysis"
188
+
189
+
190
+ class AnalysisMode(Enum):
191
+ """analysis mode"""
192
+ SYNC_MODE = "sync"
193
+ ASYNC_MODE = "async"
194
+
195
+
196
+ class JitLevel:
197
+ """jit level"""
198
+ KBK_LEVEL = "O0"
199
+ KBK_DVM_LEVEL = "O1"
200
+ GRAPH_LEVEL = "O2"
@@ -0,0 +1,208 @@
1
+ # Copyright 2023 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
+ """Profiler file manager"""
16
+ import csv
17
+ import json
18
+ import os
19
+ import shutil
20
+ from typing import List, Dict, Optional, Tuple
21
+ import numpy as np
22
+
23
+ from mindspore import log as logger
24
+ from mindspore.profiler.common.path_manager import PathManager
25
+
26
+
27
+ class FileManager:
28
+ """Profiler file manager"""
29
+
30
+ MAX_PATH_LENGTH = 4096
31
+ MAX_FILE_NAME_LENGTH = 255
32
+ DATA_FILE_AUTHORITY = 0o640
33
+ DATA_DIR_AUTHORITY = 0o700
34
+ FLAGS = os.O_WRONLY | os.O_CREAT | os.O_TRUNC
35
+
36
+ @classmethod
37
+ def read_file_content(cls, path: str, mode: str = "r"):
38
+ """Read the content in the input file."""
39
+ PathManager.check_input_file_path(path)
40
+ PathManager.check_directory_path_readable(path)
41
+ try:
42
+ with open(path, mode) as file:
43
+ return file.read()
44
+ except Exception as err:
45
+ raise RuntimeError(f"Failed read file: {path}, error: {err}") from err
46
+
47
+ @classmethod
48
+ def read_json_file(cls, file_path: str) -> Optional[Dict]:
49
+ """Read json file and return dict data"""
50
+ PathManager.check_input_file_path(file_path)
51
+ PathManager.check_directory_path_readable(file_path)
52
+ try:
53
+ with open(file_path, "r", encoding="utf-8") as json_file:
54
+ data = json.load(json_file)
55
+ return data
56
+ except Exception as err:
57
+ raise RuntimeError(
58
+ f"Failed read json file: {file_path}, error: {err}"
59
+ ) from err
60
+
61
+ @classmethod
62
+ def create_json_file(
63
+ cls, output_file_path: str, json_data: List, indent: int = None
64
+ ) -> None:
65
+ """Create json file with least authority"""
66
+ PathManager.check_directory_path_writeable(os.path.dirname(output_file_path))
67
+ if not json_data:
68
+ logger.warning("Json data is empty, file path: %s", output_file_path)
69
+ return
70
+
71
+ try:
72
+ with os.fdopen(
73
+ os.open(output_file_path, cls.FLAGS, cls.DATA_FILE_AUTHORITY), "w"
74
+ ) as fp:
75
+ data = json.dumps(json_data, indent=indent, ensure_ascii=False)
76
+ fp.write(data)
77
+ except Exception as err:
78
+ raise RuntimeError(
79
+ f"Failed create json file: {output_file_path}, error: {err}"
80
+ ) from err
81
+
82
+ @classmethod
83
+ def read_csv_file(cls, file_path: str) -> list:
84
+ """Read csv file and return list"""
85
+ PathManager.check_input_file_path(file_path)
86
+ PathManager.check_directory_path_readable(file_path)
87
+ result_data = []
88
+ try:
89
+ with open(file_path, newline="", encoding="utf-8") as csv_file:
90
+ reader = csv.reader(csv_file)
91
+ for row in reader:
92
+ result_data.append(row)
93
+ return result_data
94
+ except Exception as err:
95
+ raise RuntimeError(f"Failed read csv file: {file_path}, error: {err}") from err
96
+
97
+ @classmethod
98
+ def read_csv_file_as_numpy(
99
+ cls, file_path: str, extern_headers: list = None
100
+ ) -> Tuple[np.ndarray, List[str]]:
101
+ """Read csv file and return numpy array"""
102
+ PathManager.check_input_file_path(file_path)
103
+ PathManager.check_directory_path_readable(file_path)
104
+ try:
105
+ with open(file_path, newline="", encoding="utf-8") as csv_file:
106
+ reader = csv.DictReader(csv_file, delimiter=",", quotechar='"')
107
+ headers = reader.fieldnames
108
+ if extern_headers:
109
+ headers = extern_headers + headers
110
+
111
+ csv_data = [
112
+ tuple([row.get(field) for field in headers]) for row in reader
113
+ ]
114
+ csv_data_np = np.array(
115
+ csv_data, dtype=np.dtype([(field, object) for field in headers])
116
+ )
117
+
118
+ return csv_data_np, headers
119
+ except Exception as err:
120
+ raise RuntimeError(f"Failed read csv file: {file_path}, error: {err}") from err
121
+
122
+ @classmethod
123
+ def create_csv_file(cls, file_path: str, data: list, headers: list = None) -> None:
124
+ """Create csv file and write the data"""
125
+ if not data:
126
+ logger.error(
127
+ "Create csv file failed, data is empty, file path: %s", file_path
128
+ )
129
+ return
130
+ PathManager.check_directory_path_writeable(os.path.dirname(file_path))
131
+ try:
132
+ with os.fdopen(
133
+ os.open(file_path, cls.FLAGS, cls.DATA_FILE_AUTHORITY), "w"
134
+ ) as fp:
135
+ writer = csv.writer(fp)
136
+ if headers:
137
+ writer.writerow(headers)
138
+ writer.writerows(data)
139
+ except Exception as err:
140
+ raise RuntimeError(
141
+ f"Failed create csv file: {file_path}, error: {err}"
142
+ ) from err
143
+
144
+ @classmethod
145
+ def combine_csv_file(
146
+ cls, source_file_list: list, target_file_path: str, header_map: dict = None
147
+ ):
148
+ """Merge multiple CSV files into one"""
149
+ headers, all_data = [], []
150
+ for source_file in source_file_list:
151
+ data = cls.read_csv_file(source_file)
152
+ if len(data) > 1:
153
+ headers = data[0]
154
+ all_data.extend(data[1:])
155
+ if all_data:
156
+ if isinstance(header_map, dict):
157
+ headers = [header_map.get(header, header) for header in headers]
158
+ FileManager.create_csv_file(target_file_path, all_data, headers)
159
+
160
+ @classmethod
161
+ def read_txt_file(cls, file_path: str) -> list:
162
+ """Read txt file and return list"""
163
+ PathManager.check_input_file_path(file_path)
164
+ PathManager.check_directory_path_readable(file_path)
165
+ result_data = []
166
+ try:
167
+ with open(file_path, "r", encoding="utf-8") as file:
168
+ for line in file.readlines():
169
+ result_data.append(line.strip())
170
+ except Exception as err:
171
+ raise RuntimeError(f"Failed read txt file: {file_path}, error: {err}") from err
172
+ return result_data
173
+
174
+ @classmethod
175
+ def copy_file(cls, src_path: str, dst_path: str):
176
+ """
177
+ Function Description:
178
+ copy file safety
179
+ Parameter:
180
+ src_path: file source path
181
+ dst_path: file destination path
182
+ Exception Description:
183
+ when src_path is link throw exception
184
+ """
185
+ if not os.path.exists(src_path):
186
+ logger.warning("The source file does not exist: %s", src_path)
187
+ return
188
+
189
+ PathManager.check_input_file_path(src_path)
190
+ src_dir = os.path.dirname(src_path)
191
+ PathManager.check_directory_path_readable(src_dir)
192
+ dst_dir = os.path.dirname(dst_path)
193
+ PathManager.check_directory_path_writeable(dst_dir)
194
+
195
+ try:
196
+ shutil.copy2(src_path, dst_path)
197
+ except (shutil.Error, IOError) as err:
198
+ msg = f"Failed to copy from '{src_path}' to '{dst_path}': {err}"
199
+ raise RuntimeError(msg) from err
200
+
201
+ @classmethod
202
+ def get_csv_file_list_by_start_name(cls, source_path: str, start_name: str):
203
+ """Get all the csv files that match the name"""
204
+ file_list = []
205
+ for file_name in os.listdir(source_path):
206
+ if file_name.startswith(start_name) and file_name.endswith(".csv"):
207
+ file_list.append(os.path.join(source_path, file_name))
208
+ return file_list