mindspore 2.4.0__cp310-cp310-macosx_10_15_x86_64.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 (1387) hide show
  1. mindspore/.commit_id +1 -0
  2. mindspore/__init__.py +53 -0
  3. mindspore/_c_dataengine.cpython-310-darwin.so +0 -0
  4. mindspore/_c_expression.cpython-310-darwin.so +0 -0
  5. mindspore/_c_mindrecord.cpython-310-darwin.so +0 -0
  6. mindspore/_check_jit_forbidden_api.py +106 -0
  7. mindspore/_checkparam.py +1419 -0
  8. mindspore/_extends/__init__.py +23 -0
  9. mindspore/_extends/builtin_operations.py +224 -0
  10. mindspore/_extends/graph_kernel/__init__.py +17 -0
  11. mindspore/_extends/graph_kernel/model/__init__.py +19 -0
  12. mindspore/_extends/graph_kernel/model/graph_parallel.py +311 -0
  13. mindspore/_extends/graph_kernel/model/graph_split.py +1348 -0
  14. mindspore/_extends/graph_kernel/model/model.py +553 -0
  15. mindspore/_extends/graph_kernel/model/model_builder.py +216 -0
  16. mindspore/_extends/graph_kernel/parallel_estimate.py +60 -0
  17. mindspore/_extends/graph_kernel/splitter.py +140 -0
  18. mindspore/_extends/graph_kernel/utils.py +28 -0
  19. mindspore/_extends/parallel_compile/__init__.py +19 -0
  20. mindspore/_extends/parallel_compile/akg_compiler/__init__.py +19 -0
  21. mindspore/_extends/parallel_compile/akg_compiler/akg_process.py +269 -0
  22. mindspore/_extends/parallel_compile/akg_compiler/build_tbe_kernel.py +529 -0
  23. mindspore/_extends/parallel_compile/akg_compiler/compiler.py +56 -0
  24. mindspore/_extends/parallel_compile/akg_compiler/gen_custom_op_files.py +96 -0
  25. mindspore/_extends/parallel_compile/akg_compiler/get_file_path.py +36 -0
  26. mindspore/_extends/parallel_compile/akg_compiler/tbe_topi.py +556 -0
  27. mindspore/_extends/parallel_compile/akg_compiler/util.py +159 -0
  28. mindspore/_extends/parse/__init__.py +49 -0
  29. mindspore/_extends/parse/compile_config.py +299 -0
  30. mindspore/_extends/parse/namespace.py +136 -0
  31. mindspore/_extends/parse/parser.py +1448 -0
  32. mindspore/_extends/parse/resources.py +213 -0
  33. mindspore/_extends/parse/standard_method.py +4475 -0
  34. mindspore/_extends/parse/trope.py +97 -0
  35. mindspore/_extends/pijit/__init__.py +23 -0
  36. mindspore/_extends/pijit/pijit_func_white_list.py +669 -0
  37. mindspore/_extends/remote/__init__.py +19 -0
  38. mindspore/_extends/remote/kernel_build_server.py +199 -0
  39. mindspore/_extends/remote/kernel_build_server_akg.py +55 -0
  40. mindspore/_extends/remote/kernel_build_server_akg_v2.py +55 -0
  41. mindspore/_extends/remote/kernel_build_server_ascend.py +75 -0
  42. mindspore/_extends/utils.py +68 -0
  43. mindspore/_install_custom.py +43 -0
  44. mindspore/_profiler.py +30 -0
  45. mindspore/amp.py +433 -0
  46. mindspore/boost/__init__.py +42 -0
  47. mindspore/boost/adasum.py +319 -0
  48. mindspore/boost/base.py +535 -0
  49. mindspore/boost/boost.py +400 -0
  50. mindspore/boost/boost_cell_wrapper.py +790 -0
  51. mindspore/boost/dim_reduce.py +323 -0
  52. mindspore/boost/grad_accumulation.py +79 -0
  53. mindspore/boost/grad_freeze.py +382 -0
  54. mindspore/boost/group_loss_scale_manager.py +166 -0
  55. mindspore/boost/less_batch_normalization.py +174 -0
  56. mindspore/common/__init__.py +86 -0
  57. mindspore/common/_auto_dynamic.py +68 -0
  58. mindspore/common/_decorator.py +50 -0
  59. mindspore/common/_jit_fallback_utils.py +110 -0
  60. mindspore/common/_monad.py +25 -0
  61. mindspore/common/_pijit_context.py +190 -0
  62. mindspore/common/_register_for_adapter.py +74 -0
  63. mindspore/common/_register_for_recompute.py +48 -0
  64. mindspore/common/_register_for_tensor.py +46 -0
  65. mindspore/common/_stub_tensor.py +210 -0
  66. mindspore/common/_tensor_overload.py +139 -0
  67. mindspore/common/_utils.py +122 -0
  68. mindspore/common/api.py +2064 -0
  69. mindspore/common/auto_dynamic_shape.py +507 -0
  70. mindspore/common/dtype.py +422 -0
  71. mindspore/common/dump.py +130 -0
  72. mindspore/common/file_system.py +48 -0
  73. mindspore/common/generator.py +254 -0
  74. mindspore/common/hook_handle.py +143 -0
  75. mindspore/common/initializer.py +880 -0
  76. mindspore/common/jit_config.py +98 -0
  77. mindspore/common/lazy_inline.py +240 -0
  78. mindspore/common/mindir_util.py +111 -0
  79. mindspore/common/mutable.py +234 -0
  80. mindspore/common/no_inline.py +54 -0
  81. mindspore/common/np_dtype.py +25 -0
  82. mindspore/common/parameter.py +1081 -0
  83. mindspore/common/recompute.py +292 -0
  84. mindspore/common/seed.py +260 -0
  85. mindspore/common/sparse_tensor.py +1175 -0
  86. mindspore/common/symbol.py +122 -0
  87. mindspore/common/tensor.py +5039 -0
  88. mindspore/communication/__init__.py +37 -0
  89. mindspore/communication/_comm_helper.py +501 -0
  90. mindspore/communication/_hccl_management.py +297 -0
  91. mindspore/communication/comm_func.py +1395 -0
  92. mindspore/communication/management.py +673 -0
  93. mindspore/config/op_info.config +533 -0
  94. mindspore/context.py +2077 -0
  95. mindspore/dataset/__init__.py +90 -0
  96. mindspore/dataset/audio/__init__.py +61 -0
  97. mindspore/dataset/audio/transforms.py +3690 -0
  98. mindspore/dataset/audio/utils.py +386 -0
  99. mindspore/dataset/audio/validators.py +1172 -0
  100. mindspore/dataset/callback/__init__.py +20 -0
  101. mindspore/dataset/callback/ds_callback.py +368 -0
  102. mindspore/dataset/callback/validators.py +32 -0
  103. mindspore/dataset/core/__init__.py +13 -0
  104. mindspore/dataset/core/config.py +1095 -0
  105. mindspore/dataset/core/datatypes.py +101 -0
  106. mindspore/dataset/core/py_util_helpers.py +65 -0
  107. mindspore/dataset/core/validator_helpers.py +781 -0
  108. mindspore/dataset/debug/__init__.py +21 -0
  109. mindspore/dataset/debug/debug_hook.py +97 -0
  110. mindspore/dataset/debug/pre_defined_hook.py +67 -0
  111. mindspore/dataset/engine/__init__.py +124 -0
  112. mindspore/dataset/engine/cache_admin.py +47 -0
  113. mindspore/dataset/engine/cache_client.py +129 -0
  114. mindspore/dataset/engine/datasets.py +4582 -0
  115. mindspore/dataset/engine/datasets_audio.py +911 -0
  116. mindspore/dataset/engine/datasets_standard_format.py +543 -0
  117. mindspore/dataset/engine/datasets_text.py +2161 -0
  118. mindspore/dataset/engine/datasets_user_defined.py +1184 -0
  119. mindspore/dataset/engine/datasets_vision.py +4816 -0
  120. mindspore/dataset/engine/iterators.py +371 -0
  121. mindspore/dataset/engine/obs/__init__.py +23 -0
  122. mindspore/dataset/engine/obs/config_loader.py +68 -0
  123. mindspore/dataset/engine/obs/obs_mindrecord_dataset.py +508 -0
  124. mindspore/dataset/engine/obs/util.py +482 -0
  125. mindspore/dataset/engine/offload.py +596 -0
  126. mindspore/dataset/engine/queue.py +304 -0
  127. mindspore/dataset/engine/samplers.py +895 -0
  128. mindspore/dataset/engine/serializer_deserializer.py +159 -0
  129. mindspore/dataset/engine/validators.py +2895 -0
  130. mindspore/dataset/text/__init__.py +51 -0
  131. mindspore/dataset/text/transforms.py +1703 -0
  132. mindspore/dataset/text/utils.py +715 -0
  133. mindspore/dataset/text/validators.py +642 -0
  134. mindspore/dataset/transforms/__init__.py +45 -0
  135. mindspore/dataset/transforms/c_transforms.py +638 -0
  136. mindspore/dataset/transforms/py_transforms.py +393 -0
  137. mindspore/dataset/transforms/py_transforms_util.py +255 -0
  138. mindspore/dataset/transforms/transforms.py +1260 -0
  139. mindspore/dataset/transforms/validators.py +410 -0
  140. mindspore/dataset/utils/__init__.py +19 -0
  141. mindspore/dataset/utils/browse_dataset.py +190 -0
  142. mindspore/dataset/utils/line_reader.py +126 -0
  143. mindspore/dataset/vision/__init__.py +65 -0
  144. mindspore/dataset/vision/c_transforms.py +2641 -0
  145. mindspore/dataset/vision/py_transforms.py +2120 -0
  146. mindspore/dataset/vision/py_transforms_util.py +1660 -0
  147. mindspore/dataset/vision/transforms.py +7295 -0
  148. mindspore/dataset/vision/utils.py +863 -0
  149. mindspore/dataset/vision/validators.py +1483 -0
  150. mindspore/default_config.py +2 -0
  151. mindspore/experimental/__init__.py +20 -0
  152. mindspore/experimental/es/__init__.py +22 -0
  153. mindspore/experimental/es/embedding_service.py +883 -0
  154. mindspore/experimental/es/embedding_service_layer.py +581 -0
  155. mindspore/experimental/llm_boost/__init__.py +21 -0
  156. mindspore/experimental/llm_boost/atb/__init__.py +23 -0
  157. mindspore/experimental/llm_boost/atb/boost_base.py +211 -0
  158. mindspore/experimental/llm_boost/atb/llama_boost.py +115 -0
  159. mindspore/experimental/llm_boost/atb/qwen_boost.py +101 -0
  160. mindspore/experimental/llm_boost/register.py +129 -0
  161. mindspore/experimental/llm_boost/utils.py +31 -0
  162. mindspore/experimental/map_parameter.py +309 -0
  163. mindspore/experimental/optim/__init__.py +40 -0
  164. mindspore/experimental/optim/adadelta.py +161 -0
  165. mindspore/experimental/optim/adagrad.py +168 -0
  166. mindspore/experimental/optim/adam.py +193 -0
  167. mindspore/experimental/optim/adamax.py +170 -0
  168. mindspore/experimental/optim/adamw.py +290 -0
  169. mindspore/experimental/optim/asgd.py +153 -0
  170. mindspore/experimental/optim/lr_scheduler.py +1371 -0
  171. mindspore/experimental/optim/nadam.py +157 -0
  172. mindspore/experimental/optim/optimizer.py +262 -0
  173. mindspore/experimental/optim/radam.py +194 -0
  174. mindspore/experimental/optim/rmsprop.py +154 -0
  175. mindspore/experimental/optim/rprop.py +164 -0
  176. mindspore/experimental/optim/sgd.py +156 -0
  177. mindspore/hal/__init__.py +40 -0
  178. mindspore/hal/_ascend.py +57 -0
  179. mindspore/hal/_base.py +57 -0
  180. mindspore/hal/_cpu.py +56 -0
  181. mindspore/hal/_gpu.py +57 -0
  182. mindspore/hal/contiguous_tensors_handle.py +175 -0
  183. mindspore/hal/device.py +356 -0
  184. mindspore/hal/event.py +179 -0
  185. mindspore/hal/memory.py +326 -0
  186. mindspore/hal/stream.py +357 -0
  187. mindspore/include/OWNERS +7 -0
  188. mindspore/include/api/allocator.h +97 -0
  189. mindspore/include/api/callback/callback.h +93 -0
  190. mindspore/include/api/callback/ckpt_saver.h +41 -0
  191. mindspore/include/api/callback/loss_monitor.h +33 -0
  192. mindspore/include/api/callback/lr_scheduler.h +51 -0
  193. mindspore/include/api/callback/time_monitor.h +34 -0
  194. mindspore/include/api/callback/train_accuracy.h +37 -0
  195. mindspore/include/api/cell.h +90 -0
  196. mindspore/include/api/cfg.h +82 -0
  197. mindspore/include/api/context.h +602 -0
  198. mindspore/include/api/data_type.h +47 -0
  199. mindspore/include/api/delegate.h +178 -0
  200. mindspore/include/api/delegate_api.h +75 -0
  201. mindspore/include/api/dual_abi_helper.h +208 -0
  202. mindspore/include/api/format.h +28 -0
  203. mindspore/include/api/graph.h +46 -0
  204. mindspore/include/api/kernel.h +58 -0
  205. mindspore/include/api/kernel_api.h +168 -0
  206. mindspore/include/api/metrics/accuracy.h +36 -0
  207. mindspore/include/api/metrics/metrics.h +41 -0
  208. mindspore/include/api/model.h +438 -0
  209. mindspore/include/api/model_group.h +91 -0
  210. mindspore/include/api/model_parallel_runner.h +168 -0
  211. mindspore/include/api/serialization.h +185 -0
  212. mindspore/include/api/status.h +192 -0
  213. mindspore/include/api/types.h +431 -0
  214. mindspore/include/api/visible.h +41 -0
  215. mindspore/include/c_api/context_c.h +179 -0
  216. mindspore/include/c_api/data_type_c.h +52 -0
  217. mindspore/include/c_api/format_c.h +46 -0
  218. mindspore/include/c_api/model_c.h +347 -0
  219. mindspore/include/c_api/status_c.h +79 -0
  220. mindspore/include/c_api/tensor_c.h +146 -0
  221. mindspore/include/c_api/types_c.h +67 -0
  222. mindspore/include/dataset/config.h +163 -0
  223. mindspore/include/dataset/constants.h +363 -0
  224. mindspore/include/dataset/execute.h +196 -0
  225. mindspore/include/dataset/text.h +1092 -0
  226. mindspore/include/dataset/transforms.h +638 -0
  227. mindspore/include/dataset/vision.h +2129 -0
  228. mindspore/include/dataset/vision_ascend.h +206 -0
  229. mindspore/include/dataset/vision_lite.h +625 -0
  230. mindspore/lib/libavcodec.59.dylib +0 -0
  231. mindspore/lib/libavdevice.59.dylib +0 -0
  232. mindspore/lib/libavfilter.8.dylib +0 -0
  233. mindspore/lib/libavformat.59.dylib +0 -0
  234. mindspore/lib/libavutil.57.dylib +0 -0
  235. mindspore/lib/libdnnl.2.dylib +0 -0
  236. mindspore/lib/libicudata.69.dylib +0 -0
  237. mindspore/lib/libicui18n.69.dylib +0 -0
  238. mindspore/lib/libicuuc.69.dylib +0 -0
  239. mindspore/lib/libmindspore_address_sorting.15.dylib +0 -0
  240. mindspore/lib/libmindspore_backend.dylib +0 -0
  241. mindspore/lib/libmindspore_common.dylib +0 -0
  242. mindspore/lib/libmindspore_core.dylib +0 -0
  243. mindspore/lib/libmindspore_glog.0.dylib +0 -0
  244. mindspore/lib/libmindspore_gpr.15.dylib +0 -0
  245. mindspore/lib/libmindspore_grpc++.1.dylib +0 -0
  246. mindspore/lib/libmindspore_grpc.15.dylib +0 -0
  247. mindspore/lib/libmindspore_np_dtype.dylib +0 -0
  248. mindspore/lib/libmindspore_ops.dylib +0 -0
  249. mindspore/lib/libmindspore_upb.15.dylib +0 -0
  250. mindspore/lib/libnnacl.dylib +0 -0
  251. mindspore/lib/libopencv_core.4.5.dylib +0 -0
  252. mindspore/lib/libopencv_imgcodecs.4.5.dylib +0 -0
  253. mindspore/lib/libopencv_imgproc.4.5.dylib +0 -0
  254. mindspore/lib/libps_cache.dylib +0 -0
  255. mindspore/lib/libswresample.4.dylib +0 -0
  256. mindspore/lib/libswscale.6.dylib +0 -0
  257. mindspore/lib/libtinyxml2.8.dylib +0 -0
  258. mindspore/log.py +633 -0
  259. mindspore/mindrecord/__init__.py +43 -0
  260. mindspore/mindrecord/common/__init__.py +17 -0
  261. mindspore/mindrecord/common/constant.py +20 -0
  262. mindspore/mindrecord/common/enums.py +44 -0
  263. mindspore/mindrecord/common/exceptions.py +311 -0
  264. mindspore/mindrecord/config.py +809 -0
  265. mindspore/mindrecord/filereader.py +174 -0
  266. mindspore/mindrecord/filewriter.py +722 -0
  267. mindspore/mindrecord/mindpage.py +210 -0
  268. mindspore/mindrecord/shardheader.py +141 -0
  269. mindspore/mindrecord/shardindexgenerator.py +74 -0
  270. mindspore/mindrecord/shardreader.py +117 -0
  271. mindspore/mindrecord/shardsegment.py +128 -0
  272. mindspore/mindrecord/shardutils.py +185 -0
  273. mindspore/mindrecord/shardwriter.py +237 -0
  274. mindspore/mindrecord/tools/__init__.py +17 -0
  275. mindspore/mindrecord/tools/cifar10.py +140 -0
  276. mindspore/mindrecord/tools/cifar100.py +153 -0
  277. mindspore/mindrecord/tools/cifar100_to_mr.py +185 -0
  278. mindspore/mindrecord/tools/cifar10_to_mr.py +177 -0
  279. mindspore/mindrecord/tools/csv_to_mr.py +200 -0
  280. mindspore/mindrecord/tools/imagenet_to_mr.py +206 -0
  281. mindspore/mindrecord/tools/mnist_to_mr.py +259 -0
  282. mindspore/mindrecord/tools/tfrecord_to_mr.py +360 -0
  283. mindspore/mint/__init__.py +1586 -0
  284. mindspore/mint/distributed/__init__.py +31 -0
  285. mindspore/mint/distributed/distributed.py +254 -0
  286. mindspore/mint/linalg/__init__.py +22 -0
  287. mindspore/mint/nn/__init__.py +757 -0
  288. mindspore/mint/nn/functional.py +679 -0
  289. mindspore/mint/nn/layer/__init__.py +39 -0
  290. mindspore/mint/nn/layer/activation.py +133 -0
  291. mindspore/mint/nn/layer/normalization.py +477 -0
  292. mindspore/mint/nn/layer/pooling.py +110 -0
  293. mindspore/mint/optim/__init__.py +24 -0
  294. mindspore/mint/optim/adamw.py +206 -0
  295. mindspore/mint/special/__init__.py +63 -0
  296. mindspore/multiprocessing/__init__.py +73 -0
  297. mindspore/nn/__init__.py +47 -0
  298. mindspore/nn/cell.py +2787 -0
  299. mindspore/nn/dynamic_lr.py +482 -0
  300. mindspore/nn/grad/__init__.py +21 -0
  301. mindspore/nn/grad/cell_grad.py +196 -0
  302. mindspore/nn/layer/__init__.py +63 -0
  303. mindspore/nn/layer/activation.py +1822 -0
  304. mindspore/nn/layer/basic.py +1629 -0
  305. mindspore/nn/layer/channel_shuffle.py +90 -0
  306. mindspore/nn/layer/combined.py +248 -0
  307. mindspore/nn/layer/container.py +734 -0
  308. mindspore/nn/layer/conv.py +1505 -0
  309. mindspore/nn/layer/dense.py +204 -0
  310. mindspore/nn/layer/embedding.py +869 -0
  311. mindspore/nn/layer/image.py +661 -0
  312. mindspore/nn/layer/math.py +1069 -0
  313. mindspore/nn/layer/normalization.py +1273 -0
  314. mindspore/nn/layer/padding.py +880 -0
  315. mindspore/nn/layer/pooling.py +2302 -0
  316. mindspore/nn/layer/rnn_cells.py +388 -0
  317. mindspore/nn/layer/rnns.py +849 -0
  318. mindspore/nn/layer/thor_layer.py +963 -0
  319. mindspore/nn/layer/timedistributed.py +155 -0
  320. mindspore/nn/layer/transformer.py +823 -0
  321. mindspore/nn/learning_rate_schedule.py +512 -0
  322. mindspore/nn/loss/__init__.py +36 -0
  323. mindspore/nn/loss/loss.py +2924 -0
  324. mindspore/nn/metrics.py +53 -0
  325. mindspore/nn/optim/__init__.py +45 -0
  326. mindspore/nn/optim/_dist_optimizer_registry.py +111 -0
  327. mindspore/nn/optim/ada_grad.py +217 -0
  328. mindspore/nn/optim/adadelta.py +206 -0
  329. mindspore/nn/optim/adafactor.py +448 -0
  330. mindspore/nn/optim/adam.py +1297 -0
  331. mindspore/nn/optim/adamax.py +220 -0
  332. mindspore/nn/optim/adasum.py +548 -0
  333. mindspore/nn/optim/asgd.py +216 -0
  334. mindspore/nn/optim/ftrl.py +401 -0
  335. mindspore/nn/optim/lamb.py +296 -0
  336. mindspore/nn/optim/lars.py +202 -0
  337. mindspore/nn/optim/lazyadam.py +533 -0
  338. mindspore/nn/optim/momentum.py +239 -0
  339. mindspore/nn/optim/optimizer.py +1034 -0
  340. mindspore/nn/optim/proximal_ada_grad.py +242 -0
  341. mindspore/nn/optim/rmsprop.py +264 -0
  342. mindspore/nn/optim/rprop.py +251 -0
  343. mindspore/nn/optim/sgd.py +237 -0
  344. mindspore/nn/optim/tft_wrapper.py +127 -0
  345. mindspore/nn/optim/thor.py +1310 -0
  346. mindspore/nn/probability/__init__.py +22 -0
  347. mindspore/nn/probability/bijector/__init__.py +35 -0
  348. mindspore/nn/probability/bijector/bijector.py +337 -0
  349. mindspore/nn/probability/bijector/exp.py +65 -0
  350. mindspore/nn/probability/bijector/gumbel_cdf.py +144 -0
  351. mindspore/nn/probability/bijector/invert.py +126 -0
  352. mindspore/nn/probability/bijector/power_transform.py +196 -0
  353. mindspore/nn/probability/bijector/scalar_affine.py +167 -0
  354. mindspore/nn/probability/bijector/softplus.py +189 -0
  355. mindspore/nn/probability/bnn_layers/__init__.py +29 -0
  356. mindspore/nn/probability/bnn_layers/_util.py +46 -0
  357. mindspore/nn/probability/bnn_layers/bnn_cell_wrapper.py +112 -0
  358. mindspore/nn/probability/bnn_layers/conv_variational.py +267 -0
  359. mindspore/nn/probability/bnn_layers/dense_variational.py +302 -0
  360. mindspore/nn/probability/bnn_layers/layer_distribution.py +123 -0
  361. mindspore/nn/probability/distribution/__init__.py +56 -0
  362. mindspore/nn/probability/distribution/_utils/__init__.py +34 -0
  363. mindspore/nn/probability/distribution/_utils/custom_ops.py +96 -0
  364. mindspore/nn/probability/distribution/_utils/utils.py +362 -0
  365. mindspore/nn/probability/distribution/bernoulli.py +334 -0
  366. mindspore/nn/probability/distribution/beta.py +391 -0
  367. mindspore/nn/probability/distribution/categorical.py +435 -0
  368. mindspore/nn/probability/distribution/cauchy.py +383 -0
  369. mindspore/nn/probability/distribution/distribution.py +827 -0
  370. mindspore/nn/probability/distribution/exponential.py +350 -0
  371. mindspore/nn/probability/distribution/gamma.py +391 -0
  372. mindspore/nn/probability/distribution/geometric.py +335 -0
  373. mindspore/nn/probability/distribution/gumbel.py +257 -0
  374. mindspore/nn/probability/distribution/half_normal.py +133 -0
  375. mindspore/nn/probability/distribution/laplace.py +128 -0
  376. mindspore/nn/probability/distribution/log_normal.py +272 -0
  377. mindspore/nn/probability/distribution/logistic.py +379 -0
  378. mindspore/nn/probability/distribution/normal.py +336 -0
  379. mindspore/nn/probability/distribution/poisson.py +288 -0
  380. mindspore/nn/probability/distribution/student_t.py +149 -0
  381. mindspore/nn/probability/distribution/transformed_distribution.py +235 -0
  382. mindspore/nn/probability/distribution/uniform.py +375 -0
  383. mindspore/nn/reinforcement/__init__.py +24 -0
  384. mindspore/nn/reinforcement/_batch_read_write.py +142 -0
  385. mindspore/nn/reinforcement/_tensors_queue.py +152 -0
  386. mindspore/nn/reinforcement/tensor_array.py +145 -0
  387. mindspore/nn/sparse/__init__.py +23 -0
  388. mindspore/nn/sparse/sparse.py +147 -0
  389. mindspore/nn/wrap/__init__.py +49 -0
  390. mindspore/nn/wrap/cell_wrapper.py +968 -0
  391. mindspore/nn/wrap/grad_reducer.py +608 -0
  392. mindspore/nn/wrap/loss_scale.py +694 -0
  393. mindspore/numpy/__init__.py +121 -0
  394. mindspore/numpy/array_creations.py +2731 -0
  395. mindspore/numpy/array_ops.py +2629 -0
  396. mindspore/numpy/dtypes.py +185 -0
  397. mindspore/numpy/fft.py +966 -0
  398. mindspore/numpy/logic_ops.py +936 -0
  399. mindspore/numpy/math_ops.py +5911 -0
  400. mindspore/numpy/utils.py +214 -0
  401. mindspore/numpy/utils_const.py +565 -0
  402. mindspore/ops/__init__.py +56 -0
  403. mindspore/ops/_constants.py +30 -0
  404. mindspore/ops/_grad_experimental/__init__.py +31 -0
  405. mindspore/ops/_grad_experimental/grad_array_ops.py +830 -0
  406. mindspore/ops/_grad_experimental/grad_base.py +143 -0
  407. mindspore/ops/_grad_experimental/grad_comm_ops.py +714 -0
  408. mindspore/ops/_grad_experimental/grad_debug_ops.py +31 -0
  409. mindspore/ops/_grad_experimental/grad_implementations.py +203 -0
  410. mindspore/ops/_grad_experimental/grad_inner_ops.py +79 -0
  411. mindspore/ops/_grad_experimental/grad_math_ops.py +802 -0
  412. mindspore/ops/_grad_experimental/grad_nn_ops.py +231 -0
  413. mindspore/ops/_grad_experimental/grad_quant_ops.py +238 -0
  414. mindspore/ops/_grad_experimental/grad_sparse.py +342 -0
  415. mindspore/ops/_grad_experimental/grad_sparse_ops.py +399 -0
  416. mindspore/ops/_grad_experimental/taylor_rule.py +220 -0
  417. mindspore/ops/_op_impl/__init__.py +23 -0
  418. mindspore/ops/_op_impl/_custom_op/__init__.py +39 -0
  419. mindspore/ops/_op_impl/_custom_op/_basic.py +158 -0
  420. mindspore/ops/_op_impl/_custom_op/batch_matmul_impl.py +279 -0
  421. mindspore/ops/_op_impl/_custom_op/batchnorm_fold.py +156 -0
  422. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2.py +109 -0
  423. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2_grad.py +125 -0
  424. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2_grad_reduce.py +105 -0
  425. mindspore/ops/_op_impl/_custom_op/batchnorm_fold_grad.py +124 -0
  426. mindspore/ops/_op_impl/_custom_op/cholesky_trsm_impl.py +116 -0
  427. mindspore/ops/_op_impl/_custom_op/correction_mul.py +89 -0
  428. mindspore/ops/_op_impl/_custom_op/correction_mul_grad.py +196 -0
  429. mindspore/ops/_op_impl/_custom_op/dsd_back_impl.py +366 -0
  430. mindspore/ops/_op_impl/_custom_op/dsd_impl.py +162 -0
  431. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel.py +136 -0
  432. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel_grad.py +206 -0
  433. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel_grad_reduce.py +88 -0
  434. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer.py +128 -0
  435. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer_grad.py +199 -0
  436. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer_grad_reduce.py +88 -0
  437. mindspore/ops/_op_impl/_custom_op/fake_quant_perchannel.py +156 -0
  438. mindspore/ops/_op_impl/_custom_op/fake_quant_perchannel_grad.py +184 -0
  439. mindspore/ops/_op_impl/_custom_op/fake_quant_perlayer.py +143 -0
  440. mindspore/ops/_op_impl/_custom_op/fake_quant_perlayer_grad.py +169 -0
  441. mindspore/ops/_op_impl/_custom_op/fused_abs_max1_impl.py +548 -0
  442. mindspore/ops/_op_impl/_custom_op/img2col_impl.py +881 -0
  443. mindspore/ops/_op_impl/_custom_op/matmul_cube_dense_left_impl.py +278 -0
  444. mindspore/ops/_op_impl/_custom_op/matmul_cube_dense_right_impl.py +200 -0
  445. mindspore/ops/_op_impl/_custom_op/matmul_cube_fracz_left_cast_impl.py +334 -0
  446. mindspore/ops/_op_impl/_custom_op/matmul_cube_fracz_right_mul_impl.py +255 -0
  447. mindspore/ops/_op_impl/_custom_op/matmul_cube_impl.py +222 -0
  448. mindspore/ops/_op_impl/_custom_op/matmul_dds_grad_impl.py +644 -0
  449. mindspore/ops/_op_impl/_custom_op/matmul_dds_impl.py +488 -0
  450. mindspore/ops/_op_impl/_custom_op/matrix_combine_impl.py +87 -0
  451. mindspore/ops/_op_impl/_custom_op/minmax_update_perchannel.py +129 -0
  452. mindspore/ops/_op_impl/_custom_op/minmax_update_perlayer.py +121 -0
  453. mindspore/ops/_op_impl/_custom_op/transpose02314_impl.py +352 -0
  454. mindspore/ops/_op_impl/aicpu/__init__.py +441 -0
  455. mindspore/ops/_op_impl/aicpu/abs.py +36 -0
  456. mindspore/ops/_op_impl/aicpu/acos.py +32 -0
  457. mindspore/ops/_op_impl/aicpu/acos_grad.py +33 -0
  458. mindspore/ops/_op_impl/aicpu/acosh.py +34 -0
  459. mindspore/ops/_op_impl/aicpu/acosh_grad.py +35 -0
  460. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_2d.py +34 -0
  461. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_2d_grad.py +34 -0
  462. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_3d.py +39 -0
  463. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_3d_grad.py +39 -0
  464. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_2d.py +37 -0
  465. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_2d_grad.py +37 -0
  466. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_3d.py +42 -0
  467. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_3d_grad.py +152 -0
  468. mindspore/ops/_op_impl/aicpu/add.py +43 -0
  469. mindspore/ops/_op_impl/aicpu/add_n.py +41 -0
  470. mindspore/ops/_op_impl/aicpu/add_v2.py +40 -0
  471. mindspore/ops/_op_impl/aicpu/addcdiv.py +41 -0
  472. mindspore/ops/_op_impl/aicpu/addcmul.py +47 -0
  473. mindspore/ops/_op_impl/aicpu/adjust_contrastv2.py +32 -0
  474. mindspore/ops/_op_impl/aicpu/adjust_hue.py +31 -0
  475. mindspore/ops/_op_impl/aicpu/adjust_saturation.py +32 -0
  476. mindspore/ops/_op_impl/aicpu/affine_grid.py +33 -0
  477. mindspore/ops/_op_impl/aicpu/affine_grid_grad.py +35 -0
  478. mindspore/ops/_op_impl/aicpu/angle.py +31 -0
  479. mindspore/ops/_op_impl/aicpu/arg_max.py +75 -0
  480. mindspore/ops/_op_impl/aicpu/arg_min.py +75 -0
  481. mindspore/ops/_op_impl/aicpu/argmax_with_value.py +43 -0
  482. mindspore/ops/_op_impl/aicpu/argmin_with_value.py +43 -0
  483. mindspore/ops/_op_impl/aicpu/asin.py +32 -0
  484. mindspore/ops/_op_impl/aicpu/asin_grad.py +33 -0
  485. mindspore/ops/_op_impl/aicpu/asinh.py +34 -0
  486. mindspore/ops/_op_impl/aicpu/asinh_grad.py +35 -0
  487. mindspore/ops/_op_impl/aicpu/atanh.py +34 -0
  488. mindspore/ops/_op_impl/aicpu/avgpool_grad_v1.py +37 -0
  489. mindspore/ops/_op_impl/aicpu/avgpool_v1.py +36 -0
  490. mindspore/ops/_op_impl/aicpu/bartlett_window.py +36 -0
  491. mindspore/ops/_op_impl/aicpu/batch_matmul.py +43 -0
  492. mindspore/ops/_op_impl/aicpu/batch_norm_grad_grad.py +49 -0
  493. mindspore/ops/_op_impl/aicpu/bernoulli.py +48 -0
  494. mindspore/ops/_op_impl/aicpu/bessel_i0.py +31 -0
  495. mindspore/ops/_op_impl/aicpu/betainc.py +31 -0
  496. mindspore/ops/_op_impl/aicpu/bias_add.py +44 -0
  497. mindspore/ops/_op_impl/aicpu/bias_add_grad.py +42 -0
  498. mindspore/ops/_op_impl/aicpu/bincount.py +33 -0
  499. mindspore/ops/_op_impl/aicpu/blackman_window.py +36 -0
  500. mindspore/ops/_op_impl/aicpu/broadcast_to.py +58 -0
  501. mindspore/ops/_op_impl/aicpu/bucketize.py +34 -0
  502. mindspore/ops/_op_impl/aicpu/cache_swap_table.py +102 -0
  503. mindspore/ops/_op_impl/aicpu/cast.py +225 -0
  504. mindspore/ops/_op_impl/aicpu/cauchy.py +33 -0
  505. mindspore/ops/_op_impl/aicpu/channel_shuffle.py +40 -0
  506. mindspore/ops/_op_impl/aicpu/check_numerics.py +33 -0
  507. mindspore/ops/_op_impl/aicpu/cholesky.py +32 -0
  508. mindspore/ops/_op_impl/aicpu/cholesky_inverse.py +31 -0
  509. mindspore/ops/_op_impl/aicpu/cholesky_solve.py +33 -0
  510. mindspore/ops/_op_impl/aicpu/choleskygrad.py +32 -0
  511. mindspore/ops/_op_impl/aicpu/coalesce.py +37 -0
  512. mindspore/ops/_op_impl/aicpu/col2im.py +38 -0
  513. mindspore/ops/_op_impl/aicpu/combined_non_max_suppression.py +42 -0
  514. mindspore/ops/_op_impl/aicpu/compare_and_bitpack.py +37 -0
  515. mindspore/ops/_op_impl/aicpu/complex.py +32 -0
  516. mindspore/ops/_op_impl/aicpu/complex_abs.py +31 -0
  517. mindspore/ops/_op_impl/aicpu/compute_accidental_hits.py +44 -0
  518. mindspore/ops/_op_impl/aicpu/concat.py +57 -0
  519. mindspore/ops/_op_impl/aicpu/concat_offset.py +42 -0
  520. mindspore/ops/_op_impl/aicpu/concat_offset_v1.py +31 -0
  521. mindspore/ops/_op_impl/aicpu/conj.py +42 -0
  522. mindspore/ops/_op_impl/aicpu/conjugate_transpose.py +58 -0
  523. mindspore/ops/_op_impl/aicpu/cos.py +34 -0
  524. mindspore/ops/_op_impl/aicpu/cosh.py +34 -0
  525. mindspore/ops/_op_impl/aicpu/count_nonzero.py +43 -0
  526. mindspore/ops/_op_impl/aicpu/crop_and_resize.py +69 -0
  527. mindspore/ops/_op_impl/aicpu/crop_and_resize_grad_boxes.py +68 -0
  528. mindspore/ops/_op_impl/aicpu/crop_and_resize_grad_image.py +38 -0
  529. mindspore/ops/_op_impl/aicpu/cross.py +42 -0
  530. mindspore/ops/_op_impl/aicpu/csr_sparse_matrix_to_dense.py +48 -0
  531. mindspore/ops/_op_impl/aicpu/csr_sparse_matrix_to_sparse_tensor.py +51 -0
  532. mindspore/ops/_op_impl/aicpu/ctc_greedy_decoder.py +35 -0
  533. mindspore/ops/_op_impl/aicpu/ctc_loss_v2.py +43 -0
  534. mindspore/ops/_op_impl/aicpu/ctc_loss_v2_grad.py +45 -0
  535. mindspore/ops/_op_impl/aicpu/ctcloss.py +38 -0
  536. mindspore/ops/_op_impl/aicpu/cummax.py +41 -0
  537. mindspore/ops/_op_impl/aicpu/cumprod.py +58 -0
  538. mindspore/ops/_op_impl/aicpu/cumsum.py +58 -0
  539. mindspore/ops/_op_impl/aicpu/cumulative_logsumexp.py +36 -0
  540. mindspore/ops/_op_impl/aicpu/data_format_vec_permute.py +32 -0
  541. mindspore/ops/_op_impl/aicpu/deformable_offsets.py +38 -0
  542. mindspore/ops/_op_impl/aicpu/deformable_offsets_grad.py +43 -0
  543. mindspore/ops/_op_impl/aicpu/dense_to_csr_sparse_matrix.py +49 -0
  544. mindspore/ops/_op_impl/aicpu/dense_to_dense_set_operation.py +45 -0
  545. mindspore/ops/_op_impl/aicpu/dense_to_sparse_set_operation.py +48 -0
  546. mindspore/ops/_op_impl/aicpu/depth_to_space.py +44 -0
  547. mindspore/ops/_op_impl/aicpu/diag.py +36 -0
  548. mindspore/ops/_op_impl/aicpu/diag_part.py +36 -0
  549. mindspore/ops/_op_impl/aicpu/diagonal.py +35 -0
  550. mindspore/ops/_op_impl/aicpu/digamma.py +31 -0
  551. mindspore/ops/_op_impl/aicpu/div.py +41 -0
  552. mindspore/ops/_op_impl/aicpu/div_no_nan.py +35 -0
  553. mindspore/ops/_op_impl/aicpu/dropout2d.py +42 -0
  554. mindspore/ops/_op_impl/aicpu/dropout3d.py +42 -0
  555. mindspore/ops/_op_impl/aicpu/dropout_genmask.py +41 -0
  556. mindspore/ops/_op_impl/aicpu/dropout_genmask_v3.py +32 -0
  557. mindspore/ops/_op_impl/aicpu/dynamic_stitch.py +42 -0
  558. mindspore/ops/_op_impl/aicpu/edit_distance.py +56 -0
  559. mindspore/ops/_op_impl/aicpu/eig.py +35 -0
  560. mindspore/ops/_op_impl/aicpu/embedding_lookup.py +102 -0
  561. mindspore/ops/_op_impl/aicpu/end_of_sequence.py +30 -0
  562. mindspore/ops/_op_impl/aicpu/environ_create.py +28 -0
  563. mindspore/ops/_op_impl/aicpu/environ_destroy_all.py +28 -0
  564. mindspore/ops/_op_impl/aicpu/environ_get.py +41 -0
  565. mindspore/ops/_op_impl/aicpu/environ_set.py +40 -0
  566. mindspore/ops/_op_impl/aicpu/eps.py +32 -0
  567. mindspore/ops/_op_impl/aicpu/equal.py +41 -0
  568. mindspore/ops/_op_impl/aicpu/exp.py +37 -0
  569. mindspore/ops/_op_impl/aicpu/expand.py +45 -0
  570. mindspore/ops/_op_impl/aicpu/expand_dims.py +42 -0
  571. mindspore/ops/_op_impl/aicpu/expm1.py +34 -0
  572. mindspore/ops/_op_impl/aicpu/extract_glimpse.py +35 -0
  573. mindspore/ops/_op_impl/aicpu/eye.py +44 -0
  574. mindspore/ops/_op_impl/aicpu/fft_with_size.py +47 -0
  575. mindspore/ops/_op_impl/aicpu/fill_diagonal.py +39 -0
  576. mindspore/ops/_op_impl/aicpu/fill_v2.py +58 -0
  577. mindspore/ops/_op_impl/aicpu/flatten.py +43 -0
  578. mindspore/ops/_op_impl/aicpu/floor_div.py +38 -0
  579. mindspore/ops/_op_impl/aicpu/fmax.py +36 -0
  580. mindspore/ops/_op_impl/aicpu/fmin.py +37 -0
  581. mindspore/ops/_op_impl/aicpu/fractional_avg_pool.py +41 -0
  582. mindspore/ops/_op_impl/aicpu/fractional_avg_pool_grad.py +41 -0
  583. mindspore/ops/_op_impl/aicpu/fractional_max_pool.py +41 -0
  584. mindspore/ops/_op_impl/aicpu/fractional_max_pool3d_grad_with_fixed_ksize.py +43 -0
  585. mindspore/ops/_op_impl/aicpu/fractional_max_pool3d_with_fixed_ksize.py +65 -0
  586. mindspore/ops/_op_impl/aicpu/fractional_max_pool_grad.py +42 -0
  587. mindspore/ops/_op_impl/aicpu/fractional_max_pool_grad_with_fixed_ksize.py +42 -0
  588. mindspore/ops/_op_impl/aicpu/fractional_max_pool_with_fixed_ksize.py +49 -0
  589. mindspore/ops/_op_impl/aicpu/fse_decode.py +43 -0
  590. mindspore/ops/_op_impl/aicpu/fused_sparse_adam.py +46 -0
  591. mindspore/ops/_op_impl/aicpu/fused_sparse_ftrl.py +41 -0
  592. mindspore/ops/_op_impl/aicpu/fused_sparse_lazy_adam.py +46 -0
  593. mindspore/ops/_op_impl/aicpu/fused_sparse_proximal_adagrad.py +39 -0
  594. mindspore/ops/_op_impl/aicpu/gamma.py +38 -0
  595. mindspore/ops/_op_impl/aicpu/gather.py +46 -0
  596. mindspore/ops/_op_impl/aicpu/gather_d.py +79 -0
  597. mindspore/ops/_op_impl/aicpu/gather_d_grad_v2.py +79 -0
  598. mindspore/ops/_op_impl/aicpu/gather_grad.py +54 -0
  599. mindspore/ops/_op_impl/aicpu/gather_nd.py +56 -0
  600. mindspore/ops/_op_impl/aicpu/gcd.py +32 -0
  601. mindspore/ops/_op_impl/aicpu/generate_eod_mask.py +38 -0
  602. mindspore/ops/_op_impl/aicpu/geqrf.py +32 -0
  603. mindspore/ops/_op_impl/aicpu/get_next.py +39 -0
  604. mindspore/ops/_op_impl/aicpu/glu.py +33 -0
  605. mindspore/ops/_op_impl/aicpu/glu_grad.py +34 -0
  606. mindspore/ops/_op_impl/aicpu/greater.py +41 -0
  607. mindspore/ops/_op_impl/aicpu/greater_equal.py +41 -0
  608. mindspore/ops/_op_impl/aicpu/grid_sampler_2d.py +35 -0
  609. mindspore/ops/_op_impl/aicpu/grid_sampler_2d_grad.py +38 -0
  610. mindspore/ops/_op_impl/aicpu/grid_sampler_3d.py +34 -0
  611. mindspore/ops/_op_impl/aicpu/grid_sampler_3d_grad.py +38 -0
  612. mindspore/ops/_op_impl/aicpu/hamming_window.py +57 -0
  613. mindspore/ops/_op_impl/aicpu/hard_sigmoid.py +32 -0
  614. mindspore/ops/_op_impl/aicpu/hard_sigmoid_grad.py +33 -0
  615. mindspore/ops/_op_impl/aicpu/heaviside.py +40 -0
  616. mindspore/ops/_op_impl/aicpu/histogram.py +35 -0
  617. mindspore/ops/_op_impl/aicpu/hsv_to_rgb.py +32 -0
  618. mindspore/ops/_op_impl/aicpu/hypot.py +32 -0
  619. mindspore/ops/_op_impl/aicpu/identity.py +42 -0
  620. mindspore/ops/_op_impl/aicpu/identity_n.py +41 -0
  621. mindspore/ops/_op_impl/aicpu/igamma.py +30 -0
  622. mindspore/ops/_op_impl/aicpu/igammac.py +30 -0
  623. mindspore/ops/_op_impl/aicpu/igammagrada.py +30 -0
  624. mindspore/ops/_op_impl/aicpu/im2col.py +43 -0
  625. mindspore/ops/_op_impl/aicpu/imag.py +31 -0
  626. mindspore/ops/_op_impl/aicpu/index_fill.py +54 -0
  627. mindspore/ops/_op_impl/aicpu/index_put.py +50 -0
  628. mindspore/ops/_op_impl/aicpu/init_data_set_queue.py +27 -0
  629. mindspore/ops/_op_impl/aicpu/inplace_index_add.py +39 -0
  630. mindspore/ops/_op_impl/aicpu/instance_norm_v2.py +41 -0
  631. mindspore/ops/_op_impl/aicpu/instance_norm_v2_grad.py +44 -0
  632. mindspore/ops/_op_impl/aicpu/is_finite.py +40 -0
  633. mindspore/ops/_op_impl/aicpu/is_inf.py +31 -0
  634. mindspore/ops/_op_impl/aicpu/is_nan.py +31 -0
  635. mindspore/ops/_op_impl/aicpu/kldivloss.py +34 -0
  636. mindspore/ops/_op_impl/aicpu/kldivlossgrad.py +35 -0
  637. mindspore/ops/_op_impl/aicpu/layer_norm_grad_grad.py +47 -0
  638. mindspore/ops/_op_impl/aicpu/lcm.py +32 -0
  639. mindspore/ops/_op_impl/aicpu/left_shift.py +38 -0
  640. mindspore/ops/_op_impl/aicpu/less.py +41 -0
  641. mindspore/ops/_op_impl/aicpu/less_equal.py +41 -0
  642. mindspore/ops/_op_impl/aicpu/lgamma.py +33 -0
  643. mindspore/ops/_op_impl/aicpu/linear_sum_assignment.py +57 -0
  644. mindspore/ops/_op_impl/aicpu/linspace.py +33 -0
  645. mindspore/ops/_op_impl/aicpu/list_diff.py +50 -0
  646. mindspore/ops/_op_impl/aicpu/log.py +37 -0
  647. mindspore/ops/_op_impl/aicpu/log1p.py +34 -0
  648. mindspore/ops/_op_impl/aicpu/log_matrix_determinant.py +31 -0
  649. mindspore/ops/_op_impl/aicpu/log_normal_reverse.py +33 -0
  650. mindspore/ops/_op_impl/aicpu/log_uniform_candidate_sampler.py +37 -0
  651. mindspore/ops/_op_impl/aicpu/logical_xor.py +30 -0
  652. mindspore/ops/_op_impl/aicpu/logit.py +33 -0
  653. mindspore/ops/_op_impl/aicpu/logit_grad.py +34 -0
  654. mindspore/ops/_op_impl/aicpu/logspace.py +36 -0
  655. mindspore/ops/_op_impl/aicpu/lower_bound.py +47 -0
  656. mindspore/ops/_op_impl/aicpu/lstsq.py +34 -0
  657. mindspore/ops/_op_impl/aicpu/lu.py +39 -0
  658. mindspore/ops/_op_impl/aicpu/lu_solve.py +32 -0
  659. mindspore/ops/_op_impl/aicpu/lu_unpack.py +114 -0
  660. mindspore/ops/_op_impl/aicpu/lu_unpack_grad.py +49 -0
  661. mindspore/ops/_op_impl/aicpu/masked_fill.py +42 -0
  662. mindspore/ops/_op_impl/aicpu/masked_scatter.py +40 -0
  663. mindspore/ops/_op_impl/aicpu/masked_select.py +31 -0
  664. mindspore/ops/_op_impl/aicpu/masked_select_grad.py +35 -0
  665. mindspore/ops/_op_impl/aicpu/matmul.py +39 -0
  666. mindspore/ops/_op_impl/aicpu/matrix_band_part.py +59 -0
  667. mindspore/ops/_op_impl/aicpu/matrix_determinant.py +30 -0
  668. mindspore/ops/_op_impl/aicpu/matrix_diag_part_v3.py +54 -0
  669. mindspore/ops/_op_impl/aicpu/matrix_diag_v3.py +56 -0
  670. mindspore/ops/_op_impl/aicpu/matrix_exp.py +34 -0
  671. mindspore/ops/_op_impl/aicpu/matrix_inverse.py +31 -0
  672. mindspore/ops/_op_impl/aicpu/matrix_logarithm.py +31 -0
  673. mindspore/ops/_op_impl/aicpu/matrix_power.py +37 -0
  674. mindspore/ops/_op_impl/aicpu/matrix_set_diag_v3.py +54 -0
  675. mindspore/ops/_op_impl/aicpu/matrix_solve.py +35 -0
  676. mindspore/ops/_op_impl/aicpu/matrix_solve_ls.py +36 -0
  677. mindspore/ops/_op_impl/aicpu/matrix_triangular_solve.py +36 -0
  678. mindspore/ops/_op_impl/aicpu/max_pool3d_grad_with_argmax.py +60 -0
  679. mindspore/ops/_op_impl/aicpu/max_pool3d_with_argmax.py +59 -0
  680. mindspore/ops/_op_impl/aicpu/max_unpool2d.py +57 -0
  681. mindspore/ops/_op_impl/aicpu/max_unpool2d_grad.py +58 -0
  682. mindspore/ops/_op_impl/aicpu/max_unpool3d.py +57 -0
  683. mindspore/ops/_op_impl/aicpu/max_unpool3d_grad.py +58 -0
  684. mindspore/ops/_op_impl/aicpu/maximum_grad_grad.py +40 -0
  685. mindspore/ops/_op_impl/aicpu/maxpool_grad_v1.py +46 -0
  686. mindspore/ops/_op_impl/aicpu/maxpool_v1.py +42 -0
  687. mindspore/ops/_op_impl/aicpu/median.py +39 -0
  688. mindspore/ops/_op_impl/aicpu/median_grad.py +45 -0
  689. mindspore/ops/_op_impl/aicpu/meshgrid.py +41 -0
  690. mindspore/ops/_op_impl/aicpu/minimum_grad_grad.py +40 -0
  691. mindspore/ops/_op_impl/aicpu/mirror_pad.py +50 -0
  692. mindspore/ops/_op_impl/aicpu/mirror_pad_grad.py +48 -0
  693. mindspore/ops/_op_impl/aicpu/mul.py +43 -0
  694. mindspore/ops/_op_impl/aicpu/mul_no_nan.py +42 -0
  695. mindspore/ops/_op_impl/aicpu/multi_margin_loss.py +37 -0
  696. mindspore/ops/_op_impl/aicpu/multi_margin_loss_grad.py +41 -0
  697. mindspore/ops/_op_impl/aicpu/multilabel_margin_loss_grad.py +37 -0
  698. mindspore/ops/_op_impl/aicpu/multinomial.py +47 -0
  699. mindspore/ops/_op_impl/aicpu/multinomial_with_replacement.py +35 -0
  700. mindspore/ops/_op_impl/aicpu/mvlgamma.py +32 -0
  701. mindspore/ops/_op_impl/aicpu/mvlgamma_grad.py +33 -0
  702. mindspore/ops/_op_impl/aicpu/nan_to_num.py +34 -0
  703. mindspore/ops/_op_impl/aicpu/neg.py +36 -0
  704. mindspore/ops/_op_impl/aicpu/nextafter.py +32 -0
  705. mindspore/ops/_op_impl/aicpu/nllloss.py +38 -0
  706. mindspore/ops/_op_impl/aicpu/nllloss_grad.py +39 -0
  707. mindspore/ops/_op_impl/aicpu/no_repeat_ngram.py +34 -0
  708. mindspore/ops/_op_impl/aicpu/non_deterministic_ints.py +33 -0
  709. mindspore/ops/_op_impl/aicpu/non_max_suppression.py +36 -0
  710. mindspore/ops/_op_impl/aicpu/non_max_suppression_with_overlaps.py +35 -0
  711. mindspore/ops/_op_impl/aicpu/non_zero.py +43 -0
  712. mindspore/ops/_op_impl/aicpu/not_equal.py +39 -0
  713. mindspore/ops/_op_impl/aicpu/nth_element.py +39 -0
  714. mindspore/ops/_op_impl/aicpu/nuclear_norm.py +33 -0
  715. mindspore/ops/_op_impl/aicpu/one_hot.py +116 -0
  716. mindspore/ops/_op_impl/aicpu/ones_like.py +39 -0
  717. mindspore/ops/_op_impl/aicpu/orgqr.py +34 -0
  718. mindspore/ops/_op_impl/aicpu/pad_and_shift.py +33 -0
  719. mindspore/ops/_op_impl/aicpu/pad_v3.py +61 -0
  720. mindspore/ops/_op_impl/aicpu/pad_v3_grad.py +59 -0
  721. mindspore/ops/_op_impl/aicpu/padding.py +41 -0
  722. mindspore/ops/_op_impl/aicpu/parameterized_truncated_normal.py +54 -0
  723. mindspore/ops/_op_impl/aicpu/pdist_grad.py +33 -0
  724. mindspore/ops/_op_impl/aicpu/poisson.py +37 -0
  725. mindspore/ops/_op_impl/aicpu/polar.py +32 -0
  726. mindspore/ops/_op_impl/aicpu/polygamma.py +34 -0
  727. mindspore/ops/_op_impl/aicpu/pow.py +39 -0
  728. mindspore/ops/_op_impl/aicpu/print_tensor.py +39 -0
  729. mindspore/ops/_op_impl/aicpu/priority_replay_buffer.py +113 -0
  730. mindspore/ops/_op_impl/aicpu/qr.py +36 -0
  731. mindspore/ops/_op_impl/aicpu/quant_dtype_cast.py +40 -0
  732. mindspore/ops/_op_impl/aicpu/quantile.py +35 -0
  733. mindspore/ops/_op_impl/aicpu/ragged_range.py +49 -0
  734. mindspore/ops/_op_impl/aicpu/ragged_tensor_to_sparse.py +73 -0
  735. mindspore/ops/_op_impl/aicpu/ragged_tensor_to_tensor.py +74 -0
  736. mindspore/ops/_op_impl/aicpu/random_categorical.py +68 -0
  737. mindspore/ops/_op_impl/aicpu/random_choice_with_mask.py +36 -0
  738. mindspore/ops/_op_impl/aicpu/random_gamma.py +38 -0
  739. mindspore/ops/_op_impl/aicpu/random_poisson.py +134 -0
  740. mindspore/ops/_op_impl/aicpu/random_shuffle.py +47 -0
  741. mindspore/ops/_op_impl/aicpu/randperm.py +38 -0
  742. mindspore/ops/_op_impl/aicpu/randperm_v2.py +41 -0
  743. mindspore/ops/_op_impl/aicpu/range.py +36 -0
  744. mindspore/ops/_op_impl/aicpu/range_v2.py +35 -0
  745. mindspore/ops/_op_impl/aicpu/real.py +31 -0
  746. mindspore/ops/_op_impl/aicpu/real_div.py +40 -0
  747. mindspore/ops/_op_impl/aicpu/reciprocal.py +34 -0
  748. mindspore/ops/_op_impl/aicpu/reciprocal_grad.py +35 -0
  749. mindspore/ops/_op_impl/aicpu/reduce_mean.py +57 -0
  750. mindspore/ops/_op_impl/aicpu/reduce_prod.py +57 -0
  751. mindspore/ops/_op_impl/aicpu/reduce_sum.py +57 -0
  752. mindspore/ops/_op_impl/aicpu/relu_grad_v3.py +41 -0
  753. mindspore/ops/_op_impl/aicpu/relu_v3.py +38 -0
  754. mindspore/ops/_op_impl/aicpu/reservoir_replay_buffer.py +96 -0
  755. mindspore/ops/_op_impl/aicpu/reshape.py +42 -0
  756. mindspore/ops/_op_impl/aicpu/resize_area.py +40 -0
  757. mindspore/ops/_op_impl/aicpu/resize_bicubic.py +20 -0
  758. mindspore/ops/_op_impl/aicpu/resize_bicubic_grad.py +19 -0
  759. mindspore/ops/_op_impl/aicpu/resize_bilinear.py +32 -0
  760. mindspore/ops/_op_impl/aicpu/resize_bilinear_grad.py +32 -0
  761. mindspore/ops/_op_impl/aicpu/resize_nearest_neighbor_v2.py +36 -0
  762. mindspore/ops/_op_impl/aicpu/resize_nearest_neighbor_v2_grad.py +35 -0
  763. mindspore/ops/_op_impl/aicpu/resize_v2.py +68 -0
  764. mindspore/ops/_op_impl/aicpu/resize_v2_grad.py +68 -0
  765. mindspore/ops/_op_impl/aicpu/reverse_sequence.py +55 -0
  766. mindspore/ops/_op_impl/aicpu/reversev2.py +54 -0
  767. mindspore/ops/_op_impl/aicpu/rgb_to_hsv.py +32 -0
  768. mindspore/ops/_op_impl/aicpu/right_shift.py +38 -0
  769. mindspore/ops/_op_impl/aicpu/rnnt_loss.py +35 -0
  770. mindspore/ops/_op_impl/aicpu/round.py +34 -0
  771. mindspore/ops/_op_impl/aicpu/rsqrt.py +33 -0
  772. mindspore/ops/_op_impl/aicpu/rsqrt_grad.py +36 -0
  773. mindspore/ops/_op_impl/aicpu/sample_distorted_bounding_box_v2.py +49 -0
  774. mindspore/ops/_op_impl/aicpu/scale_and_translate.py +52 -0
  775. mindspore/ops/_op_impl/aicpu/scale_and_translate_grad.py +36 -0
  776. mindspore/ops/_op_impl/aicpu/scatter.py +79 -0
  777. mindspore/ops/_op_impl/aicpu/scatter_add_with_axis.py +53 -0
  778. mindspore/ops/_op_impl/aicpu/scatter_elements.py +39 -0
  779. mindspore/ops/_op_impl/aicpu/scatter_nd.py +59 -0
  780. mindspore/ops/_op_impl/aicpu/scatter_nd_max.py +54 -0
  781. mindspore/ops/_op_impl/aicpu/scatter_nd_min.py +54 -0
  782. mindspore/ops/_op_impl/aicpu/scatter_nd_update.py +59 -0
  783. mindspore/ops/_op_impl/aicpu/search_sorted.py +44 -0
  784. mindspore/ops/_op_impl/aicpu/segment_max.py +52 -0
  785. mindspore/ops/_op_impl/aicpu/segment_mean.py +56 -0
  786. mindspore/ops/_op_impl/aicpu/segment_min.py +52 -0
  787. mindspore/ops/_op_impl/aicpu/segment_prod.py +56 -0
  788. mindspore/ops/_op_impl/aicpu/segment_sum.py +56 -0
  789. mindspore/ops/_op_impl/aicpu/select.py +45 -0
  790. mindspore/ops/_op_impl/aicpu/self_adjoint_eig.py +34 -0
  791. mindspore/ops/_op_impl/aicpu/sequence_add.py +34 -0
  792. mindspore/ops/_op_impl/aicpu/sequence_add_offset.py +34 -0
  793. mindspore/ops/_op_impl/aicpu/sequence_addn.py +38 -0
  794. mindspore/ops/_op_impl/aicpu/sequence_concat.py +40 -0
  795. mindspore/ops/_op_impl/aicpu/sequence_stack.py +40 -0
  796. mindspore/ops/_op_impl/aicpu/set_size.py +38 -0
  797. mindspore/ops/_op_impl/aicpu/sign.py +36 -0
  798. mindspore/ops/_op_impl/aicpu/sin.py +34 -0
  799. mindspore/ops/_op_impl/aicpu/sinc.py +43 -0
  800. mindspore/ops/_op_impl/aicpu/sinh.py +34 -0
  801. mindspore/ops/_op_impl/aicpu/slice.py +59 -0
  802. mindspore/ops/_op_impl/aicpu/slice_grad.py +76 -0
  803. mindspore/ops/_op_impl/aicpu/smooth_l1_loss.py +35 -0
  804. mindspore/ops/_op_impl/aicpu/smooth_l1_loss_grad.py +37 -0
  805. mindspore/ops/_op_impl/aicpu/sort.py +39 -0
  806. mindspore/ops/_op_impl/aicpu/space_to_depth.py +44 -0
  807. mindspore/ops/_op_impl/aicpu/sparse_addmm.py +87 -0
  808. mindspore/ops/_op_impl/aicpu/sparse_apply_adagrad_da.py +80 -0
  809. mindspore/ops/_op_impl/aicpu/sparse_apply_centered_rms_prop.py +105 -0
  810. mindspore/ops/_op_impl/aicpu/sparse_apply_momentum.py +80 -0
  811. mindspore/ops/_op_impl/aicpu/sparse_apply_proximal_gradient_descent.py +79 -0
  812. mindspore/ops/_op_impl/aicpu/sparse_concat.py +59 -0
  813. mindspore/ops/_op_impl/aicpu/sparse_cross.py +42 -0
  814. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_add.py +58 -0
  815. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_div.py +58 -0
  816. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_mul.py +58 -0
  817. mindspore/ops/_op_impl/aicpu/sparse_fill_empty_rows.py +63 -0
  818. mindspore/ops/_op_impl/aicpu/sparse_fill_empty_rows_grad.py +45 -0
  819. mindspore/ops/_op_impl/aicpu/sparse_matrix_mat_mul.py +56 -0
  820. mindspore/ops/_op_impl/aicpu/sparse_matrix_nnz.py +81 -0
  821. mindspore/ops/_op_impl/aicpu/sparse_matrix_transpose.py +116 -0
  822. mindspore/ops/_op_impl/aicpu/sparse_reorder.py +56 -0
  823. mindspore/ops/_op_impl/aicpu/sparse_reshape.py +34 -0
  824. mindspore/ops/_op_impl/aicpu/sparse_segment_mean_grad.py +36 -0
  825. mindspore/ops/_op_impl/aicpu/sparse_segment_mean_with_num_segments.py +44 -0
  826. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n.py +43 -0
  827. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n_grad.py +38 -0
  828. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n_with_num_segments.py +44 -0
  829. mindspore/ops/_op_impl/aicpu/sparse_segment_sum.py +49 -0
  830. mindspore/ops/_op_impl/aicpu/sparse_segment_sum_with_num_segments.py +68 -0
  831. mindspore/ops/_op_impl/aicpu/sparse_slice.py +63 -0
  832. mindspore/ops/_op_impl/aicpu/sparse_slice_grad.py +61 -0
  833. mindspore/ops/_op_impl/aicpu/sparse_softmax.py +33 -0
  834. mindspore/ops/_op_impl/aicpu/sparse_softmax_cross_entropy_with_logits_v2.py +35 -0
  835. mindspore/ops/_op_impl/aicpu/sparse_sparse_maximum.py +53 -0
  836. mindspore/ops/_op_impl/aicpu/sparse_sparse_minimum.py +53 -0
  837. mindspore/ops/_op_impl/aicpu/sparse_tensor_dense_add.py +84 -0
  838. mindspore/ops/_op_impl/aicpu/sparse_tensor_dense_mat_mul.py +190 -0
  839. mindspore/ops/_op_impl/aicpu/sparse_tensor_to_csr_sparse_matrix.py +51 -0
  840. mindspore/ops/_op_impl/aicpu/sparse_to_dense_v2.py +73 -0
  841. mindspore/ops/_op_impl/aicpu/split.py +45 -0
  842. mindspore/ops/_op_impl/aicpu/sqrt.py +34 -0
  843. mindspore/ops/_op_impl/aicpu/sqrt_grad.py +35 -0
  844. mindspore/ops/_op_impl/aicpu/square.py +35 -0
  845. mindspore/ops/_op_impl/aicpu/squared_difference.py +37 -0
  846. mindspore/ops/_op_impl/aicpu/squeeze.py +42 -0
  847. mindspore/ops/_op_impl/aicpu/sspaddmm.py +97 -0
  848. mindspore/ops/_op_impl/aicpu/stack.py +45 -0
  849. mindspore/ops/_op_impl/aicpu/stack_push_pop.py +87 -0
  850. mindspore/ops/_op_impl/aicpu/standard_laplace.py +34 -0
  851. mindspore/ops/_op_impl/aicpu/standard_normal.py +34 -0
  852. mindspore/ops/_op_impl/aicpu/stateless_dropout_genmask.py +37 -0
  853. mindspore/ops/_op_impl/aicpu/stft.py +70 -0
  854. mindspore/ops/_op_impl/aicpu/strided_slice.py +43 -0
  855. mindspore/ops/_op_impl/aicpu/strided_slice_grad.py +50 -0
  856. mindspore/ops/_op_impl/aicpu/sub.py +41 -0
  857. mindspore/ops/_op_impl/aicpu/sub_and_filter.py +36 -0
  858. mindspore/ops/_op_impl/aicpu/tan.py +34 -0
  859. mindspore/ops/_op_impl/aicpu/tanh.py +34 -0
  860. mindspore/ops/_op_impl/aicpu/tanh_grad.py +35 -0
  861. mindspore/ops/_op_impl/aicpu/tensor_scatter_update.py +59 -0
  862. mindspore/ops/_op_impl/aicpu/tile.py +56 -0
  863. mindspore/ops/_op_impl/aicpu/topk.py +34 -0
  864. mindspore/ops/_op_impl/aicpu/trace.py +40 -0
  865. mindspore/ops/_op_impl/aicpu/tracegrad.py +41 -0
  866. mindspore/ops/_op_impl/aicpu/trans_data.py +35 -0
  867. mindspore/ops/_op_impl/aicpu/transpose.py +58 -0
  868. mindspore/ops/_op_impl/aicpu/tridiagonal_matmul.py +42 -0
  869. mindspore/ops/_op_impl/aicpu/tridiagonal_solve.py +35 -0
  870. mindspore/ops/_op_impl/aicpu/tril.py +42 -0
  871. mindspore/ops/_op_impl/aicpu/tril_indices.py +34 -0
  872. mindspore/ops/_op_impl/aicpu/triplet_margin_loss.py +62 -0
  873. mindspore/ops/_op_impl/aicpu/triu.py +43 -0
  874. mindspore/ops/_op_impl/aicpu/triu_indices.py +34 -0
  875. mindspore/ops/_op_impl/aicpu/truncated_normal.py +39 -0
  876. mindspore/ops/_op_impl/aicpu/uniform.py +36 -0
  877. mindspore/ops/_op_impl/aicpu/uniform_candidate_sampler.py +41 -0
  878. mindspore/ops/_op_impl/aicpu/uniform_int.py +36 -0
  879. mindspore/ops/_op_impl/aicpu/uniform_real.py +33 -0
  880. mindspore/ops/_op_impl/aicpu/unique.py +31 -0
  881. mindspore/ops/_op_impl/aicpu/unique_consecutive.py +47 -0
  882. mindspore/ops/_op_impl/aicpu/unique_with_pad.py +32 -0
  883. mindspore/ops/_op_impl/aicpu/unravel_index.py +32 -0
  884. mindspore/ops/_op_impl/aicpu/unsorted_segment_prod.py +53 -0
  885. mindspore/ops/_op_impl/aicpu/unsorted_segment_sum.py +57 -0
  886. mindspore/ops/_op_impl/aicpu/unstack.py +45 -0
  887. mindspore/ops/_op_impl/aicpu/update_cache.py +44 -0
  888. mindspore/ops/_op_impl/aicpu/upper_bound.py +47 -0
  889. mindspore/ops/_op_impl/aicpu/upsample_nearest_3d.py +42 -0
  890. mindspore/ops/_op_impl/aicpu/upsample_nearest_3d_grad.py +49 -0
  891. mindspore/ops/_op_impl/aicpu/upsample_trilinear_3d.py +40 -0
  892. mindspore/ops/_op_impl/aicpu/upsample_trilinear_3d_grad.py +50 -0
  893. mindspore/ops/_op_impl/aicpu/xdivy.py +35 -0
  894. mindspore/ops/_op_impl/aicpu/xlogy.py +33 -0
  895. mindspore/ops/_op_impl/aicpu/zeros_like.py +42 -0
  896. mindspore/ops/_op_impl/aicpu/zeta.py +31 -0
  897. mindspore/ops/_op_impl/akg/__init__.py +19 -0
  898. mindspore/ops/_op_impl/akg/ascend/__init__.py +48 -0
  899. mindspore/ops/_op_impl/akg/ascend/abs.py +35 -0
  900. mindspore/ops/_op_impl/akg/ascend/add.py +42 -0
  901. mindspore/ops/_op_impl/akg/ascend/add_n.py +37 -0
  902. mindspore/ops/_op_impl/akg/ascend/batchmatmul.py +33 -0
  903. mindspore/ops/_op_impl/akg/ascend/cast.py +46 -0
  904. mindspore/ops/_op_impl/akg/ascend/equal.py +35 -0
  905. mindspore/ops/_op_impl/akg/ascend/exp.py +35 -0
  906. mindspore/ops/_op_impl/akg/ascend/expand_dims.py +33 -0
  907. mindspore/ops/_op_impl/akg/ascend/greater.py +34 -0
  908. mindspore/ops/_op_impl/akg/ascend/greater_equal.py +35 -0
  909. mindspore/ops/_op_impl/akg/ascend/less.py +31 -0
  910. mindspore/ops/_op_impl/akg/ascend/less_equal.py +35 -0
  911. mindspore/ops/_op_impl/akg/ascend/load_im2col.py +33 -0
  912. mindspore/ops/_op_impl/akg/ascend/log.py +34 -0
  913. mindspore/ops/_op_impl/akg/ascend/maximum.py +36 -0
  914. mindspore/ops/_op_impl/akg/ascend/minimum.py +39 -0
  915. mindspore/ops/_op_impl/akg/ascend/mul.py +41 -0
  916. mindspore/ops/_op_impl/akg/ascend/neg.py +37 -0
  917. mindspore/ops/_op_impl/akg/ascend/pow.py +35 -0
  918. mindspore/ops/_op_impl/akg/ascend/prod_force_se_a.py +33 -0
  919. mindspore/ops/_op_impl/akg/ascend/real_div.py +36 -0
  920. mindspore/ops/_op_impl/akg/ascend/reciprocal.py +32 -0
  921. mindspore/ops/_op_impl/akg/ascend/reduce_max.py +32 -0
  922. mindspore/ops/_op_impl/akg/ascend/reduce_min.py +32 -0
  923. mindspore/ops/_op_impl/akg/ascend/reduce_sum.py +37 -0
  924. mindspore/ops/_op_impl/akg/ascend/rsqrt.py +35 -0
  925. mindspore/ops/_op_impl/akg/ascend/select.py +37 -0
  926. mindspore/ops/_op_impl/akg/ascend/sqrt.py +35 -0
  927. mindspore/ops/_op_impl/akg/ascend/square.py +35 -0
  928. mindspore/ops/_op_impl/akg/ascend/sub.py +42 -0
  929. mindspore/ops/_op_impl/akg/cpu/__init__.py +23 -0
  930. mindspore/ops/_op_impl/akg/cpu/coo2csr.py +29 -0
  931. mindspore/ops/_op_impl/akg/cpu/csr2coo.py +29 -0
  932. mindspore/ops/_op_impl/akg/cpu/csr_gather.py +33 -0
  933. mindspore/ops/_op_impl/akg/cpu/csr_mm.py +34 -0
  934. mindspore/ops/_op_impl/akg/cpu/csr_mul.py +33 -0
  935. mindspore/ops/_op_impl/akg/cpu/csr_mv.py +33 -0
  936. mindspore/ops/_op_impl/akg/cpu/csr_reduce_sum.py +31 -0
  937. mindspore/ops/_op_impl/akg/gpu/__init__.py +24 -0
  938. mindspore/ops/_op_impl/akg/gpu/coo2csr.py +29 -0
  939. mindspore/ops/_op_impl/akg/gpu/csr2coo.py +29 -0
  940. mindspore/ops/_op_impl/akg/gpu/csr_div.py +36 -0
  941. mindspore/ops/_op_impl/akg/gpu/csr_gather.py +33 -0
  942. mindspore/ops/_op_impl/akg/gpu/csr_mm.py +37 -0
  943. mindspore/ops/_op_impl/akg/gpu/csr_mul.py +36 -0
  944. mindspore/ops/_op_impl/akg/gpu/csr_mv.py +36 -0
  945. mindspore/ops/_op_impl/akg/gpu/csr_reduce_sum.py +33 -0
  946. mindspore/ops/_op_impl/cpu/__init__.py +78 -0
  947. mindspore/ops/_op_impl/cpu/adam.py +49 -0
  948. mindspore/ops/_op_impl/cpu/adam_weight_decay.py +47 -0
  949. mindspore/ops/_op_impl/cpu/arg_max.py +30 -0
  950. mindspore/ops/_op_impl/cpu/arg_max_with_value.py +31 -0
  951. mindspore/ops/_op_impl/cpu/arg_min_with_value.py +31 -0
  952. mindspore/ops/_op_impl/cpu/buffer_append.py +28 -0
  953. mindspore/ops/_op_impl/cpu/buffer_get.py +28 -0
  954. mindspore/ops/_op_impl/cpu/buffer_sample.py +28 -0
  955. mindspore/ops/_op_impl/cpu/cast.py +171 -0
  956. mindspore/ops/_op_impl/cpu/concat_offset.py +38 -0
  957. mindspore/ops/_op_impl/cpu/conv2d.py +30 -0
  958. mindspore/ops/_op_impl/cpu/conv3d.py +30 -0
  959. mindspore/ops/_op_impl/cpu/div.py +32 -0
  960. mindspore/ops/_op_impl/cpu/dropout.py +31 -0
  961. mindspore/ops/_op_impl/cpu/dropout_grad.py +30 -0
  962. mindspore/ops/_op_impl/cpu/dynamic_shape.py +42 -0
  963. mindspore/ops/_op_impl/cpu/dynamic_stitch.py +41 -0
  964. mindspore/ops/_op_impl/cpu/equal_count.py +30 -0
  965. mindspore/ops/_op_impl/cpu/gather_d.py +49 -0
  966. mindspore/ops/_op_impl/cpu/gather_d_grad.py +38 -0
  967. mindspore/ops/_op_impl/cpu/gather_d_grad_v2.py +40 -0
  968. mindspore/ops/_op_impl/cpu/gather_v2.py +40 -0
  969. mindspore/ops/_op_impl/cpu/hsigmoid.py +33 -0
  970. mindspore/ops/_op_impl/cpu/hsigmoid_grad.py +34 -0
  971. mindspore/ops/_op_impl/cpu/hswish.py +32 -0
  972. mindspore/ops/_op_impl/cpu/hswish_grad.py +33 -0
  973. mindspore/ops/_op_impl/cpu/identity_n.py +40 -0
  974. mindspore/ops/_op_impl/cpu/is_finite.py +39 -0
  975. mindspore/ops/_op_impl/cpu/l2loss.py +30 -0
  976. mindspore/ops/_op_impl/cpu/layer_norm.py +36 -0
  977. mindspore/ops/_op_impl/cpu/layer_norm_grad.py +38 -0
  978. mindspore/ops/_op_impl/cpu/maximum.py +35 -0
  979. mindspore/ops/_op_impl/cpu/maximum_grad.py +47 -0
  980. mindspore/ops/_op_impl/cpu/minimum.py +40 -0
  981. mindspore/ops/_op_impl/cpu/minimum_grad.py +51 -0
  982. mindspore/ops/_op_impl/cpu/mirror_pad.py +36 -0
  983. mindspore/ops/_op_impl/cpu/mirror_pad_grad.py +36 -0
  984. mindspore/ops/_op_impl/cpu/mul.py +32 -0
  985. mindspore/ops/_op_impl/cpu/one_hot.py +31 -0
  986. mindspore/ops/_op_impl/cpu/pad.py +32 -0
  987. mindspore/ops/_op_impl/cpu/pow.py +32 -0
  988. mindspore/ops/_op_impl/cpu/priority_replay_buffer.py +42 -0
  989. mindspore/ops/_op_impl/cpu/pyexecute.py +29 -0
  990. mindspore/ops/_op_impl/cpu/pyfunc.py +29 -0
  991. mindspore/ops/_op_impl/cpu/range.py +34 -0
  992. mindspore/ops/_op_impl/cpu/real_div.py +33 -0
  993. mindspore/ops/_op_impl/cpu/reduce_all.py +29 -0
  994. mindspore/ops/_op_impl/cpu/reduce_any.py +29 -0
  995. mindspore/ops/_op_impl/cpu/reduce_max.py +32 -0
  996. mindspore/ops/_op_impl/cpu/reduce_mean.py +40 -0
  997. mindspore/ops/_op_impl/cpu/reduce_min.py +32 -0
  998. mindspore/ops/_op_impl/cpu/reduce_prod.py +40 -0
  999. mindspore/ops/_op_impl/cpu/reduce_std.py +31 -0
  1000. mindspore/ops/_op_impl/cpu/reduce_sum.py +41 -0
  1001. mindspore/ops/_op_impl/cpu/space_to_batch_nd.py +38 -0
  1002. mindspore/ops/_op_impl/cpu/sparse_slice.py +62 -0
  1003. mindspore/ops/_op_impl/cpu/sparse_slice_grad.py +60 -0
  1004. mindspore/ops/_op_impl/cpu/split.py +34 -0
  1005. mindspore/ops/_op_impl/cpu/sspaddmm.py +95 -0
  1006. mindspore/ops/_op_impl/cpu/stack.py +38 -0
  1007. mindspore/ops/_op_impl/cpu/sub.py +32 -0
  1008. mindspore/ops/_op_impl/cpu/tensor_copy_slices.py +41 -0
  1009. mindspore/ops/_op_impl/cpu/tile.py +37 -0
  1010. mindspore/ops/_op_impl/cpu/top_k.py +31 -0
  1011. mindspore/ops/_op_impl/cpu/transpose.py +39 -0
  1012. mindspore/ops/_primitive_cache.py +90 -0
  1013. mindspore/ops/_register_for_op.py +73 -0
  1014. mindspore/ops/_utils/__init__.py +20 -0
  1015. mindspore/ops/_utils/utils.py +147 -0
  1016. mindspore/ops/_vmap/__init__.py +25 -0
  1017. mindspore/ops/_vmap/vmap_array_ops.py +2149 -0
  1018. mindspore/ops/_vmap/vmap_base.py +533 -0
  1019. mindspore/ops/_vmap/vmap_convolution_ops.py +441 -0
  1020. mindspore/ops/_vmap/vmap_debug_ops.py +50 -0
  1021. mindspore/ops/_vmap/vmap_grad_math_ops.py +274 -0
  1022. mindspore/ops/_vmap/vmap_grad_nn_ops.py +806 -0
  1023. mindspore/ops/_vmap/vmap_image_ops.py +194 -0
  1024. mindspore/ops/_vmap/vmap_math_ops.py +993 -0
  1025. mindspore/ops/_vmap/vmap_nn_ops.py +2250 -0
  1026. mindspore/ops/_vmap/vmap_other_ops.py +105 -0
  1027. mindspore/ops/_vmap/vmap_random_ops.py +122 -0
  1028. mindspore/ops/_vmap/vmap_sparse_ops.py +89 -0
  1029. mindspore/ops/auto_generate/__init__.py +31 -0
  1030. mindspore/ops/auto_generate/cpp_create_prim_instance_helper.py +309 -0
  1031. mindspore/ops/auto_generate/gen_arg_dtype_cast.py +252 -0
  1032. mindspore/ops/auto_generate/gen_arg_handler.py +197 -0
  1033. mindspore/ops/auto_generate/gen_extend_func.py +1701 -0
  1034. mindspore/ops/auto_generate/gen_ops_def.py +8482 -0
  1035. mindspore/ops/auto_generate/gen_ops_prim.py +16704 -0
  1036. mindspore/ops/auto_generate/pyboost_inner_prim.py +549 -0
  1037. mindspore/ops/composite/__init__.py +71 -0
  1038. mindspore/ops/composite/base.py +1318 -0
  1039. mindspore/ops/composite/env_ops.py +41 -0
  1040. mindspore/ops/composite/math_ops.py +125 -0
  1041. mindspore/ops/composite/multitype_ops/__init__.py +77 -0
  1042. mindspore/ops/composite/multitype_ops/_compile_utils.py +1459 -0
  1043. mindspore/ops/composite/multitype_ops/_constexpr_utils.py +897 -0
  1044. mindspore/ops/composite/multitype_ops/add_impl.py +606 -0
  1045. mindspore/ops/composite/multitype_ops/bitwise_and_impl.py +56 -0
  1046. mindspore/ops/composite/multitype_ops/bitwise_or_impl.py +56 -0
  1047. mindspore/ops/composite/multitype_ops/bitwise_xor_impl.py +56 -0
  1048. mindspore/ops/composite/multitype_ops/div_impl.py +189 -0
  1049. mindspore/ops/composite/multitype_ops/equal_impl.py +335 -0
  1050. mindspore/ops/composite/multitype_ops/floordiv_impl.py +88 -0
  1051. mindspore/ops/composite/multitype_ops/getitem_impl.py +400 -0
  1052. mindspore/ops/composite/multitype_ops/greater_equal_impl.py +109 -0
  1053. mindspore/ops/composite/multitype_ops/greater_impl.py +110 -0
  1054. mindspore/ops/composite/multitype_ops/in_impl.py +196 -0
  1055. mindspore/ops/composite/multitype_ops/left_shift_impl.py +37 -0
  1056. mindspore/ops/composite/multitype_ops/less_equal_impl.py +111 -0
  1057. mindspore/ops/composite/multitype_ops/less_impl.py +112 -0
  1058. mindspore/ops/composite/multitype_ops/logic_not_impl.py +113 -0
  1059. mindspore/ops/composite/multitype_ops/logical_and_impl.py +60 -0
  1060. mindspore/ops/composite/multitype_ops/logical_or_impl.py +61 -0
  1061. mindspore/ops/composite/multitype_ops/mod_impl.py +86 -0
  1062. mindspore/ops/composite/multitype_ops/mul_impl.py +294 -0
  1063. mindspore/ops/composite/multitype_ops/negative_impl.py +79 -0
  1064. mindspore/ops/composite/multitype_ops/not_equal_impl.py +290 -0
  1065. mindspore/ops/composite/multitype_ops/not_in_impl.py +196 -0
  1066. mindspore/ops/composite/multitype_ops/ones_like_impl.py +96 -0
  1067. mindspore/ops/composite/multitype_ops/pow_impl.py +87 -0
  1068. mindspore/ops/composite/multitype_ops/right_shift_impl.py +37 -0
  1069. mindspore/ops/composite/multitype_ops/setitem_impl.py +884 -0
  1070. mindspore/ops/composite/multitype_ops/sub_impl.py +116 -0
  1071. mindspore/ops/composite/multitype_ops/uadd_impl.py +29 -0
  1072. mindspore/ops/composite/multitype_ops/zeros_like_impl.py +228 -0
  1073. mindspore/ops/deprecated.py +315 -0
  1074. mindspore/ops/function/__init__.py +782 -0
  1075. mindspore/ops/function/array_func.py +7226 -0
  1076. mindspore/ops/function/clip_func.py +384 -0
  1077. mindspore/ops/function/debug_func.py +181 -0
  1078. mindspore/ops/function/fft_func.py +44 -0
  1079. mindspore/ops/function/grad/__init__.py +34 -0
  1080. mindspore/ops/function/grad/grad_func.py +1425 -0
  1081. mindspore/ops/function/image_func.py +292 -0
  1082. mindspore/ops/function/linalg_func.py +416 -0
  1083. mindspore/ops/function/math_func.py +12228 -0
  1084. mindspore/ops/function/nn_func.py +8609 -0
  1085. mindspore/ops/function/other_func.py +115 -0
  1086. mindspore/ops/function/parameter_func.py +134 -0
  1087. mindspore/ops/function/random_func.py +1715 -0
  1088. mindspore/ops/function/reshard_func.py +104 -0
  1089. mindspore/ops/function/sparse_func.py +884 -0
  1090. mindspore/ops/function/sparse_unary_func.py +2422 -0
  1091. mindspore/ops/function/spectral_func.py +150 -0
  1092. mindspore/ops/function/vmap_func.py +117 -0
  1093. mindspore/ops/functional.py +464 -0
  1094. mindspore/ops/op_info_register.py +1572 -0
  1095. mindspore/ops/operations/__init__.py +722 -0
  1096. mindspore/ops/operations/_csr_ops.py +403 -0
  1097. mindspore/ops/operations/_custom_grad.py +181 -0
  1098. mindspore/ops/operations/_embedding_cache_ops.py +307 -0
  1099. mindspore/ops/operations/_grad_ops.py +2978 -0
  1100. mindspore/ops/operations/_infer_ops.py +19 -0
  1101. mindspore/ops/operations/_inner_ops.py +2544 -0
  1102. mindspore/ops/operations/_map_tensor_ops.py +112 -0
  1103. mindspore/ops/operations/_ms_kernel.py +601 -0
  1104. mindspore/ops/operations/_ocr_ops.py +379 -0
  1105. mindspore/ops/operations/_opaque_predicate_registry.py +41 -0
  1106. mindspore/ops/operations/_pyfunc_registry.py +58 -0
  1107. mindspore/ops/operations/_quant_ops.py +1844 -0
  1108. mindspore/ops/operations/_rl_inner_ops.py +1231 -0
  1109. mindspore/ops/operations/_scalar_ops.py +106 -0
  1110. mindspore/ops/operations/_sequence_ops.py +1155 -0
  1111. mindspore/ops/operations/_sparse_grad_ops.py +56 -0
  1112. mindspore/ops/operations/_tensor_array.py +359 -0
  1113. mindspore/ops/operations/_thor_ops.py +807 -0
  1114. mindspore/ops/operations/array_ops.py +6124 -0
  1115. mindspore/ops/operations/comm_ops.py +1985 -0
  1116. mindspore/ops/operations/control_ops.py +127 -0
  1117. mindspore/ops/operations/custom_ops.py +1129 -0
  1118. mindspore/ops/operations/debug_ops.py +678 -0
  1119. mindspore/ops/operations/image_ops.py +1041 -0
  1120. mindspore/ops/operations/inner_ops.py +697 -0
  1121. mindspore/ops/operations/linalg_ops.py +95 -0
  1122. mindspore/ops/operations/manually_defined/__init__.py +24 -0
  1123. mindspore/ops/operations/manually_defined/_inner.py +73 -0
  1124. mindspore/ops/operations/manually_defined/ops_def.py +2271 -0
  1125. mindspore/ops/operations/math_ops.py +5095 -0
  1126. mindspore/ops/operations/nn_ops.py +9575 -0
  1127. mindspore/ops/operations/other_ops.py +874 -0
  1128. mindspore/ops/operations/random_ops.py +1288 -0
  1129. mindspore/ops/operations/reshard_ops.py +53 -0
  1130. mindspore/ops/operations/rl_ops.py +288 -0
  1131. mindspore/ops/operations/sparse_ops.py +2753 -0
  1132. mindspore/ops/operations/spectral_ops.py +111 -0
  1133. mindspore/ops/primitive.py +1046 -0
  1134. mindspore/ops/signature.py +54 -0
  1135. mindspore/ops/vm_impl_registry.py +91 -0
  1136. mindspore/ops_generate/__init__.py +27 -0
  1137. mindspore/ops_generate/arg_dtype_cast.py +252 -0
  1138. mindspore/ops_generate/arg_handler.py +197 -0
  1139. mindspore/ops_generate/gen_aclnn_implement.py +263 -0
  1140. mindspore/ops_generate/gen_constants.py +36 -0
  1141. mindspore/ops_generate/gen_ops.py +1099 -0
  1142. mindspore/ops_generate/gen_ops_inner_prim.py +131 -0
  1143. mindspore/ops_generate/gen_pyboost_func.py +1052 -0
  1144. mindspore/ops_generate/gen_utils.py +209 -0
  1145. mindspore/ops_generate/op_proto.py +145 -0
  1146. mindspore/ops_generate/pyboost_utils.py +367 -0
  1147. mindspore/ops_generate/template.py +261 -0
  1148. mindspore/parallel/__init__.py +30 -0
  1149. mindspore/parallel/_auto_parallel_context.py +1486 -0
  1150. mindspore/parallel/_cell_wrapper.py +174 -0
  1151. mindspore/parallel/_cost_model_context.py +700 -0
  1152. mindspore/parallel/_dp_allreduce_fusion.py +159 -0
  1153. mindspore/parallel/_offload_context.py +275 -0
  1154. mindspore/parallel/_parallel_serialization.py +561 -0
  1155. mindspore/parallel/_ps_context.py +242 -0
  1156. mindspore/parallel/_recovery_context.py +110 -0
  1157. mindspore/parallel/_tensor.py +730 -0
  1158. mindspore/parallel/_transformer/__init__.py +35 -0
  1159. mindspore/parallel/_transformer/layers.py +765 -0
  1160. mindspore/parallel/_transformer/loss.py +251 -0
  1161. mindspore/parallel/_transformer/moe.py +693 -0
  1162. mindspore/parallel/_transformer/op_parallel_config.py +222 -0
  1163. mindspore/parallel/_transformer/transformer.py +3119 -0
  1164. mindspore/parallel/_utils.py +612 -0
  1165. mindspore/parallel/algo_parameter_config.py +400 -0
  1166. mindspore/parallel/checkpoint_transform.py +650 -0
  1167. mindspore/parallel/cluster/__init__.py +15 -0
  1168. mindspore/parallel/cluster/process_entity/__init__.py +18 -0
  1169. mindspore/parallel/cluster/process_entity/_api.py +352 -0
  1170. mindspore/parallel/cluster/process_entity/_utils.py +101 -0
  1171. mindspore/parallel/cluster/run.py +136 -0
  1172. mindspore/parallel/mpi/__init__.py +14 -0
  1173. mindspore/parallel/mpi/_mpi_config.py +116 -0
  1174. mindspore/parallel/parameter_broadcast.py +151 -0
  1175. mindspore/parallel/shard.py +481 -0
  1176. mindspore/parallel/transform_safetensors.py +993 -0
  1177. mindspore/profiler/__init__.py +28 -0
  1178. mindspore/profiler/common/__init__.py +14 -0
  1179. mindspore/profiler/common/constant.py +29 -0
  1180. mindspore/profiler/common/exceptions/__init__.py +14 -0
  1181. mindspore/profiler/common/exceptions/error_code.py +83 -0
  1182. mindspore/profiler/common/exceptions/exceptions.py +286 -0
  1183. mindspore/profiler/common/process_pool.py +41 -0
  1184. mindspore/profiler/common/registry.py +47 -0
  1185. mindspore/profiler/common/singleton.py +28 -0
  1186. mindspore/profiler/common/struct_type.py +118 -0
  1187. mindspore/profiler/common/util.py +472 -0
  1188. mindspore/profiler/common/validator/__init__.py +14 -0
  1189. mindspore/profiler/common/validator/validate_path.py +84 -0
  1190. mindspore/profiler/dynamic_profiler.py +694 -0
  1191. mindspore/profiler/envprofiling.py +254 -0
  1192. mindspore/profiler/parser/__init__.py +14 -0
  1193. mindspore/profiler/parser/aicpu_data_parser.py +272 -0
  1194. mindspore/profiler/parser/ascend_analysis/__init__.py +14 -0
  1195. mindspore/profiler/parser/ascend_analysis/constant.py +71 -0
  1196. mindspore/profiler/parser/ascend_analysis/file_manager.py +180 -0
  1197. mindspore/profiler/parser/ascend_analysis/function_event.py +185 -0
  1198. mindspore/profiler/parser/ascend_analysis/fwk_cann_parser.py +136 -0
  1199. mindspore/profiler/parser/ascend_analysis/fwk_file_parser.py +131 -0
  1200. mindspore/profiler/parser/ascend_analysis/msprof_timeline_parser.py +104 -0
  1201. mindspore/profiler/parser/ascend_analysis/path_manager.py +313 -0
  1202. mindspore/profiler/parser/ascend_analysis/profiler_info_parser.py +123 -0
  1203. mindspore/profiler/parser/ascend_analysis/tlv_decoder.py +86 -0
  1204. mindspore/profiler/parser/ascend_analysis/trace_event_manager.py +75 -0
  1205. mindspore/profiler/parser/ascend_cluster_generator.py +116 -0
  1206. mindspore/profiler/parser/ascend_communicate_generator.py +314 -0
  1207. mindspore/profiler/parser/ascend_flops_generator.py +116 -0
  1208. mindspore/profiler/parser/ascend_fpbp_generator.py +82 -0
  1209. mindspore/profiler/parser/ascend_hccl_generator.py +271 -0
  1210. mindspore/profiler/parser/ascend_integrate_generator.py +42 -0
  1211. mindspore/profiler/parser/ascend_memory_generator.py +185 -0
  1212. mindspore/profiler/parser/ascend_msprof_exporter.py +282 -0
  1213. mindspore/profiler/parser/ascend_msprof_generator.py +187 -0
  1214. mindspore/profiler/parser/ascend_op_generator.py +334 -0
  1215. mindspore/profiler/parser/ascend_steptrace_generator.py +94 -0
  1216. mindspore/profiler/parser/ascend_timeline_generator.py +545 -0
  1217. mindspore/profiler/parser/base_timeline_generator.py +483 -0
  1218. mindspore/profiler/parser/container.py +229 -0
  1219. mindspore/profiler/parser/cpu_gpu_timeline_generator.py +697 -0
  1220. mindspore/profiler/parser/flops_parser.py +531 -0
  1221. mindspore/profiler/parser/framework_enum.py +111 -0
  1222. mindspore/profiler/parser/framework_parser.py +464 -0
  1223. mindspore/profiler/parser/framework_struct.py +61 -0
  1224. mindspore/profiler/parser/gpu_analysis/__init__.py +14 -0
  1225. mindspore/profiler/parser/gpu_analysis/function_event.py +44 -0
  1226. mindspore/profiler/parser/gpu_analysis/fwk_file_parser.py +89 -0
  1227. mindspore/profiler/parser/gpu_analysis/profiler_info_parser.py +72 -0
  1228. mindspore/profiler/parser/hccl_parser.py +573 -0
  1229. mindspore/profiler/parser/hwts_log_parser.py +122 -0
  1230. mindspore/profiler/parser/integrator.py +526 -0
  1231. mindspore/profiler/parser/memory_usage_parser.py +277 -0
  1232. mindspore/profiler/parser/minddata_analyzer.py +800 -0
  1233. mindspore/profiler/parser/minddata_parser.py +186 -0
  1234. mindspore/profiler/parser/minddata_pipeline_parser.py +299 -0
  1235. mindspore/profiler/parser/op_intermediate_parser.py +149 -0
  1236. mindspore/profiler/parser/optime_parser.py +250 -0
  1237. mindspore/profiler/parser/profiler_info.py +213 -0
  1238. mindspore/profiler/parser/step_trace_parser.py +666 -0
  1239. mindspore/profiler/profiler.py +153 -0
  1240. mindspore/profiler/profiling.py +1922 -0
  1241. mindspore/rewrite/__init__.py +28 -0
  1242. mindspore/rewrite/api/__init__.py +17 -0
  1243. mindspore/rewrite/api/node.py +519 -0
  1244. mindspore/rewrite/api/node_type.py +53 -0
  1245. mindspore/rewrite/api/pattern_engine.py +490 -0
  1246. mindspore/rewrite/api/scoped_value.py +181 -0
  1247. mindspore/rewrite/api/symbol_tree.py +497 -0
  1248. mindspore/rewrite/ast_helpers/__init__.py +25 -0
  1249. mindspore/rewrite/ast_helpers/ast_converter.py +143 -0
  1250. mindspore/rewrite/ast_helpers/ast_finder.py +404 -0
  1251. mindspore/rewrite/ast_helpers/ast_flattener.py +268 -0
  1252. mindspore/rewrite/ast_helpers/ast_modifier.py +605 -0
  1253. mindspore/rewrite/ast_helpers/ast_replacer.py +79 -0
  1254. mindspore/rewrite/common/__init__.py +19 -0
  1255. mindspore/rewrite/common/config.py +24 -0
  1256. mindspore/rewrite/common/error_log.py +39 -0
  1257. mindspore/rewrite/common/event.py +28 -0
  1258. mindspore/rewrite/common/namer.py +271 -0
  1259. mindspore/rewrite/common/namespace.py +118 -0
  1260. mindspore/rewrite/common/observable.py +44 -0
  1261. mindspore/rewrite/common/observer.py +54 -0
  1262. mindspore/rewrite/node/__init__.py +22 -0
  1263. mindspore/rewrite/node/call_function.py +95 -0
  1264. mindspore/rewrite/node/cell_container.py +139 -0
  1265. mindspore/rewrite/node/control_flow.py +113 -0
  1266. mindspore/rewrite/node/node.py +1428 -0
  1267. mindspore/rewrite/node/node_manager.py +283 -0
  1268. mindspore/rewrite/node/node_topological_manager.py +223 -0
  1269. mindspore/rewrite/parsers/__init__.py +29 -0
  1270. mindspore/rewrite/parsers/arguments_parser.py +63 -0
  1271. mindspore/rewrite/parsers/assign_parser.py +852 -0
  1272. mindspore/rewrite/parsers/attribute_parser.py +57 -0
  1273. mindspore/rewrite/parsers/class_def_parser.py +289 -0
  1274. mindspore/rewrite/parsers/constant_parser.py +104 -0
  1275. mindspore/rewrite/parsers/container_parser.py +88 -0
  1276. mindspore/rewrite/parsers/expr_parser.py +55 -0
  1277. mindspore/rewrite/parsers/for_parser.py +61 -0
  1278. mindspore/rewrite/parsers/function_def_parser.py +84 -0
  1279. mindspore/rewrite/parsers/if_parser.py +85 -0
  1280. mindspore/rewrite/parsers/module_parser.py +117 -0
  1281. mindspore/rewrite/parsers/parser.py +43 -0
  1282. mindspore/rewrite/parsers/parser_register.py +86 -0
  1283. mindspore/rewrite/parsers/return_parser.py +37 -0
  1284. mindspore/rewrite/parsers/while_parser.py +59 -0
  1285. mindspore/rewrite/sparsify/__init__.py +0 -0
  1286. mindspore/rewrite/sparsify/sparse_transformer.py +457 -0
  1287. mindspore/rewrite/sparsify/sparsify.py +112 -0
  1288. mindspore/rewrite/sparsify/utils.py +179 -0
  1289. mindspore/rewrite/symbol_tree/__init__.py +20 -0
  1290. mindspore/rewrite/symbol_tree/symbol_tree.py +1819 -0
  1291. mindspore/rewrite/symbol_tree/symbol_tree_builder.py +76 -0
  1292. mindspore/rewrite/symbol_tree/symbol_tree_dumper.py +142 -0
  1293. mindspore/run_check/__init__.py +20 -0
  1294. mindspore/run_check/_check_version.py +507 -0
  1295. mindspore/run_check/run_check.py +66 -0
  1296. mindspore/safeguard/__init__.py +18 -0
  1297. mindspore/safeguard/rewrite_obfuscation.py +875 -0
  1298. mindspore/scipy/__init__.py +18 -0
  1299. mindspore/scipy/fft.py +264 -0
  1300. mindspore/scipy/linalg.py +919 -0
  1301. mindspore/scipy/ops.py +165 -0
  1302. mindspore/scipy/ops_grad.py +115 -0
  1303. mindspore/scipy/ops_wrapper.py +74 -0
  1304. mindspore/scipy/optimize/__init__.py +20 -0
  1305. mindspore/scipy/optimize/_bfgs.py +230 -0
  1306. mindspore/scipy/optimize/_lagrange.py +201 -0
  1307. mindspore/scipy/optimize/_lbfgs.py +146 -0
  1308. mindspore/scipy/optimize/gradient_optimization_algorithm.py +168 -0
  1309. mindspore/scipy/optimize/line_search.py +370 -0
  1310. mindspore/scipy/optimize/linear_sum_assignment.py +78 -0
  1311. mindspore/scipy/optimize/minimize.py +200 -0
  1312. mindspore/scipy/utils.py +156 -0
  1313. mindspore/scipy/utils_const.py +246 -0
  1314. mindspore/train/__init__.py +48 -0
  1315. mindspore/train/_utils.py +465 -0
  1316. mindspore/train/amp.py +935 -0
  1317. mindspore/train/anf_ir_pb2.py +1517 -0
  1318. mindspore/train/callback/__init__.py +44 -0
  1319. mindspore/train/callback/_backup_and_restore.py +117 -0
  1320. mindspore/train/callback/_callback.py +613 -0
  1321. mindspore/train/callback/_checkpoint.py +814 -0
  1322. mindspore/train/callback/_cluster_monitor.py +201 -0
  1323. mindspore/train/callback/_dataset_graph.py +150 -0
  1324. mindspore/train/callback/_early_stop.py +239 -0
  1325. mindspore/train/callback/_flops_collector.py +239 -0
  1326. mindspore/train/callback/_history.py +92 -0
  1327. mindspore/train/callback/_lambda_callback.py +80 -0
  1328. mindspore/train/callback/_landscape.py +1049 -0
  1329. mindspore/train/callback/_loss_monitor.py +107 -0
  1330. mindspore/train/callback/_lr_scheduler_callback.py +76 -0
  1331. mindspore/train/callback/_on_request_exit.py +298 -0
  1332. mindspore/train/callback/_reduce_lr_on_plateau.py +226 -0
  1333. mindspore/train/callback/_summary_collector.py +1184 -0
  1334. mindspore/train/callback/_tft_register.py +352 -0
  1335. mindspore/train/callback/_time_monitor.py +141 -0
  1336. mindspore/train/checkpoint_pb2.py +233 -0
  1337. mindspore/train/data_sink.py +219 -0
  1338. mindspore/train/dataset_helper.py +692 -0
  1339. mindspore/train/lineage_pb2.py +1260 -0
  1340. mindspore/train/loss_scale_manager.py +213 -0
  1341. mindspore/train/memory_profiling_pb2.py +298 -0
  1342. mindspore/train/metrics/__init__.py +175 -0
  1343. mindspore/train/metrics/accuracy.py +133 -0
  1344. mindspore/train/metrics/auc.py +129 -0
  1345. mindspore/train/metrics/bleu_score.py +170 -0
  1346. mindspore/train/metrics/confusion_matrix.py +700 -0
  1347. mindspore/train/metrics/cosine_similarity.py +109 -0
  1348. mindspore/train/metrics/dice.py +116 -0
  1349. mindspore/train/metrics/error.py +175 -0
  1350. mindspore/train/metrics/fbeta.py +167 -0
  1351. mindspore/train/metrics/hausdorff_distance.py +333 -0
  1352. mindspore/train/metrics/loss.py +97 -0
  1353. mindspore/train/metrics/mean_surface_distance.py +189 -0
  1354. mindspore/train/metrics/metric.py +373 -0
  1355. mindspore/train/metrics/occlusion_sensitivity.py +225 -0
  1356. mindspore/train/metrics/perplexity.py +133 -0
  1357. mindspore/train/metrics/precision.py +160 -0
  1358. mindspore/train/metrics/recall.py +159 -0
  1359. mindspore/train/metrics/roc.py +223 -0
  1360. mindspore/train/metrics/root_mean_square_surface_distance.py +191 -0
  1361. mindspore/train/metrics/topk.py +167 -0
  1362. mindspore/train/mind_ir_pb2.py +1908 -0
  1363. mindspore/train/model.py +2252 -0
  1364. mindspore/train/node_strategy_pb2.py +653 -0
  1365. mindspore/train/print_pb2.py +184 -0
  1366. mindspore/train/profiling_parallel_pb2.py +151 -0
  1367. mindspore/train/serialization.py +3325 -0
  1368. mindspore/train/summary/__init__.py +23 -0
  1369. mindspore/train/summary/_lineage_adapter.py +41 -0
  1370. mindspore/train/summary/_summary_adapter.py +496 -0
  1371. mindspore/train/summary/_writer_pool.py +207 -0
  1372. mindspore/train/summary/enums.py +56 -0
  1373. mindspore/train/summary/summary_record.py +581 -0
  1374. mindspore/train/summary/writer.py +167 -0
  1375. mindspore/train/summary_pb2.py +1165 -0
  1376. mindspore/train/train_thor/__init__.py +20 -0
  1377. mindspore/train/train_thor/convert_utils.py +268 -0
  1378. mindspore/train/train_thor/dataset_helper.py +192 -0
  1379. mindspore/train/train_thor/model_thor.py +257 -0
  1380. mindspore/utils/__init__.py +21 -0
  1381. mindspore/utils/utils.py +60 -0
  1382. mindspore/version.py +1 -0
  1383. mindspore-2.4.0.dist-info/METADATA +352 -0
  1384. mindspore-2.4.0.dist-info/RECORD +1387 -0
  1385. mindspore-2.4.0.dist-info/WHEEL +5 -0
  1386. mindspore-2.4.0.dist-info/entry_points.txt +3 -0
  1387. mindspore-2.4.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2731 @@
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
+ """array operations, the function docs are adapted from Numpy API."""
16
+ from __future__ import absolute_import
17
+ from __future__ import division
18
+
19
+ import math
20
+ import operator
21
+
22
+ import numpy as onp
23
+
24
+ from mindspore import context
25
+ from mindspore import ops
26
+ from mindspore.common import Tensor
27
+ from mindspore.common import dtype as mstype
28
+ from mindspore.common.seed import get_seed
29
+ from mindspore.ops import operations as P
30
+ from mindspore.ops import functional as F
31
+ from mindspore.ops.primitive import constexpr, _primexpr
32
+ from mindspore.ops.function.random_func import _get_seed
33
+ from mindspore.nn.layer.basic import tril as nn_tril
34
+ from mindspore.nn.layer.basic import triu as nn_triu
35
+ from mindspore._c_expression import Tensor as Tensor_
36
+
37
+ from mindspore.numpy.utils import _check_input_for_asarray, _deep_list, _deep_tensor_to_nparray, \
38
+ _check_input_tensor, _convert_64_to_32, _get_dtype_from_scalar, \
39
+ _expand, _to_tensor, _slice_along_axis, _callable
40
+ from mindspore.numpy.utils_const import _raise_value_error, _empty, _max, _min, \
41
+ _check_same_type, _is_shape_empty, _check_shape, _check_dtype, _tile_size, _abs, \
42
+ _raise_type_error, _expanded_shape, _check_is_float, _iota, _type_convert, \
43
+ _canonicalize_axis, _list_comprehensions, _ceil, _tuple_slice, _raise_unimplemented_error, \
44
+ _tuple_setitem
45
+ from mindspore.numpy.array_ops import ravel, concatenate, broadcast_arrays, reshape, broadcast_to, flip, \
46
+ apply_along_axis, where, moveaxis
47
+ from mindspore.numpy.dtypes import nan, pi
48
+
49
+ # According to official numpy reference, the dimension of a numpy array must be less
50
+ # than 32
51
+ MAX_NUMPY_DIMS = 32
52
+ # All types that can be accepted as "array_like" parameters in graph mode.
53
+ ARRAY_TYPES = (int, float, bool, list, tuple, Tensor)
54
+
55
+ _reduce_min_keepdims = P.ReduceMin(True)
56
+ _reduce_max_keepdims = P.ReduceMax(True)
57
+ _reduce_mean_keepdims = P.ReduceMean(True)
58
+
59
+
60
+ def array(obj, dtype=None, copy=True, ndmin=0):
61
+ """
62
+ Creates a tensor.
63
+
64
+ This function creates tensors from an array-like object.
65
+
66
+ Args:
67
+ obj (Union[int, float, bool, list, tuple]): Input data, in any form that
68
+ can be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
69
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
70
+ be in format of np.int32, or \'int32\'. If dtype is ``None``, the data type
71
+ of the new tensor will be inferred from obj. Default is ``None``.
72
+ copy (bool): If `True`, then the object is copied. Otherwise, a copy will
73
+ only be made if necessary. Default: ``True``.
74
+ ndmin (int): Specifies the minimum number of dimensions that the resulting
75
+ tensor should have. Ones will be pre-pended to the shape as needed to
76
+ meet this requirement. Default: ``0`` .
77
+
78
+ Returns:
79
+ Tensor, generated tensor with the specified dtype.
80
+
81
+ Raises:
82
+ TypeError: If input arguments have types not specified above.
83
+ ValueError: If input `obj` has different sizes at different dimensions.
84
+
85
+ Supported Platforms:
86
+ ``Ascend`` ``GPU`` ``CPU``
87
+
88
+ Examples:
89
+ >>> import mindspore.numpy as np
90
+ >>> print(np.array([1,2,3]))
91
+ [1 2 3]
92
+ """
93
+ if dtype is not None:
94
+ dtype = _check_dtype(dtype)
95
+ res = asarray(obj, dtype)
96
+
97
+ if ndmin > res.ndim:
98
+ if res.size == 0:
99
+ _raise_value_error("Empty tensor cannot be expanded beyond the current dimension.")
100
+ res = _expand(res, ndmin)
101
+
102
+ if copy and isinstance(obj, Tensor):
103
+ res = copy_(res)
104
+ elif dtype is not None and dtype != res.dtype:
105
+ res = res.astype(dtype)
106
+
107
+ return res
108
+
109
+
110
+ @constexpr
111
+ def asarray_const(a, dtype=None):
112
+ """Converts the input to tensor. Note here `a` cannot be tensor itself."""
113
+ _check_input_for_asarray(a)
114
+
115
+ if dtype is not None:
116
+ dtype = _check_dtype(dtype)
117
+
118
+ if isinstance(a, (float, int, bool)) and dtype is None:
119
+ dtype = _get_dtype_from_scalar(a)
120
+
121
+ if isinstance(a, (list, tuple)):
122
+ # Convert all tuple/nested tuples to lists
123
+ a = _deep_list(a)
124
+ # Convert all tensor sub-elements to numpy arrays
125
+ a = _deep_tensor_to_nparray(a)
126
+ a = onp.asarray(a)
127
+ if a.dtype is onp.dtype('object'):
128
+ raise ValueError('Input array must have the same size across all dimensions.')
129
+ # If dtype is not specified, we keep consistent with numpy decision
130
+ # only exceptions are: we use int/float32
131
+ if dtype is None:
132
+ dtype = mstype.pytype_to_dtype(a.dtype)
133
+ if dtype == mstype.float64:
134
+ dtype = mstype.float32
135
+ elif dtype == mstype.int64:
136
+ dtype = mstype.int32
137
+ if a.size == 0:
138
+ a = Tensor_(a)
139
+
140
+ if isinstance(a, onp.ndarray) and dtype is None:
141
+ if a.dtype is onp.dtype('object'):
142
+ raise TypeError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
143
+ dtype = mstype.pytype_to_dtype(a.dtype)
144
+ a = Tensor.from_numpy(a)
145
+
146
+ return Tensor(a, dtype=dtype)
147
+
148
+
149
+ def asarray(a, dtype=None):
150
+ """
151
+ Converts the input to tensor.
152
+
153
+ This function converts tensors from an array-like object.
154
+
155
+ Args:
156
+ a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
157
+ be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
158
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
159
+ be in format of np.int32, or \'int32\'. If dtype is ``None``, the data type
160
+ of the new tensor will be inferred from obj. Default is ``None`` .
161
+
162
+ Returns:
163
+ Tensor, generated tensor with the specified dtype.
164
+
165
+ Raises:
166
+ TypeError: If input arguments have types not specified above.
167
+ ValueError: If input `a` has different sizes at different dimensions.
168
+
169
+ Supported Platforms:
170
+ ``Ascend`` ``GPU`` ``CPU``
171
+
172
+ Examples:
173
+ >>> import mindspore.numpy as np
174
+ >>> print(np.asarray([1,2,3]))
175
+ [1 2 3]
176
+ """
177
+ if dtype is not None:
178
+ dtype = _check_dtype(dtype)
179
+ if isinstance(a, Tensor):
180
+ if dtype is None or dtype == a.dtype:
181
+ return a
182
+ return a.astype(dtype)
183
+ return asarray_const(a, dtype)
184
+
185
+
186
+ @constexpr
187
+ def asfarray_const(a, dtype=mstype.float32):
188
+ """Converts the input to tensor. Note here `a` cannot be tensor itself."""
189
+ _check_input_for_asarray(a)
190
+ if isinstance(a, (list, tuple)):
191
+ # Convert all tuple/nested tuples to lists
192
+ a = _deep_list(a)
193
+ # Convert all tensor sub-elements to numpy arrays
194
+ a = _deep_tensor_to_nparray(a)
195
+ a = onp.asarray(a)
196
+ if a.dtype is onp.dtype('object'):
197
+ raise ValueError(f"For Tensor conversion, the input_data is {a} that contains unsupported element.")
198
+ a = Tensor.from_numpy(a)
199
+
200
+ return Tensor(a, dtype)
201
+
202
+
203
+ def asfarray(a, dtype=mstype.float32):
204
+ """
205
+ Similar to asarray, converts the input to a float tensor.
206
+
207
+ If non-float dtype is defined, this function will return a float32 tensor instead.
208
+
209
+ Args:
210
+ a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
211
+ be converted to a `Tensor`. This includes Tensor, list, tuple and numbers.
212
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
213
+ be in format of np.int32, or \'int32\'. If dtype is ``None``, the data type
214
+ of the new tensor will be inferred from `a`. Default is ``mstype.float32``.
215
+
216
+
217
+ Returns:
218
+ Tensor, generated tensor with the specified float dtype.
219
+
220
+ Raises:
221
+ TypeError: If input arguments have types not specified above.
222
+ ValueError: If input `a` has different sizes at different dimensions.
223
+
224
+ Supported Platforms:
225
+ ``Ascend`` ``GPU`` ``CPU``
226
+
227
+ Examples:
228
+ >>> import mindspore.numpy as np
229
+ >>> print(np.asfarray([1,2,3]))
230
+ [1. 2. 3.]
231
+ """
232
+ if dtype is None:
233
+ return asarray(a)
234
+
235
+ dtype = _check_dtype(dtype)
236
+ if dtype not in (mstype.float16, mstype.float32, mstype.float64):
237
+ dtype = mstype.float32
238
+
239
+ if isinstance(a, Tensor):
240
+ return a.astype(dtype)
241
+
242
+ return asfarray_const(a, dtype)
243
+
244
+
245
+ def copy_(a):
246
+ """
247
+ Returns a tensor copy of the given object.
248
+
249
+ Args:
250
+ a (Union[int, float, bool, list, tuple, Tensor]): Input data, in any form that can
251
+ be converted to a Tensor. This includes Tensor, list, tuple and numbers.
252
+
253
+ Returns:
254
+ Tensor, has the same data as `a`.
255
+
256
+ Raises:
257
+ TypeError: If input `a` has type not specified above.
258
+ ValueError: If input `a` has different sizes at different dimensions.
259
+
260
+ Supported Platforms:
261
+ ``Ascend`` ``GPU`` ``CPU``
262
+
263
+ Examples:
264
+ >>> import mindspore.numpy as np
265
+ >>> x = np.ones((2,2))
266
+ >>> print(np.copy(x))
267
+ [[1. 1.]
268
+ [1. 1.]]
269
+ """
270
+ a = asarray(a)
271
+ return a.copy()
272
+
273
+
274
+ def ones(shape, dtype=mstype.float32):
275
+ """
276
+ Returns a new tensor of given shape and type, filled with ones.
277
+
278
+ Args:
279
+ shape (Union[int, tuple, list]): the shape of the new tensor.
280
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
281
+ Default is ``mstype.float32``.
282
+
283
+ Returns:
284
+ Tensor, with the designated `shape` and `dtype`, filled with ones.
285
+
286
+ Raises:
287
+ TypeError: If input arguments have types not specified above.
288
+ ValueError: If `shape` entries have values :math:`< 0`.
289
+
290
+ Supported Platforms:
291
+ ``Ascend`` ``GPU`` ``CPU``
292
+
293
+ Examples:
294
+ >>> import mindspore.numpy as np
295
+ >>> print(np.ones((2,2)))
296
+ [[1. 1.]
297
+ [1. 1.]]
298
+ """
299
+ shape = _check_shape(shape)
300
+ dtype = _check_dtype(dtype)
301
+ if _is_shape_empty(shape):
302
+ return full(shape, 1.0, dtype)
303
+ output = F.fill(dtype, shape, 1)
304
+ return output
305
+
306
+
307
+ def zeros(shape, dtype=mstype.float32):
308
+ """
309
+ Returns a new tensor of given shape and type, filled with zeros.
310
+
311
+ Args:
312
+ shape (Union[int, tuple, list]): the shape of the new tensor.
313
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
314
+ Default is mstype.float32.
315
+
316
+ Returns:
317
+ Tensor, with the designated `shape` and `dtype`, filled with zeros.
318
+
319
+ Raises:
320
+ TypeError: If input arguments have types not specified above.
321
+ ValueError: If `shape` entries have values :math:`< 0`.
322
+
323
+ Supported Platforms:
324
+ ``Ascend`` ``GPU`` ``CPU``
325
+
326
+ Examples:
327
+ >>> import mindspore.numpy as np
328
+ >>> print(np.zeros((2,2)))
329
+ [[0. 0.]
330
+ [0. 0.]]
331
+ """
332
+ shape = _check_shape(shape)
333
+ dtype = _check_dtype(dtype)
334
+ if _is_shape_empty(shape):
335
+ return full(shape, 0.0, dtype)
336
+ output = F.fill(dtype, shape, 0)
337
+ return output
338
+
339
+
340
+ def full(shape, fill_value, dtype=None):
341
+ """
342
+ Returns a new tensor of given shape and type, filled with `fill_value`.
343
+
344
+ Args:
345
+ shape (Union[int, tuple(int), list(int)]): Shape of the new tensor, e.g.,
346
+ :math:`(2, 3)` or :math:`2`.
347
+ fill_value (Union[int, float, bool, list, tuple]): Scalar or array_like
348
+ fill value.
349
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
350
+ if `dtype` is ``None``, the data type of the new tensor will be inferred from
351
+ `fill_value`. Default is ``None``.
352
+
353
+ Returns:
354
+ Tensor, with the designated shape and dtype, filled with `fill_value`.
355
+
356
+ Raises:
357
+ TypeError: If input arguments have types not specified above.
358
+ ValueError: If `shape` has entries < 0.
359
+
360
+ Supported Platforms:
361
+ ``Ascend`` ``GPU`` ``CPU``
362
+
363
+ Examples:
364
+ >>> import mindspore.numpy as np
365
+ >>> print(np.full((2,2), True))
366
+ [[True True]
367
+ [True True]]
368
+ """
369
+ shape = _check_shape(shape)
370
+ if not isinstance(fill_value, ARRAY_TYPES):
371
+ _raise_type_error("fill value should be int, float, bool, list, tuple, Tensor, but got", fill_value)
372
+ if dtype is not None:
373
+ dtype = _check_dtype(dtype)
374
+ else:
375
+ if isinstance(fill_value, (int, float, bool)):
376
+ dtype = _get_dtype_from_scalar(fill_value)
377
+ if isinstance(fill_value, Tensor):
378
+ dtype = fill_value.dtype
379
+
380
+ if not _is_shape_empty(shape):
381
+ if isinstance(fill_value, (int, float, bool)):
382
+ return F.fill(dtype, shape, fill_value)
383
+ if isinstance(fill_value, (list, tuple)):
384
+ fill_value = asarray_const(fill_value)
385
+ return broadcast_to(fill_value, shape)
386
+ # if shape contains zero, use c.Tensor()
387
+ return _convert_64_to_32(empty_compile(dtype, shape))
388
+
389
+
390
+ @_primexpr
391
+ def _generate_shapes(shape):
392
+ """Generate shapes for randn and rand."""
393
+ if not shape:
394
+ size = (1,)
395
+ elif len(shape) == 1:
396
+ if isinstance(shape[0], int):
397
+ size = shape
398
+ elif isinstance(shape[0], list):
399
+ size = tuple(shape[0])
400
+ elif isinstance(shape[0], tuple):
401
+ size = shape[0]
402
+ else:
403
+ _raise_type_error("If the length of the argument 'shape' is 1, the type of the argument 'shape' must be "
404
+ "one of ['int', 'list', 'tuple'], but got ", shape[0])
405
+ else:
406
+ for value in shape:
407
+ if not isinstance(value, int):
408
+ _raise_type_error("If the length of the argument 'shape' is > 1, the type of the argument 'shape' must "
409
+ "all be int, but got ", value)
410
+ size = shape
411
+ return size
412
+
413
+
414
+ @constexpr
415
+ def _check_rand_type(dtype):
416
+ """Check type for randn and rand"""
417
+ type_list = ['float', 'float16', 'float32', 'float64']
418
+ if isinstance(dtype, str):
419
+ if dtype not in type_list:
420
+ _raise_value_error("If the argument 'dtype' is str, it must be one of ['float', 'float16', 'float32', "
421
+ "'float64'], but got ", dtype)
422
+ elif dtype not in (mstype.float64, mstype.float32, mstype.float16):
423
+ _raise_value_error("The argument 'dtype' must be 'mindspore.float64', 'mindspore.float32' or "
424
+ "'mindspore.float16', but got ", dtype)
425
+
426
+
427
+ def randn(*shape, dtype=mstype.float32):
428
+ """
429
+ Returns a new Tensor with given shape and dtype, filled with a sample (or samples)
430
+ from the standard normal distribution.
431
+
432
+ Args:
433
+ *shape (Union[int, tuple(int), list(int)]): Shape of the new tensor, e.g.,
434
+ :math:`(2, 3)` or :math:`2`.
435
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, it must
436
+ be float type. Default is ``mindspore.float32``.
437
+
438
+ Returns:
439
+ Tensor, with the designated shape and dtype, filled with a sample (or samples)
440
+ from the "standard normal" distribution.
441
+
442
+ Raises:
443
+ TypeError: If input arguments have types not specified above.
444
+ ValueError: If `dtype` is not float type.
445
+
446
+ Supported Platforms:
447
+ ``Ascend`` ``GPU`` ``CPU``
448
+
449
+ Examples:
450
+ >>> import mindspore.numpy as np
451
+ >>> from mindspore import set_seed
452
+ >>> set_seed(1)
453
+ >>> print(np.randn((2,3)))
454
+ [[ 0.30639967 -0.42438635 -0.20454668]
455
+ [-0.4287376 1.3054721 0.64747655]]
456
+ """
457
+ _check_rand_type(dtype)
458
+ size = _generate_shapes(shape)
459
+ seed = get_seed()
460
+ if seed is not None:
461
+ seed1, seed2 = _get_seed(seed, "StandardNormal")
462
+ stdnormal = P.StandardNormal(seed=seed1, seed2=seed2)
463
+ else:
464
+ stdnormal = P.StandardNormal()
465
+ return stdnormal(size).astype(dtype)
466
+
467
+
468
+ def rand(*shape, dtype=mstype.float32):
469
+ """
470
+ Returns a new Tensor with given shape and dtype, filled with random numbers from the
471
+ uniform distribution on the interval :math:`[0, 1)`.
472
+
473
+ Args:
474
+ *shape (Union[int, tuple(int), list(int)]): Shape of the new tensor, e.g.,
475
+ :math:`(2, 3)` or :math:`2`.
476
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, it must
477
+ be float type. Default is ``mindspore.float32``.
478
+
479
+ Returns:
480
+ Tensor, with the designated shape and dtype, filled with random numbers from the
481
+ uniform distribution on the interval :math:`[0, 1)`.
482
+
483
+ Raises:
484
+ TypeError: If input arguments have types not specified above.
485
+ ValueError: If `dtype` is not float type.
486
+
487
+ Supported Platforms:
488
+ ``Ascend`` ``GPU`` ``CPU``
489
+
490
+ Examples:
491
+ >>> import mindspore.numpy as np
492
+ >>> from mindspore import set_seed
493
+ >>> set_seed(1)
494
+ >>> print(np.rand((2,3)))
495
+ [[4.1702199e-01 9.9718481e-01 7.2032452e-01]
496
+ [9.3255734e-01 1.1438108e-04 1.2812445e-01]]
497
+ """
498
+ _check_rand_type(dtype)
499
+ size = _generate_shapes(shape)
500
+ seed = get_seed()
501
+ if seed is not None:
502
+ seed1, seed2 = _get_seed(seed, "UniformReal")
503
+ uniformreal = P.UniformReal(seed=seed1, seed2=seed2)
504
+ else:
505
+ uniformreal = P.UniformReal()
506
+ return uniformreal(size).astype(dtype)
507
+
508
+
509
+ def randint(minval, maxval=None, shape=None, dtype=mstype.int32):
510
+ """
511
+ Return random integers from minval (inclusive) to maxval (exclusive). Return random integers from the discrete
512
+ uniform distribution of the specified dtype in the “half-open” interval :math:`[minval, maxval)`. If maxval is
513
+ None (the default), the value range will be :math:`[0, minval)`, in this case, minval must be greater than 0.
514
+
515
+ Args:
516
+ minval(Union[int]): Start value of interval. The interval includes this value. When `maxval`
517
+ is ``None``, `minval` must be greater than 0. When `maxval` is not ``None``,
518
+ `minval` must be less than `maxval`.
519
+ maxval(Union[int], optional): End value of interval. The interval does not include this value.
520
+ shape (Union[int, tuple(int)]): Shape of the new tensor, e.g., :math:`(2, 3)` or :math:`2`.
521
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, it must
522
+ be int type. Default is `mindspore.int32`.
523
+
524
+ Returns:
525
+ Tensor, with the designated shape and dtype, filled with random integers from minval (inclusive)
526
+ to maxval (exclusive).
527
+
528
+ Raises:
529
+ TypeError: If input arguments have types not specified above.
530
+ ValueError: If input arguments have values not specified above.
531
+
532
+ Supported Platforms:
533
+ ``Ascend`` ``GPU`` ``CPU``
534
+
535
+ Examples:
536
+ >>> import mindspore.numpy as np
537
+ >>> from mindspore import set_seed
538
+ >>> set_seed(1)
539
+ >>> print(np.randint(1, 10, (2,3)))
540
+ [[4 9 7]
541
+ [9 1 2]]
542
+ """
543
+ if not isinstance(minval, int):
544
+ _raise_type_error("For mindspore.numpy.randint, the type of the argument 'minval' must be int, "
545
+ "but got ", minval)
546
+ if maxval is None:
547
+ if minval <= 0:
548
+ _raise_value_error("For mindspore.numpy.randint, the argument 'minval' must be > 0 when the argument "
549
+ "'maxval' is None, but got ", minval)
550
+ maxval = minval
551
+ minval = 0
552
+ else:
553
+ if not isinstance(maxval, int):
554
+ _raise_type_error("For mindspore.numpy.randint, the type of the argument 'maxval' must be int, "
555
+ "but got ", maxval)
556
+ if minval >= maxval:
557
+ _raise_value_error("For mindspore.numpy.randint, the value of 'minval' must be greater than the "
558
+ "value of 'maxval'.")
559
+ if isinstance(dtype, str):
560
+ if dtype not in ('int', 'int8', 'int16', 'int32', 'int64'):
561
+ _raise_value_error("For 'mindspore.numpy.randint', if the argument 'dtype' is str, it must be one of "
562
+ "['int', 'int8', 'int16', 'int32', 'int64'], but got ", dtype)
563
+ elif dtype not in (mstype.int64, mstype.int32, mstype.int16, mstype.int8):
564
+ _raise_value_error("For 'mindspore.numpy.randint', the argument 'dtype' must be 'mindspore.int64', "
565
+ "'mindspore.int32', 'mindspore.int16' or 'mindspore.int8', but got ", dtype)
566
+ if shape is None:
567
+ shape = (1,)
568
+ else:
569
+ shape = _check_shape(shape)
570
+ seed = get_seed()
571
+ if seed is not None:
572
+ seed1, seed2 = _get_seed(seed, "UniformInt")
573
+ uniformint = P.UniformInt(seed=seed1, seed2=seed2)
574
+ else:
575
+ uniformint = P.UniformInt()
576
+ t_min = _type_convert(Tensor, minval).astype(dtype)
577
+ t_max = _type_convert(Tensor, maxval).astype(dtype)
578
+ return uniformint(shape, t_min, t_max).astype(dtype)
579
+
580
+
581
+ def arange(start, stop=None, step=None, dtype=None):
582
+ """
583
+ Returns evenly spaced values within a given interval.
584
+
585
+ Args:
586
+ start(Union[int, float]): Start of interval. The interval includes this value.
587
+ When `stop` is provided as a position argument, `start` must be given, when `stop`
588
+ is a normal argument, `start` can be optional, and default: ``0`` .
589
+ Please see additional examples below.
590
+ stop(Union[int, float], optional): End of interval. The interval does not
591
+ include this value, except in some cases where `step` is not an integer
592
+ and floating point round-off affects the length of out.
593
+ step(Union[int, float], optional): Spacing between values. For any output
594
+ `out`, this is the distance between two adjacent values, :math:`out[i+1] - out[i]`.
595
+ The default step size is 1. If `step` is specified as a position argument,
596
+ `start` must also be given.
597
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
598
+ If dtype is None, the data type of the new tensor will be inferred from start,
599
+ stop and step. Default: ``None`` .
600
+
601
+ Returns:
602
+ Tensor with evenly spaced values.
603
+
604
+ Raises:
605
+ TypeError(PyNative Mode): If input arguments have types not specified above,
606
+ or arguments are not given in the correct orders specified above.
607
+ RuntimeError(Graph Mode): The inputs that lead to TypeError in Pynative Mode
608
+ will lead to RuntimeError in Graph Mode.
609
+
610
+ Supported Platforms:
611
+ ``Ascend`` ``GPU`` ``CPU``
612
+
613
+ Examples:
614
+ >>> import mindspore.numpy as np
615
+ >>> print(np.arange(0, 5, 1))
616
+ [0 1 2 3 4]
617
+ >>> print(np.arange(3))
618
+ [0 1 2]
619
+ >>> print(np.arange(start=0, stop=3))
620
+ [0 1 2]
621
+ >>> print(np.arange(0, stop=3, step=0.5))
622
+ [0. 0.5 1. 1.5 2. 2.5]
623
+ """
624
+ # This implementation was inspired by jax.numpy.arange
625
+ # infer the dtype
626
+ if dtype is None:
627
+ dtype = _get_dtype_from_scalar(start, stop, step)
628
+ if stop is None and step is None: # (start, stop, step) -> (0, start, 1)
629
+ num = _ceil(start)
630
+ out = _iota(mstype.float32, num)
631
+ elif step is None: # (start, stop, step) -> (start, stop, 1)
632
+ num = _ceil(stop - start)
633
+ out = _iota(mstype.float32, num) + start
634
+ elif stop is None: # (start, stop, step) -> (0, start, step)
635
+ num = _ceil((start + 0.0) / step)
636
+ out = _iota(mstype.float32, num) * step
637
+ else:
638
+ num = _ceil((stop - start + 0.0) / step)
639
+ out = _iota(mstype.float32, num) * step + start
640
+ return out.astype(dtype)
641
+
642
+
643
+ def _type_checking_for_xspace(start, stop, num, endpoint, dtype):
644
+ """utility parameter checking function for linspace, logspace, geomspace."""
645
+ if not isinstance(start, ARRAY_TYPES):
646
+ _raise_type_error("start should be int, float, bool, list, tuple, Tensor, but got", start)
647
+ if not isinstance(stop, ARRAY_TYPES):
648
+ _raise_type_error("end should be int, float, bool, list, tuple, Tensor, but got", stop)
649
+ if not isinstance(start, Tensor):
650
+ start = _type_convert(Tensor, start).astype(mstype.float32)
651
+ if not isinstance(stop, Tensor):
652
+ stop = _type_convert(Tensor, stop).astype(mstype.float32)
653
+ if not isinstance(num, int):
654
+ _raise_type_error("num should be an integer, but got ", num)
655
+ if not isinstance(endpoint, bool):
656
+ _raise_type_error("endpoint should be an boolean, but got ", endpoint)
657
+ if dtype is not None:
658
+ dtype = _check_dtype(dtype)
659
+ else:
660
+ dtype = mstype.float32
661
+ start, stop = broadcast_arrays(start, stop)
662
+ return start, stop, num, endpoint, dtype
663
+
664
+
665
+ def _compute_shapes(start, axis, num, endpoint):
666
+ """Computes shapes for local variables for np.linspace"""
667
+ bounds_shape = start.shape
668
+ bounds_shape = _tuple_slice(bounds_shape, None, axis) + (1,) + _tuple_slice(bounds_shape, axis, None)
669
+ iota_shape = _list_comprehensions(start.ndim + 1, 1, True)
670
+ iota_shape = _tuple_slice(iota_shape, None, axis) + (num,) + _tuple_slice(iota_shape, axis + 1, None)
671
+ num_tensor = _type_convert(Tensor, num).astype(mstype.float32)
672
+ div = (num_tensor - 1) if endpoint else num_tensor
673
+ return bounds_shape, iota_shape, div
674
+
675
+
676
+ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0):
677
+ """
678
+ Returns evenly spaced values within a given interval.
679
+
680
+ Args:
681
+ start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
682
+ stop (Union[int, list(int), tuple(int), tensor]): The end value of the sequence,
683
+ unless `endpoint` is set to False. In that case, the sequence consists
684
+ of all but the last of `num + 1` evenly spaced samples, so that `stop`
685
+ is excluded. Note that the step size changes when `endpoint` is False.
686
+ num (int, optional): Number of samples to generate. Default: ``50`` .
687
+ endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
688
+ not included. Default: ``True`` .
689
+ retstep (bool, optional): If True, return (`samples`, `step`), where `step` is
690
+ the spacing between samples.
691
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
692
+ If `dtype` is None, infer the data type from other input arguments. Default: ``None`` .
693
+ axis (int, optional): The axis in the result to store the samples. Relevant
694
+ only if start or stop are array-like. By default, the samples will
695
+ be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
696
+ Default: ``0`` .
697
+
698
+ Returns:
699
+ Tensor, with `num` equally spaced samples in the closed interval
700
+ :math:`[start, stop]` or the half-open interval :math:`[start, stop)`
701
+ (depending on whether `endpoint` is True or False).
702
+
703
+ Step, the size of spacing between samples, only returned if `retstep` is True.
704
+
705
+ Raises:
706
+ TypeError: If input arguments have types not specified above.
707
+
708
+ Supported Platforms:
709
+ ``Ascend`` ``GPU`` ``CPU``
710
+
711
+ Examples:
712
+ >>> import mindspore.numpy as np
713
+ >>> print(np.linspace(0, 5, 6))
714
+ [0. 1. 2. 3. 4. 5.]
715
+ """
716
+ # This implementation was inspired by jax.numpy.linspace and numpy.linspace
717
+ start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
718
+ axis = _canonicalize_axis(axis, start.ndim + 1)
719
+ if not isinstance(retstep, bool):
720
+ _raise_type_error("retstep should be an boolean, but got ", retstep)
721
+ bounds_shape, iota_shape, div = _compute_shapes(start, axis, num, endpoint)
722
+ out = None
723
+ delta = None
724
+ if num > 1:
725
+ delta = (stop - start) / div
726
+ # This is similar to how numpy and jax compute linspace
727
+ start_expand = reshape(start, bounds_shape)
728
+ incremental_expand = reshape(_iota(mstype.float32, num), iota_shape)
729
+ delta_expand = reshape(delta, bounds_shape)
730
+ start_expand, incremental_expand, delta_expand = broadcast_arrays(
731
+ start_expand, incremental_expand, delta_expand)
732
+ out = start_expand + (incremental_expand * delta_expand)
733
+ # recover endpoint
734
+ if endpoint:
735
+ out = moveaxis(out, axis, 0)
736
+ out[-1] = stop
737
+ out = moveaxis(out, 0, axis)
738
+ elif num == 1:
739
+ delta = nan if endpoint else stop - start
740
+ out = reshape(start, bounds_shape)
741
+ else: # num == 0
742
+ _raise_value_error("cannot support Tensor with num=0.")
743
+ if retstep:
744
+ return out.astype(dtype), delta
745
+ return out.astype(dtype)
746
+
747
+
748
+ def logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, axis=0):
749
+ """
750
+ Returns numbers spaced evenly on a log scale.
751
+
752
+ In linear space, the sequence starts at base ** start (base to the power of
753
+ start) and ends with base ** stop (see endpoint below).
754
+
755
+ Args:
756
+ start (Union[int, list(int), tuple(int), tensor]): ``base ** start`` is the starting
757
+ value of the sequence.
758
+ stop (Union[int, list(int), tuple(int), tensor]): ``base ** stop`` is the final value of
759
+ the sequence, unless `endpoint` is False. In that case, ``num + 1`` values are spaced
760
+ over the interval in log-space, of which all but the last (a sequence of length num)
761
+ are returned.
762
+ num (int, optional): Number of samples to generate. Default: ``50`` .
763
+ endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
764
+ not included. Default: ``True`` .
765
+ base (Union[int, float], optional): The base of the log space. The step size
766
+ between the elements in :math:`ln(samples) / ln(base)` (or :math:`log_{base}(samples)`)
767
+ is uniform. Default: ``10.0`` .
768
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
769
+ If `dtype` is None, infer the data type from other input arguments. Default: ``None`` .
770
+ axis (int, optional): The axis in the result to store the samples. Relevant
771
+ only if start or stop is array-like. By default, the samples will
772
+ be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
773
+ Default: ``0`` .
774
+
775
+ Returns:
776
+ Tensor, equally spaced on a log scale.
777
+
778
+ Raises:
779
+ TypeError: If input arguments have types not specified above.
780
+
781
+ Supported Platforms:
782
+ ``Ascend`` ``GPU`` ``CPU``
783
+
784
+ Examples:
785
+ >>> import mindspore.numpy as np
786
+ >>> print(np.logspace(0, 5, 6, base=2.0))
787
+ [ 1. 2. 4. 8. 16. 32.]
788
+ """
789
+ # This implementation was inspired by jax.numpy.linspace and numpy.linspace
790
+ start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
791
+ axis = _canonicalize_axis(axis, start.ndim + 1)
792
+ if not isinstance(base, (int, float, bool)):
793
+ _raise_type_error("base should be a number, but got ", base)
794
+ linspace_res = linspace(start, stop, num, endpoint=endpoint, retstep=False, dtype=None, axis=axis)
795
+ return F.tensor_pow(base, linspace_res).astype(dtype)
796
+
797
+
798
+ def geomspace(start, stop, num=50, endpoint=True, dtype=None, axis=0):
799
+ """
800
+ Returns numbers spaced evenly on a log scale (a geometric progression).
801
+
802
+ This is similar to logspace, but with endpoints specified directly. Each output sample
803
+ is a constant multiple of the previous.
804
+
805
+ Args:
806
+ start (Union[int, list(int), tuple(int), tensor]): The starting value of the sequence.
807
+ stop (Union[int, list(int), tuple(int), tensor]): The final value of the sequence,
808
+ unless endpoint is False. In that case, num + 1 values are spaced over the
809
+ interval in log-space, of which all but the last (a sequence of length num) are
810
+ returned.
811
+ num (int, optional): Number of samples to generate. Default: ``50`` .
812
+ endpoint (bool, optional): If True, `stop` is the last sample. Otherwise, it is
813
+ not included. Default: ``True`` .
814
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype, can
815
+ be in format of np.float32, or `float32`.If `dtype` is None, infer the data
816
+ type from other input arguments. Default: ``None`` .
817
+ axis (int, optional): The axis in the result to store the samples. Relevant
818
+ only if start or stop is array-like. By default (0), the samples will
819
+ be along a new axis inserted at the beginning. Use -1 to get an axis at the end.
820
+ Default: ``0`` .
821
+
822
+ Returns:
823
+ Tensor, with samples equally spaced on a log scale.
824
+
825
+ Raises:
826
+ TypeError: If input arguments have types not specified above.
827
+
828
+ Supported Platforms:
829
+ ``Ascend`` ``GPU`` ``CPU``
830
+
831
+ Examples:
832
+ >>> import mindspore.numpy as np
833
+ >>> output = np.geomspace(1, 256, num=9)
834
+ >>> print(output)
835
+ [ 1. 2. 4. 8. 16. 32. 64. 128. 256.]
836
+ >>> output = np.geomspace(1, 256, num=8, endpoint=False)
837
+ >>> print(output)
838
+ [ 1. 2. 4. 8. 16. 32. 64. 128.]
839
+ """
840
+ start, stop, num, endpoint, dtype = _type_checking_for_xspace(start, stop, num, endpoint, dtype)
841
+ axis = _canonicalize_axis(axis, start.ndim + 1)
842
+ root = num
843
+ if endpoint:
844
+ root -= 1
845
+ bases = F.tensor_pow(F.tensor_div(stop, start), asarray_const(1. / (root)))
846
+ exponents = linspace(zeros(F.shape(bases)), F.fill(F.dtype(bases), F.shape(bases), root),
847
+ num, endpoint=endpoint, dtype=dtype, axis=axis)
848
+ shape = F.shape(bases)
849
+ axis = axis + F.rank(bases) + 1 if axis < 0 else axis
850
+ expanded_shape = _tuple_slice(shape, None, axis) + (1,) + _tuple_slice(shape, axis, None)
851
+ bases = F.reshape(bases, expanded_shape)
852
+ start = F.reshape(start, expanded_shape)
853
+ res = F.tensor_mul(F.tensor_pow(bases, exponents), start)
854
+ if dtype is not None:
855
+ res = F.cast(res, dtype)
856
+ return res
857
+
858
+
859
+ def eye(N, M=None, k=0, dtype=mstype.float32):
860
+ """
861
+ Returns a 2-D tensor with ones on the diagonal and zeros elsewhere.
862
+
863
+ Args:
864
+ N (int): Number of rows in the output, must be larger than 0.
865
+ M (int, optional): Number of columns in the output. If is ``None``, default: ``N`` ,
866
+ if defined, must be larger than 0. Default: ``None``.
867
+ k (int, optional): Index of the diagonal: ``0`` (the default) refers to the main
868
+ diagonal, a positive value refers to an upper diagonal, and a negative value
869
+ to a lower diagonal. Default: ``0`` .
870
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype.
871
+ Default: ``mstype.float32`` .
872
+
873
+ Returns:
874
+ A tensor of shape (N, M). A tensor where all elements are equal to zero,
875
+ except for the k-th diagonal, whose values are equal to one.
876
+
877
+ Raises:
878
+ TypeError: If input arguments have types not specified above.
879
+
880
+ Supported Platforms:
881
+ ``Ascend`` ``GPU`` ``CPU``
882
+
883
+ Examples:
884
+ >>> import mindspore.numpy as np
885
+ >>> print(np.eye(2, 2))
886
+ [[1. 0.]
887
+ [0. 1.]]
888
+ """
889
+ dtype = _check_dtype(dtype)
890
+ if M is None:
891
+ M = N
892
+ if not (isinstance(M, int) and isinstance(N, int) and isinstance(k, int)):
893
+ _raise_type_error("Input tensor dimensions should be integers.")
894
+ out = None
895
+ if N == 0 or M == 0:
896
+ # Fill the shape with any value is fine.
897
+ return full((N, M), 0, dtype)
898
+
899
+ out = F.eye(N, M, dtype)
900
+
901
+ if k >= M or k <= -N:
902
+ return full((N, M), 0, dtype)
903
+ if k != 0:
904
+ out = out.astype(mstype.float32)
905
+ if k > 0:
906
+ out_left = full((N, k), 0, dtype)
907
+ out_right = out[..., 0:M - k:1]
908
+ return concatenate((out_left, out_right), 1).astype(dtype)
909
+ if k < 0:
910
+ out_upper = full((-k, M), 0, dtype)
911
+ out_lower = out[0:N + k:1, ...]
912
+ return concatenate((out_upper, out_lower), 0).astype(dtype)
913
+ return out
914
+
915
+
916
+ def identity(n, dtype=mstype.float32):
917
+ """
918
+ Returns the identity tensor.
919
+
920
+ Args:
921
+ n (int): Number of rows and columns in the output, must be larger than 0.
922
+ dtype (Union[:class:`mindspore.dtype`, str], optional): Designated tensor dtype,
923
+ default is `mstype.float32`.
924
+
925
+ Returns:
926
+ A tensor of shape `(n, n)`, where all elements are equal to zero,
927
+ except for the diagonal, whose values are equal to one.
928
+
929
+ Supported Platforms:
930
+ ``Ascend`` ``GPU`` ``CPU``
931
+
932
+ Raises:
933
+ TypeError: If input arguments have types not specified above.
934
+
935
+ Examples:
936
+ >>> import mindspore.numpy as np
937
+ >>> print(np.identity(2))
938
+ [[1. 0.]
939
+ [0. 1.]]
940
+ """
941
+ if not isinstance(n, int):
942
+ _raise_type_error("Input tensor dimensions should be integers.")
943
+ dtype = _check_dtype(dtype)
944
+ return eye(n, dtype=dtype)
945
+
946
+
947
+ @constexpr
948
+ def empty_compile(dtype, shape):
949
+ """Returns an empty Tensor."""
950
+ return Tensor_(dtype, shape)
951
+
952
+
953
+ def empty(shape, dtype=mstype.float32):
954
+ """
955
+ Returns a new array of given shape and type, without initializing
956
+ entries.
957
+
958
+ Note:
959
+ Numpy argument `order` is not supported.
960
+ Object arrays are not supported.
961
+
962
+ Args:
963
+ shape (Union[int, tuple(int)]): Shape of the empty array, e.g.,
964
+ (2, 3) or 2.
965
+ dtype (:class:`mindspore.dtype`, optional): Desired output data-type for the
966
+ array, e.g, mstype.int8. Default: ``mstype.float32`` .
967
+
968
+ Returns:
969
+ Tensor, array of uninitialized (arbitrary) data of the given
970
+ shape and dtype.
971
+
972
+ Raises:
973
+ TypeError: If the input shape or dtype is invalid.
974
+
975
+ Supported Platforms:
976
+ ``Ascend`` ``GPU`` ``CPU``
977
+
978
+ Examples:
979
+ >>> import mindspore.numpy as np
980
+ >>> output = np.empty((2, 3))
981
+ >>> print(output)
982
+ [[0. 0. 0.]
983
+ [0. 0. 0.]]
984
+ """
985
+ return ops.zeros(shape, dtype)
986
+
987
+
988
+ def _get_shape(array_like):
989
+ """Returns the shape of the array like object."""
990
+ if isinstance(array_like, Tensor):
991
+ return array_like.shape
992
+ return asarray_const(array_like).shape
993
+
994
+
995
+ def _get_dtype(array_like):
996
+ """Returns the data type of the array like object."""
997
+ if isinstance(array_like, Tensor):
998
+ return array_like.dtype
999
+ return asarray_const(array_like).dtype
1000
+
1001
+
1002
+ def _x_like(prototype, dtype, shape, constructor, fill_value=None):
1003
+ """
1004
+ Returns a tensor with the same shape and type as prototype,
1005
+ using constructor.
1006
+ """
1007
+ if not isinstance(prototype, ARRAY_TYPES):
1008
+ _raise_type_error("prototype should be int, float, bool, list, tuple, Tensor, but got", prototype)
1009
+ dtype_out = dtype
1010
+ shape_out = shape
1011
+ if dtype_out is None:
1012
+ dtype_out = _get_dtype(prototype)
1013
+ if shape_out is None or isinstance(shape_out, (list, tuple)) and not shape_out:
1014
+ shape_out = _get_shape(prototype)
1015
+ if fill_value is not None:
1016
+ return constructor(shape_out, fill_value, dtype_out)
1017
+ return constructor(shape_out, dtype_out)
1018
+
1019
+
1020
+ def empty_like(prototype, dtype=None, shape=None):
1021
+ """
1022
+ Returns a new array with the same shape and type as a given array.
1023
+
1024
+ Note:
1025
+ Input array must have the same size across a dimension.
1026
+ If `prototype` is not a Tensor, dtype is float32 by default if not provided.
1027
+
1028
+ Args:
1029
+ prototype (Union[Tensor, list, tuple]): The shape and data-type of `prototype`
1030
+ define these same attributes of the returned array.
1031
+ dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
1032
+ result.
1033
+ shape (int or sequence of ints, optional): Overrides the shape
1034
+ of the result.
1035
+
1036
+ Returns:
1037
+ Tensor, array of uninitialized (arbitrary) data with the same
1038
+ shape and type as `prototype`.
1039
+
1040
+ Raises:
1041
+ ValueError: If `prototype` is not a Tensor, list or tuple.
1042
+
1043
+ Supported Platforms:
1044
+ ``Ascend`` ``GPU`` ``CPU``
1045
+
1046
+ Examples:
1047
+ >>> import mindspore.numpy as np
1048
+ >>> a = np.ones((4,1,2))
1049
+ >>> output = np.empty_like(a)
1050
+ >>> print(output)
1051
+ [[[0. 0.]]
1052
+ [[0. 0.]]
1053
+ [[0. 0.]]
1054
+ [[0. 0.]]]
1055
+ """
1056
+ return _x_like(prototype, dtype, shape, empty)
1057
+
1058
+
1059
+ def ones_like(a, dtype=None, shape=None):
1060
+ """
1061
+ Returns an array of ones with the same shape and type as a given array.
1062
+
1063
+ Note:
1064
+ Input array must have the same size across a dimension.
1065
+ If `a` is not a Tensor, dtype is float32 by default if not provided.
1066
+
1067
+ Args:
1068
+ a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
1069
+ attributes of the returned array.
1070
+ dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
1071
+ result. Default: ``None``.
1072
+ shape (int, sequence of ints, optional): Overrides the shape
1073
+ of the result. Default: ``None``.
1074
+
1075
+ Returns:
1076
+ Tensor, array of ones with the same shape and type as `a`.
1077
+
1078
+ Raises:
1079
+ ValueError: If `a` is not a Tensor, list or tuple.
1080
+
1081
+ Supported Platforms:
1082
+ ``Ascend`` ``GPU`` ``CPU``
1083
+
1084
+ Examples:
1085
+ >>> import mindspore.numpy as np
1086
+ >>> a = np.ones((4,1,2))
1087
+ >>> output = np.ones_like(a)
1088
+ >>> print(output)
1089
+ [[[1. 1.]]
1090
+ [[1. 1.]]
1091
+ [[1. 1.]]
1092
+ [[1. 1.]]]
1093
+ """
1094
+ return _x_like(a, dtype, shape, ones)
1095
+
1096
+
1097
+ def zeros_like(a, dtype=None, shape=None):
1098
+ """
1099
+ Returns an array of zeros with the same shape and type as a given array.
1100
+
1101
+ Note:
1102
+ Input array must have the same size across a dimension.
1103
+ If `a` is not a Tensor, dtype is float32 by default if not provided.
1104
+
1105
+ Args:
1106
+ a (Union[Tensor, list, tuple]): The shape and data-type of a define these same
1107
+ attributes of the returned array.
1108
+ dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
1109
+ result.
1110
+ shape (int, sequence of ints, optional): Overrides the shape
1111
+ of the result.
1112
+
1113
+ Returns:
1114
+ Tensor, array of zeros with the same shape and type as `a`.
1115
+
1116
+ Raises:
1117
+ ValueError: If `a` is not a Tensor, list or tuple.
1118
+
1119
+ Supported Platforms:
1120
+ ``Ascend`` ``GPU`` ``CPU``
1121
+
1122
+ Examples:
1123
+ >>> import mindspore.numpy as np
1124
+ >>> a = np.ones((4,1,2))
1125
+ >>> output = np.zeros_like(a)
1126
+ >>> print(output)
1127
+ [[[0. 0.]]
1128
+ [[0. 0.]]
1129
+ [[0. 0.]]
1130
+ [[0. 0.]]]
1131
+ """
1132
+ return _x_like(a, dtype, shape, zeros)
1133
+
1134
+
1135
+ def full_like(a, fill_value, dtype=None, shape=None):
1136
+ """
1137
+ Returns a full array with the same shape and type as a given array.
1138
+
1139
+ Note:
1140
+ - Input array must have the same size across a dimension.
1141
+ - If `a` is not a Tensor, dtype is float32 by default if not provided.
1142
+
1143
+ Args:
1144
+ a (Union[Tensor, list, tuple]): The shape and data-type of `a` define these same
1145
+ attributes of the returned array.
1146
+ fill_value (scalar): Fill value.
1147
+ dtype (:class:`mindspore.dtype`, optional): Overrides the data type of the
1148
+ result.
1149
+ shape (int, sequence of ints, optional): Overrides the shape
1150
+ of the result.
1151
+
1152
+ Returns:
1153
+ Tensor, array of fill_value with the same shape and type as `a`.
1154
+
1155
+ Raises:
1156
+ ValueError: If `a` is not a Tensor, list or tuple.
1157
+
1158
+ Supported Platforms:
1159
+ ``Ascend`` ``GPU`` ``CPU``
1160
+
1161
+ Examples:
1162
+ >>> import mindspore.numpy as np
1163
+ >>> a = np.ones((4,1,2))
1164
+ >>> output = np.full_like(a, 0.5)
1165
+ >>> print(output)
1166
+ [[[0.5 0.5]]
1167
+ [[0.5 0.5]]
1168
+ [[0.5 0.5]]
1169
+ [[0.5 0.5]]]
1170
+ """
1171
+ return _x_like(a, dtype, shape, full, fill_value=fill_value)
1172
+
1173
+
1174
+ def tri(N, M=None, k=0, dtype=mstype.float32):
1175
+ """
1176
+ Returns a tensor with ones at and below the given diagonal and zeros elsewhere.
1177
+
1178
+ Args:
1179
+ N(int): Number of rows in the array.
1180
+ M(int, optional): Number of columns in the array. By default, `M` is taken
1181
+ equal to N. Default: ``None`` .
1182
+ k(int, optional): The sub-diagonal at and below which the array is filled.
1183
+ :math:`k = 0` is the main diagonal, while :math:`k < 0` is below it, and :math:`k > 0` is above.
1184
+ Default: ``0`` .
1185
+ dtype(:class:`mindspore.dtype`, optional): Data type of the returned array. Default: ``mstype.float32`` .
1186
+
1187
+ Returns:
1188
+ Tensor with shape `(N, M)`, with its lower triangle filled with
1189
+ ones and zeros elsewhere; in other words :math:`T[i,j] = 1` for :math:`j <= i + k`,
1190
+ 0 otherwise.
1191
+
1192
+ Raises:
1193
+ TypeError: If input arguments have types not specified above.
1194
+
1195
+ Supported Platforms:
1196
+ ``Ascend`` ``GPU`` ``CPU``
1197
+
1198
+ Examples:
1199
+ >>> import mindspore.numpy as np
1200
+ >>> output = np.tri(3, 3, 1)
1201
+ >>> print(output)
1202
+ [[1. 1. 0.]
1203
+ [1. 1. 1.]
1204
+ [1. 1. 1.]]
1205
+ """
1206
+ if M is None:
1207
+ M = N
1208
+ return nn_tril((N, M), dtype, k)
1209
+
1210
+
1211
+ @constexpr
1212
+ def _device_target():
1213
+ return context.get_context("device_target")
1214
+
1215
+
1216
+ def tril(m, k=0):
1217
+ """
1218
+ Returns a lower triangle of a tensor.
1219
+
1220
+ Returns a copy of a tensor with elements above the `k-th` diagonal zeroed.
1221
+
1222
+ Args:
1223
+ m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
1224
+ attributes of the returned tensor.
1225
+ k (int, optional): Diagonal above which to zero elements. :math:`k = 0` (the default)
1226
+ is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
1227
+
1228
+ Returns:
1229
+ Lower triangle of `m`, of same shape and data-type as `m`.
1230
+
1231
+ Supported Platforms:
1232
+ ``Ascend`` ``GPU`` ``CPU``
1233
+
1234
+ Raises:
1235
+ TypeError: If input arguments have types not specified above.
1236
+ ValueError: If input `m`\'s rank :math:`< 1`.
1237
+
1238
+ Examples:
1239
+ >>> import mindspore.numpy as np
1240
+ >>> output = np.tril(np.ones((3, 3)))
1241
+ >>> print(output)
1242
+ [[1. 0. 0.]
1243
+ [1. 1. 0.]
1244
+ [1. 1. 1.]]
1245
+ """
1246
+ if not isinstance(m, Tensor):
1247
+ m = asarray_const(m)
1248
+ dtype = m.dtype
1249
+ device_target = _device_target()
1250
+ # check rank
1251
+ rank = len(m.shape)
1252
+ if rank < 1:
1253
+ _raise_value_error("input m's rank should be larger than 0")
1254
+ elif rank == 1:
1255
+ mask = tri(m.shape[0], k=k, dtype=mstype.bool_)
1256
+ return where(mask, m, zeros(1, m.dtype))
1257
+ # Only Ascend hardware will reduce accuracy
1258
+ if device_target == "Ascend":
1259
+ m = m.astype(mstype.float32)
1260
+ assist = nn_tril(m.shape, mstype.float32, k)
1261
+ # MindSpore binary op do not support bool
1262
+ elif dtype == mstype.bool_:
1263
+ m = m.astype(mstype.float32)
1264
+ assist = nn_tril(m.shape, mstype.float32, k)
1265
+ else:
1266
+ assist = nn_tril(m.shape, dtype, k)
1267
+ return F.tensor_mul(assist, m).astype(dtype)
1268
+
1269
+
1270
+ def triu(m, k=0):
1271
+ """
1272
+ Returns an upper triangle of a tensor.
1273
+
1274
+ Returns a copy of a tensor with elements below the `k-th` diagonal zeroed.
1275
+
1276
+ Args:
1277
+ m (Union[Tensor, list, tuple]): The shape and data-type of `m` define these same
1278
+ attributes of the returned tensor.
1279
+ k (int, optional): Diagonal below which to zero elements. :math:`k = 0` (the default)
1280
+ is the main diagonal, :math:`k < 0` is below it and :math:`k > 0` is above.
1281
+
1282
+ Returns:
1283
+ Upper triangle of `m`, of same shape and data-type as `m`.
1284
+
1285
+ Raises:
1286
+ TypeError: If input arguments have types not specified above.
1287
+ ValueError: If input `m`\'s rank < 1.
1288
+
1289
+ Supported Platforms:
1290
+ ``Ascend`` ``GPU`` ``CPU``
1291
+
1292
+ Examples:
1293
+ >>> import mindspore.numpy as np
1294
+ >>> output = np.triu(np.ones((3, 3)))
1295
+ >>> print(output)
1296
+ [[1. 1. 1.]
1297
+ [0. 1. 1.]
1298
+ [0. 0. 1.]]
1299
+ """
1300
+ if not isinstance(m, Tensor):
1301
+ m = asarray_const(m)
1302
+ dtype = m.dtype
1303
+ device_target = _device_target()
1304
+ # check rank
1305
+ rank = len(m.shape)
1306
+ if rank < 1:
1307
+ _raise_value_error("input m's rank should be larger than 0")
1308
+ elif rank == 1:
1309
+ mask = tri(m.shape[0], k=k - 1, dtype=mstype.bool_)
1310
+ return where(mask, zeros(1, m.dtype), m)
1311
+ # Only Ascend hardware will reduce accuracy
1312
+ if device_target == "Ascend":
1313
+ m = m.astype(mstype.float32)
1314
+ assist = nn_triu(m.shape, mstype.float32, k)
1315
+ # MindSpore binary op do not support bool
1316
+ elif dtype == mstype.bool_:
1317
+ m = m.astype(mstype.float32)
1318
+ assist = nn_triu(m.shape, mstype.float32, k)
1319
+ else:
1320
+ assist = nn_triu(m.shape, dtype, k)
1321
+ return F.tensor_mul(assist, m).astype(dtype)
1322
+
1323
+
1324
+ def diagonal(a, offset=0, axis1=0, axis2=1):
1325
+ """
1326
+ Returns specified diagonals.
1327
+
1328
+ If `a` is 2-D, returns the diagonal of `a` with the given offset, i.e., the
1329
+ collection of elements of the form ``a[i, i+offset]``. If `a` has more than two
1330
+ dimensions, then the axes specified by `axis1` and `axis2` are used to determine
1331
+ the 2-D sub-array whose diagonal is returned. The shape of the resulting
1332
+ array can be determined by removing `axis1` and `axis2` and appending an index
1333
+ to the right equal to the size of the resulting diagonals.
1334
+
1335
+ Args:
1336
+ a (Tensor): Array from which the diagonals are taken.
1337
+ offset (int, optional): Offset of the diagonal from the main diagonal.
1338
+ Can be positive or negative. Defaults to main diagonal.
1339
+ axis1 (int, optional): Axis to be used as the first axis of the 2-D
1340
+ sub-arrays from which the diagonals should be taken. Defaults to
1341
+ first axis (0).
1342
+ axis2 (int, optional): Axis to be used as the second axis of the 2-D
1343
+ sub-arrays from which the diagonals should be taken. Defaults to
1344
+ second axis.
1345
+
1346
+ Returns:
1347
+ Tensor, if `a` is 2-D, then `a` 1-D array containing the diagonal. If
1348
+ ``a.ndim > 2``, then the dimensions specified by `axis1` and `axis2` are removed,
1349
+ and a new axis inserted at the end corresponding to the diagonal.
1350
+
1351
+ Raises:
1352
+ ValueError: If the input tensor has less than two dimensions.
1353
+
1354
+ Supported Platforms:
1355
+ ``Ascend`` ``GPU`` ``CPU``
1356
+
1357
+ Examples:
1358
+ >>> import mindspore.numpy as np
1359
+ >>> a = np.arange(4).reshape(2,2).astype(np.float32)
1360
+ >>> print(a)
1361
+ [[0. 1.]
1362
+ [2. 3.]]
1363
+ >>> output = np.diagonal(a)
1364
+ >>> print(output)
1365
+ [0. 3.]
1366
+ >>> output = np.diagonal(a, 1)
1367
+ >>> print(output)
1368
+ [1.]
1369
+ >>> a = np.arange(8).reshape(2, 2, 2).astype(np.float32)
1370
+ >>> print(a)
1371
+ [[[0. 1.]
1372
+ [2. 3.]]
1373
+ [[4. 5.]
1374
+ [6. 7.]]]
1375
+ >>> output = np.diagonal(a, 0, 0, 1)
1376
+ >>> print(output)
1377
+ [[0. 6.]
1378
+ [1. 7.]]
1379
+ """
1380
+ return a.diagonal(offset=offset, axis1=axis1, axis2=axis2)
1381
+
1382
+
1383
+ def trace(a, offset=0, axis1=0, axis2=1, dtype=None):
1384
+ """
1385
+ Return the sum along diagonals of the tensor.
1386
+
1387
+ Note:
1388
+ - `trace` is currently only used in `mindscience` scientific computing scenarios and
1389
+ dose not support other usage scenarios.
1390
+ - `trace` is not supported on Windows platform yet.
1391
+
1392
+ Args:
1393
+ a (Tensor): A matrix to be calculated.
1394
+ offset (int, optional): Offset of the diagonal from the main diagonal.
1395
+ Can be positive or negative. Default: ``0``.
1396
+ axis1 (int, optional): Axis to be used as the first axis of the 2-D
1397
+ sub-arrays from which the diagonals should be taken. Default: ``0``.
1398
+ axis2 (int, optional): Axis to be used as the second axis of the 2-D
1399
+ sub-arrays from which the diagonals should be taken. Default: ``1``.
1400
+ dtype (:class:`mindspore.dtype`, optional): Overrides the dtype of the
1401
+ output Tensor if not ``None``. Default: ``None``.
1402
+
1403
+ Returns:
1404
+ Tensor, the sum along diagonals. If `a` is 2-D, the sum along the diagonal is returned.
1405
+ If `a` has more than two dimensions, then the axes specified by `axis1` and `axis2` are used
1406
+ to determine the 2-D sub-arrays whose traces are returned. The shape of the resulting
1407
+ array is the same as that of `a` with `axis1` and `axis2` removed.
1408
+
1409
+ Raises:
1410
+ ValueError: If `a` has less than two dimensions.
1411
+ ValueError: If `axis1` or `axis2` is not in [-dims, dims), which dims is dimension of `a`.
1412
+ ValueError: If axes specified by `axis1` and `axis2` are same.
1413
+
1414
+ Supported Platforms:
1415
+ ``Ascend`` ``GPU`` ``CPU``
1416
+
1417
+ Examples:
1418
+ >>> import numpy as np
1419
+ >>> from mindspore import Tensor
1420
+ >>> from mindspore.numpy import trace
1421
+ >>> x = Tensor(np.eye(3, dtype=np.float32))
1422
+ >>> print(trace(x))
1423
+ 3.0
1424
+ """
1425
+ return a.trace(offset=offset, axis1=axis1, axis2=axis2, dtype=dtype)
1426
+
1427
+
1428
+ def _index(i, size, cartesian=True):
1429
+ """If cartesian=True, index 0 is swapped with index 1."""
1430
+ if cartesian:
1431
+ if i == 1:
1432
+ return 0
1433
+ if i == 0 and size >= 2:
1434
+ return 1
1435
+ return i
1436
+
1437
+
1438
+ def meshgrid(*xi, sparse=False, indexing='xy'):
1439
+ """
1440
+ Returns coordinate matrices from coordinate vectors.
1441
+
1442
+ Make `N-D` coordinate arrays for vectorized evaluations of `N-D`
1443
+ scalar/vector fields over `N-D` grids, given one-dimensional
1444
+ coordinate arrays `x1, x2,…, xn`.
1445
+
1446
+ Note:
1447
+ Numpy argument copy is not supported, and a copy is always
1448
+ returned.
1449
+
1450
+ Args:
1451
+ *xi (Tensor): 1-D arrays representing the coordinates
1452
+ of a grid.
1453
+ indexing ('xy', 'ij', optional): Cartesian ('xy', default) or
1454
+ matrix ('ij') indexing of output. In the 2-D case with
1455
+ inputs of length `M` and `N`, the outputs are of shape `(N, M)`
1456
+ for 'xy' indexing and `(M, N)` for 'ij' indexing. In the 3-D
1457
+ case with inputs of length `M`, `N` and `P`, outputs are of shape
1458
+ `(N, M, P)` for 'xy' indexing and `(M, N, P)` for 'ij' indexing.
1459
+ sparse (bool, optional): If True a sparse grid is returned in
1460
+ order to conserve memory. Default is False.
1461
+
1462
+ Returns:
1463
+ Tuple of tensors, for vectors `x1, x2,…, xn` with lengths
1464
+ ``Ni=len(xi)``, return `(N1, N2, N3,...Nn)` shaped arrays if
1465
+ ``indexing='ij'`` or `(N2, N1, N3,...Nn)` shaped arrays if
1466
+ ``indexing='xy'`` with the elements of `xi` repeated to fill the matrix
1467
+ along the first dimension for `x1`, the second for `x2` and so on.
1468
+
1469
+ Raises:
1470
+ TypeError: If the input is not a tensor, or sparse is not boolean, or
1471
+ indexing is not 'xy' or 'ij'.
1472
+
1473
+ Supported Platforms:
1474
+ ``Ascend`` ``GPU`` ``CPU``
1475
+
1476
+ Examples:
1477
+ >>> import mindspore.numpy as np
1478
+ >>> x = np.linspace(0, 1, 3)
1479
+ >>> y = np.linspace(0, 1, 2)
1480
+ >>> xv, yv = np.meshgrid(x, y)
1481
+ >>> print(xv)
1482
+ [[0. 0.5 1. ]
1483
+ [0. 0.5 1. ]]
1484
+ >>> print(yv)
1485
+ [[0. 0. 0.]
1486
+ [1. 1. 1.]]
1487
+ >>> xv, yv = np.meshgrid(x, y, sparse=True)
1488
+ >>> print(xv)
1489
+ [[0. 0.5 1. ]]
1490
+ >>> print(yv)
1491
+ [[0.]
1492
+ [1.]]
1493
+ """
1494
+ _check_input_tensor(*xi)
1495
+ if not isinstance(sparse, bool):
1496
+ _raise_type_error('argument sparse should be boolean')
1497
+ if indexing not in ('xy', 'ij'):
1498
+ _raise_type_error("Valid values for `indexing` are 'xy' and 'ij'.")
1499
+
1500
+ shape_out = ()
1501
+ for x in xi:
1502
+ shape_out += (x.size,)
1503
+ if _is_shape_empty(shape_out):
1504
+ return ones(shape_out)
1505
+
1506
+ grids = []
1507
+ for x in xi:
1508
+ if F.rank(x) == 1:
1509
+ grids.append(x)
1510
+ else:
1511
+ grids.append(ravel(x))
1512
+ ndim = len(grids)
1513
+
1514
+ cartesian = indexing == 'xy'
1515
+ shape_out = ()
1516
+ for i in range(len(grids)):
1517
+ grid_index = _index(i, ndim, cartesian=cartesian)
1518
+ shape_out += (F.shape(grids[grid_index])[0],)
1519
+
1520
+ res = []
1521
+ for i, x in enumerate(grids):
1522
+ grid_index = _index(i, ndim, cartesian=cartesian)
1523
+ shape_expanded = _expanded_shape(ndim, shape_out[grid_index], grid_index)
1524
+ x = x.reshape(shape_expanded)
1525
+ if not sparse:
1526
+ x = F.tile(x, _tile_size(shape_expanded, shape_out, ndim))
1527
+ res.append(x)
1528
+ return res
1529
+
1530
+
1531
+ class NdGrid:
1532
+ """
1533
+ Construct a multi-dimensional "meshgrid".
1534
+
1535
+ ``grid = NdGrid()`` creates an instance which will return a mesh-grid
1536
+ when indexed.
1537
+ If instantiated with an argument of ``sparse=True``, the mesh-grid is
1538
+ open (or not fleshed out) so that only one-dimension of each
1539
+ returned argument is greater than 1.
1540
+
1541
+ Args:
1542
+ sparse (bool): Whether the grid is sparse or not. Default is
1543
+ False.
1544
+
1545
+ Returns:
1546
+ Tensor or tuple of tensor, a meshgrid. If ``sparse=False``, returns
1547
+ tensors are all of the same dimensions; and if ``sparse=True``,
1548
+ returns tensors with only one dimension not equal to `1`.
1549
+ """
1550
+
1551
+ def __init__(self, sparse=False):
1552
+ self.sparse = sparse
1553
+
1554
+ def __getitem__(self, keys):
1555
+ if isinstance(keys, slice):
1556
+ keys = (keys,)
1557
+
1558
+ xi = []
1559
+ for k in keys:
1560
+ if not isinstance(k.start, int) or not isinstance(k.stop, int):
1561
+ _raise_type_error('slice indices must be integers')
1562
+ if k.step:
1563
+ step = k.step
1564
+ else:
1565
+ step = 1
1566
+ if isinstance(step, complex):
1567
+ v = linspace(k.start, k.stop, int(abs(step)))
1568
+ else:
1569
+ v = arange(k.start, k.stop, step)
1570
+ xi.append(v)
1571
+ grids = meshgrid(*xi, sparse=self.sparse, indexing='ij')
1572
+
1573
+ if len(grids) == 1:
1574
+ return grids[0]
1575
+ if self.sparse:
1576
+ return grids
1577
+
1578
+ if isinstance(grids, (Tensor, Tensor_)):
1579
+ return grids
1580
+ expanded = []
1581
+ for grid in grids:
1582
+ expanded.append(F.expand_dims(grid, 0))
1583
+ res = concatenate(tuple(expanded))
1584
+ return res
1585
+
1586
+
1587
+ class MGridClass(NdGrid):
1588
+ """
1589
+ mgrid is an `NdGrid` instance with ``sparse=False``.
1590
+
1591
+ The dimension and number of the output arrays are equal to the number
1592
+ of indexing dimensions. If the step length is not a complex number,
1593
+ then the stop is not inclusive. However, if the step length is a complex
1594
+ number (e.g. 5j), then the integer part of its magnitude is interpreted
1595
+ as specifying the number of points to create between the start and
1596
+ stop values, where the stop value is inclusive.
1597
+
1598
+ Note:
1599
+ Not supported in graph mode.
1600
+ Unlike Numpy, if the step length is a complex number with a real
1601
+ component, the step length is handled as equivalent to
1602
+ ``int(abs(step))``.
1603
+
1604
+ Returns:
1605
+ Tensor or tuple of tensor, a meshgrid.
1606
+
1607
+ Raises:
1608
+ TypeError: If slicing indices are not integers.
1609
+
1610
+ Supported Platforms:
1611
+ ``Ascend`` ``GPU`` ``CPU``
1612
+
1613
+ Examples:
1614
+ >>> import mindspore.numpy as np
1615
+ >>> output = np.mgrid[0:5, 0:5]
1616
+ >>> print(output)
1617
+ [[[0 0 0 0 0]
1618
+ [1 1 1 1 1]
1619
+ [2 2 2 2 2]
1620
+ [3 3 3 3 3]
1621
+ [4 4 4 4 4]]
1622
+ [[0 1 2 3 4]
1623
+ [0 1 2 3 4]
1624
+ [0 1 2 3 4]
1625
+ [0 1 2 3 4]
1626
+ [0 1 2 3 4]]]
1627
+ >>> output = mgrid[-1:1:5j]
1628
+ >>> print(output)
1629
+ [-1. -0.5 0. 0.5 1. ]
1630
+ """
1631
+
1632
+ def __init__(self):
1633
+ super(MGridClass, self).__init__(sparse=False)
1634
+
1635
+
1636
+ class OGridClass(NdGrid):
1637
+ """
1638
+ ogrid is an `NdGrid` instance with ``sparse=True``.
1639
+
1640
+ The dimension and number of the output arrays are equal to the number
1641
+ of indexing dimensions. If the step length is not a complex number,
1642
+ then the stop is not inclusive. However, if the step length is a complex
1643
+ number (e.g. 5j), then the integer part of its magnitude is interpreted
1644
+ as specifying the number of points to create between the start and
1645
+ stop values, where the stop value is inclusive.
1646
+
1647
+ Note:
1648
+ Not supported in graph mode.
1649
+ Unlike Numpy, if the step length is a complex number with a real
1650
+ component, the step length is handled as equivalent to
1651
+ ``int(abs(step))``.
1652
+
1653
+ Raises:
1654
+ TypeError: If slicing indices are not integers.
1655
+
1656
+ Supported Platforms:
1657
+ ``Ascend`` ``GPU`` ``CPU``
1658
+
1659
+ Examples:
1660
+ >>> import mindspore.numpy as np
1661
+ >>> output = np.ogrid[0:5,0:5]
1662
+ >>> print(output)
1663
+ [Tensor(shape=[5, 1], dtype=Int32, value=
1664
+ [[0],
1665
+ [1],
1666
+ [2],
1667
+ [3],
1668
+ [4]]), Tensor(shape=[1, 5], dtype=Int32, value=
1669
+ [[0, 1, 2, 3, 4]])]
1670
+ >>> output = ogrid[-1:1:5j]
1671
+ >>> print(output)
1672
+ [-1. -0.5 0. 0.5 1. ]
1673
+ """
1674
+
1675
+ def __init__(self):
1676
+ super(OGridClass, self).__init__(sparse=True)
1677
+
1678
+
1679
+ mgrid = MGridClass()
1680
+
1681
+ ogrid = OGridClass()
1682
+
1683
+
1684
+ def diag(v, k=0):
1685
+ """
1686
+ Extracts a diagonal or construct a diagonal array.
1687
+
1688
+ Args:
1689
+ v (Tensor): If `v` is a 2-D array, return a copy of its `k-th` diagonal.
1690
+ If `v` is a 1-D array, return a 2-D array with v on the `k-th` diagonal.
1691
+ k (int, optional): Diagonal in question. The default is 0. Use ``k>0`` for
1692
+ diagonals above the main diagonal, and ``k<0`` for diagonals below the
1693
+ main diagonal.
1694
+
1695
+ Returns:
1696
+ Tensor, the extracted diagonal or constructed diagonal array.
1697
+
1698
+ Raises:
1699
+ ValueError: If input is not 1-D or 2-D.
1700
+
1701
+ Supported Platforms:
1702
+ ``Ascend`` ``GPU`` ``CPU``
1703
+
1704
+ Examples:
1705
+ >>> import mindspore.numpy as np
1706
+ >>> x = np.arange(9).reshape((3,3))
1707
+ >>> print(x)
1708
+ [[0 1 2]
1709
+ [3 4 5]
1710
+ [6 7 8]]
1711
+ >>> output = np.diag(x)
1712
+ >>> print(output)
1713
+ [0 4 8]
1714
+ >>> output = np.diag(x, k=1)
1715
+ >>> print(output)
1716
+ [1 5]
1717
+ >>> output = np.diag(x, k=-1)
1718
+ >>> print(output)
1719
+ [3 7]
1720
+ """
1721
+ ndim = F.rank(v)
1722
+ if ndim == 1:
1723
+ return diagflat(v, k=k)
1724
+ if ndim == 2:
1725
+ shape = F.shape(v)
1726
+ dtype = F.dtype(v)
1727
+ if _is_shape_empty(shape):
1728
+ return _empty(dtype, (0,))
1729
+ e = eye(shape[0], shape[1], k, dtype)
1730
+ prod = F.tensor_mul(v, e)
1731
+
1732
+ cast_type = dtype
1733
+ if not _check_is_float(dtype):
1734
+ # reduce sum only supports float types
1735
+ cast_type = mstype.float32
1736
+ prod = F.cast(prod, cast_type)
1737
+
1738
+ res = F.reduce_sum(prod, 1)
1739
+ res = res[_max(0, -k): _min(shape[0], _max(0, shape[1] - k))]
1740
+
1741
+ if not _check_same_type(cast_type, dtype):
1742
+ res = F.cast(res, dtype)
1743
+
1744
+ return res
1745
+ return _raise_value_error("Input must be 1- or 2-d.")
1746
+
1747
+
1748
+ def diagflat(v, k=0):
1749
+ """
1750
+ Creates a two-dimensional array with the flattened input as a diagonal.
1751
+
1752
+ Note:
1753
+ On GPU, the supported dtypes are np.float16, and np.float32.
1754
+
1755
+ Args:
1756
+ v (Tensor): Input data, which is flattened and set as the `k-th` diagonal
1757
+ of the output.
1758
+ k (int, optional): Diagonal to set; 0, the default, corresponds to the
1759
+ "main" diagonal, a positive (negative) `k` giving the number of the
1760
+ diagonal above (below) the main.
1761
+
1762
+ Returns:
1763
+ Tensor, The 2-D output array.
1764
+
1765
+ Raises:
1766
+ TypeError: If the input is not a tensor.
1767
+
1768
+ Supported Platforms:
1769
+ ``Ascend`` ``GPU`` ``CPU``
1770
+
1771
+ Examples:
1772
+ >>> import mindspore.numpy as np
1773
+ >>> output = np.diagflat(np.asarray([[1,2], [3,4]]))
1774
+ >>> print(output)
1775
+ [[1 0 0 0]
1776
+ [0 2 0 0]
1777
+ [0 0 3 0]
1778
+ [0 0 0 4]]
1779
+ >>> output = np.diagflat(np.asarray([1,2]), 1)
1780
+ >>> print(output)
1781
+ [[0 1 0]
1782
+ [0 0 2]
1783
+ [0 0 0]]
1784
+ """
1785
+ _check_input_tensor(v)
1786
+ dtype = F.dtype(v)
1787
+ k_abs = _abs(k)
1788
+ if _is_shape_empty(F.shape(v)):
1789
+ return zeros((k_abs, k_abs), dtype)
1790
+
1791
+ v = ravel(v)
1792
+ size = F.shape(v)[0]
1793
+ e = eye(size, size, 0, dtype)
1794
+ res = F.tensor_mul(v, e)
1795
+
1796
+ if k != 0:
1797
+ pad_y = zeros((size, k_abs), dtype)
1798
+ pad_x = zeros((k_abs, size + k_abs), dtype)
1799
+ if k < 0:
1800
+ res = concatenate((res, pad_y), axis=1)
1801
+ res = concatenate((pad_x, res), axis=0)
1802
+ else:
1803
+ res = concatenate((pad_y, res), axis=1)
1804
+ res = concatenate((res, pad_x), axis=0)
1805
+ return res
1806
+
1807
+
1808
+ def diag_indices(n, ndim=2):
1809
+ """
1810
+ Returns the indices to access the main diagonal of an array.
1811
+
1812
+ This returns a tuple of indices that can be used to access the main
1813
+ diagonal of an array a with ``a.ndim >= 2`` dimensions and shape `(n, n, …, n)`.
1814
+ For ``a.ndim = 2`` this is the usual diagonal, for ``a.ndim > 2`` this is the set
1815
+ of indices to access ``a[i, i, ..., i]`` for ``i = [0..n-1]``.
1816
+
1817
+ Args:
1818
+ n (int): The size, along each dimension, of the arrays for which
1819
+ the returned indices can be used.
1820
+ ndim (int, optional): The number of dimensions.
1821
+
1822
+ Returns:
1823
+ Tuple of Tensor.
1824
+
1825
+ Raises:
1826
+ TypeError: If input are not integers.
1827
+
1828
+ Supported Platforms:
1829
+ ``Ascend`` ``GPU`` ``CPU``
1830
+
1831
+ Examples:
1832
+ >>> import mindspore.numpy as np
1833
+ >>> output = np.diag_indices(5, 3)
1834
+ >>> print(output)
1835
+ (Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
1836
+ Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]),
1837
+ Tensor(shape=[5], dtype=Int32, value= [0, 1, 2, 3, 4]))
1838
+ """
1839
+ if not isinstance(n, int) or not isinstance(ndim, int):
1840
+ _raise_type_error('input must be integers')
1841
+ return _list_comprehensions(ndim, arange(start=0, stop=n), True)
1842
+
1843
+
1844
+ def ix_(*args):
1845
+ r"""
1846
+ Constructs an open mesh from multiple sequences.
1847
+
1848
+ This function takes `N` 1-D sequences and returns `N` outputs with `N`
1849
+ dimensions each, such that the shape is 1 in all but one dimension
1850
+ and the dimension with the non-unit shape value cycles through all
1851
+ N dimensions.
1852
+ Using ix\_ one can quickly construct index arrays that will index
1853
+ the cross product. ``a[np.ix_([1,3],[2,5])]`` returns the array
1854
+ ``[[a[1,2] a[1,5]], [a[3,2] a[3,5]]]``.
1855
+
1856
+ Note:
1857
+ Boolean masks are not supported.
1858
+
1859
+ Args:
1860
+ *args (Tensor): 1-D sequences.
1861
+
1862
+ Returns:
1863
+ Tuple of Tensor, `N` arrays with `N` dimensions each, with `N` the
1864
+ number of input sequences. Together these arrays form an open
1865
+ mesh.
1866
+
1867
+ Raises:
1868
+ TypeError: If the input is not a tensor.
1869
+
1870
+ Supported Platforms:
1871
+ ``Ascend`` ``GPU`` ``CPU``
1872
+
1873
+ Examples:
1874
+ >>> import mindspore.numpy as np
1875
+ >>> ixgrid = np.ix_(np.array([0, 1]), np.array([2, 4]))
1876
+ >>> print(ixgrid)
1877
+ (Tensor(shape=[2, 1], dtype=Int32, value=
1878
+ [[0],
1879
+ [1]]), Tensor(shape=[1, 2], dtype=Int32, value=
1880
+ [[2, 4]]))
1881
+ """
1882
+ _check_input_tensor(*args)
1883
+ ndim = len(args)
1884
+ res = ()
1885
+ for i, arr in enumerate(args):
1886
+ if F.rank(arr) != 1:
1887
+ return _raise_value_error('Cross index must be 1 dimensional')
1888
+ res += (F.reshape(arr, _expanded_shape(ndim, arr.size, i)),)
1889
+ return res
1890
+
1891
+
1892
+ def vander(x, N=None, increasing=False):
1893
+ """
1894
+ Generates a Vandermonde matrix.
1895
+
1896
+ The columns of the output matrix are powers of the input vector. The order of
1897
+ the powers is determined by the increasing boolean argument. Specifically, when
1898
+ increasing is `False`, the i-th output column is the input vector raised element-wise
1899
+ to the power of :math:`N - i - 1`. Such a matrix with a geometric progression in each row
1900
+ is named for Alexandre-Theophile Vandermonde.
1901
+
1902
+ Args:
1903
+ x (Union[list, tuple, Tensor]): 1-D input array.
1904
+ N (int, optional): Number of columns in the output. If N is not specified, a
1905
+ square array is returned (``N = len(x)``).
1906
+ increasing (bool, optional): Order of the powers of the columns. If True, the
1907
+ powers increase from left to right, if False (the default) they are reversed.
1908
+
1909
+ Returns:
1910
+ Vandermonde matrix. If `increasing` is `False`, the first column is :math:`x^{(N-1)}`,
1911
+ the second :math:`x^{(N-2)}` and so forth. If `increasing` is `True`, the columns are
1912
+ :math:`x^0, x^1, ..., x^{(N-1)}`.
1913
+
1914
+ Raises:
1915
+ TypeError: If inputs have types not specified above.
1916
+ ValueError: If `x` is not 1-D, or `N` < 0.
1917
+
1918
+ Supported Platforms:
1919
+ ``Ascend`` ``GPU`` ``CPU``
1920
+
1921
+ Examples:
1922
+ >>> import mindspore.numpy as np
1923
+ >>> print(np.vander([1., 2., 3., 4., 5.]))
1924
+ [[ 1. 1. 1. 1. 1.]
1925
+ [ 16. 8. 4. 2. 1.]
1926
+ [ 81. 27. 9. 3. 1.]
1927
+ [256. 64. 16. 4. 1.]
1928
+ [625. 125. 25. 5. 1.]]
1929
+ """
1930
+ if isinstance(x, (list, tuple)):
1931
+ x = asarray_const(x)
1932
+ elif not isinstance(x, Tensor):
1933
+ _raise_type_error("Input x must be list, tuple or Tensor, but got ", x)
1934
+ if x.ndim != 1:
1935
+ _raise_value_error("Input x must be 1-D, but got dimension=", x.ndim)
1936
+ N = N or x.size
1937
+ if not isinstance(N, int):
1938
+ _raise_type_error("Input N must be an integer.")
1939
+ if N <= 0:
1940
+ _raise_value_error("Input N must > 0.")
1941
+ if not isinstance(increasing, bool):
1942
+ _raise_type_error("increasing must be a bool.")
1943
+ exponent = _iota(x.dtype, N, increasing)
1944
+ x = F.expand_dims(x, 1)
1945
+ exponent = F.expand_dims(exponent, 0)
1946
+ return F.tensor_pow(x, exponent)
1947
+
1948
+
1949
+ def indices(dimensions, dtype=mstype.int32, sparse=False):
1950
+ """
1951
+ Returns an array representing the indices of a grid.
1952
+
1953
+ Computes an array where the subarrays contain index values 0, 1, …
1954
+ varying only along the corresponding axis.
1955
+
1956
+ Args:
1957
+ dimensions (Union[list(int), tuple]): The shape of the grid.
1958
+ dtype (:class:`mindspore.dtype`, optional): Data type of the result. Default: ``mstype.int32``.
1959
+ sparse (boolean, optional): Default: ``False`` . Return a sparse
1960
+ representation of the grid instead of a dense representation.
1961
+
1962
+ Returns:
1963
+ Tensor or tuple of Tensor, If `sparse` is False, returns one array
1964
+ of grid indices, ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
1965
+ If sparse is True, returns a tuple of arrays, with
1966
+ ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
1967
+ ``dimensions[i]`` in the `ith` place
1968
+
1969
+ Raises:
1970
+ TypeError: If input dimensions is not a tuple or list.
1971
+
1972
+ Supported Platforms:
1973
+ ``Ascend`` ``GPU`` ``CPU``
1974
+
1975
+ Examples:
1976
+ >>> import mindspore.numpy as np
1977
+ >>> grid = np.indices((2, 3))
1978
+ >>> print(grid)
1979
+ [Tensor(shape=[2, 3], dtype=Int32, value=
1980
+ [[0, 0, 0],
1981
+ [1, 1, 1]]), Tensor(shape=[2, 3], dtype=Int32, value=
1982
+ [[0, 1, 2],
1983
+ [0, 1, 2]])]
1984
+ """
1985
+ if not isinstance(dimensions, (tuple, list)):
1986
+ _raise_type_error('Shape of the grid must be tuple or list')
1987
+ grids = ()
1988
+ for d in dimensions:
1989
+ grids += (arange(d, dtype=dtype),)
1990
+ return meshgrid(*grids, sparse=sparse, indexing='ij')
1991
+
1992
+
1993
+ def _check_window_size(x):
1994
+ """Returns True if window size is greater than 1."""
1995
+ if not isinstance(x, int):
1996
+ _raise_type_error('the number fo points should be an int')
1997
+ return x > 1
1998
+
1999
+
2000
+ def bartlett(M):
2001
+ """
2002
+ Returns the Bartlett window.
2003
+ The Bartlett window is very similar to a triangular window, except that the
2004
+ end points are at zero. It is often used in signal processing for tapering a
2005
+ signal, without generating too much ripple in the frequency domain.
2006
+
2007
+ Args:
2008
+ M (int): Number of points in the output window. If zero or less, an empty
2009
+ array is returned.
2010
+
2011
+ Returns:
2012
+ Tensor, the triangular window, with the maximum value normalized to one
2013
+ (the value one appears only if the number of samples is odd), with the
2014
+ first and last samples equal to zero.
2015
+
2016
+ Raises:
2017
+ TypeError: If `M` is not an int.
2018
+
2019
+ Supported Platforms:
2020
+ ``Ascend`` ``GPU`` ``CPU``
2021
+
2022
+ Examples:
2023
+ >>> import mindspore.numpy as np
2024
+ >>> print(np.bartlett(12))
2025
+ [0. 0.18181819 0.36363637 0.5454545 0.72727275 0.9090909
2026
+ 0.9090909 0.72727275 0.5454545 0.36363637 0.18181819 0. ]
2027
+ """
2028
+ if not _check_window_size(M):
2029
+ return ones(_max(0, M))
2030
+ n = _iota(mstype.float32, M)
2031
+ m_minus_one = _to_tensor(M - 1)
2032
+ return _to_tensor(1) - F.absolute(_to_tensor(2) * n - m_minus_one) / m_minus_one
2033
+
2034
+
2035
+ def blackman(M):
2036
+ """
2037
+ Returns the Blackman window.
2038
+ The Blackman window is a taper formed by using the first three terms of a
2039
+ summation of cosines. It was designed to have close to the minimal leakage
2040
+ possible. It is close to optimal, only slightly worse than a Kaiser window.
2041
+
2042
+ Args:
2043
+ M (int): Number of points in the output window. If zero or less, an empty
2044
+ array is returned.
2045
+
2046
+ Returns:
2047
+ Tensor, the window, with the maximum value normalized to one (the value
2048
+ one appears only if the number of samples is odd).
2049
+
2050
+ Raises:
2051
+ TypeError: If `M` is not an int.
2052
+
2053
+ Supported Platforms:
2054
+ ``Ascend`` ``GPU`` ``CPU``
2055
+
2056
+ Examples:
2057
+ >>> import mindspore.numpy as np
2058
+ >>> print(np.blackman(12))
2059
+ [-1.4901161e-08 3.2606430e-02 1.5990365e-01 4.1439798e-01
2060
+ 7.3604518e-01 9.6704674e-01 9.6704674e-01 7.3604518e-01
2061
+ 4.1439798e-01 1.5990365e-01 3.2606430e-02 -1.4901161e-08]
2062
+ """
2063
+ if not _check_window_size(M):
2064
+ return ones(_max(0, M))
2065
+ n_doubled = arange(1 - M, M, 2, dtype=mstype.float32)
2066
+ return (_to_tensor(0.42) + _to_tensor(0.5) * F.cos(_to_tensor(pi / (M - 1)) * n_doubled) +
2067
+ _to_tensor(0.08) * F.cos(_to_tensor(2 * pi / (M - 1)) * n_doubled))
2068
+
2069
+
2070
+ def hamming(M):
2071
+ """
2072
+ Returns the Hamming window.
2073
+ The Hamming window is a taper formed by using a weighted cosine.
2074
+
2075
+ Args:
2076
+ M (int): Number of points in the output window. If zero or less, an empty
2077
+ array is returned.
2078
+
2079
+ Returns:
2080
+ Tensor, the window, with the maximum value normalized to one (the value
2081
+ one appears only if the number of samples is odd).
2082
+
2083
+ Raises:
2084
+ TypeError: If `M` is not an int.
2085
+
2086
+ Supported Platforms:
2087
+ ``Ascend`` ``GPU`` ``CPU``
2088
+
2089
+ Examples:
2090
+ >>> import mindspore.numpy as np
2091
+ >>> print(np.hamming(12))
2092
+ [0.08000001 0.15302339 0.34890914 0.6054648 0.841236 0.9813669
2093
+ 0.9813668 0.8412359 0.6054647 0.34890908 0.15302327 0.08000001]
2094
+ """
2095
+ if not _check_window_size(M):
2096
+ return ones(_max(0, M))
2097
+ n = _iota(mstype.float32, M)
2098
+ return _to_tensor(0.54) - _to_tensor(0.46) * F.cos(_to_tensor(2 * pi / (M - 1)) * n)
2099
+
2100
+
2101
+ def hanning(M):
2102
+ """
2103
+ Returns the Hanning window.
2104
+ The Hanning window is a taper formed by using a weighted cosine.
2105
+
2106
+ Args:
2107
+ M (int): Number of points in the output window. If zero or less, an empty
2108
+ array is returned.
2109
+
2110
+ Returns:
2111
+ Tensor, the window, with the maximum value normalized to one (the value
2112
+ one appears only if the number of samples is odd).
2113
+
2114
+ Raises:
2115
+ TypeError: If `M` is not an int.
2116
+
2117
+ Supported Platforms:
2118
+ ``Ascend`` ``GPU`` ``CPU``
2119
+
2120
+ Examples:
2121
+ >>> import mindspore.numpy as np
2122
+ >>> print(np.hanning(12))
2123
+ [0. 0.07937324 0.29229254 0.5711574 0.8274304 0.9797465
2124
+ 0.97974646 0.82743025 0.5711573 0.29229245 0.07937312 0. ]
2125
+ """
2126
+ if not _check_window_size(M):
2127
+ return ones(_max(0, M))
2128
+ n = _iota(mstype.float32, M)
2129
+ return _to_tensor(0.5) - _to_tensor(0.5) * F.cos(_to_tensor(2 * pi / (M - 1)) * n)
2130
+
2131
+
2132
+ @constexpr
2133
+ def tri_indices(n, k=0, m=None, upper=True):
2134
+ """Returns triu/tril indices in o(nm) time."""
2135
+ if not isinstance(n, (int, float, bool)):
2136
+ raise TypeError("Input n must be a number.")
2137
+ if not isinstance(k, (int, float, bool)):
2138
+ raise TypeError("Input k must be a number.")
2139
+ if m is None:
2140
+ m = n
2141
+ elif not isinstance(m, (int, float, bool)):
2142
+ raise TypeError("Input m must be a number.")
2143
+ if upper:
2144
+ compare = operator.ge
2145
+ else:
2146
+ compare = operator.le
2147
+ x_coordinate = []
2148
+ y_coordinate = []
2149
+ # math.ceil is used to match numpy's behaviour
2150
+ for i in range(math.ceil(n)):
2151
+ curr_limit = i + k
2152
+ for j in range(math.ceil(m)):
2153
+ if compare(j, curr_limit):
2154
+ x_coordinate.append(i)
2155
+ y_coordinate.append(j)
2156
+ return asarray_const(x_coordinate), asarray_const(y_coordinate)
2157
+
2158
+
2159
+ def triu_indices(n, k=0, m=None):
2160
+ """
2161
+ Returns the indices for the upper-triangle of an (n, m) array.
2162
+
2163
+ Args:
2164
+ n (int): The size of the arrays for which the returned indices will be valid.
2165
+ k (int, optional): Diagonal offset, default: ``0`` .
2166
+ m (int, optional): The column dimension of the arrays for which the returned
2167
+ arrays will be valid. By default `m` is taken equal to `n`. Default: ``None`` .
2168
+
2169
+ Returns:
2170
+ The indices for the triangle. The returned tuple contains two tensors, each
2171
+ with the indices along one dimension of the tensor.
2172
+
2173
+ Raises:
2174
+ TypeError: If `n`, `k`, `m` are not numbers.
2175
+
2176
+ Supported Platforms:
2177
+ ``Ascend`` ``GPU`` ``CPU``
2178
+
2179
+ Examples:
2180
+ >>> import mindspore.numpy as np
2181
+ >>> print(np.triu_indices(3))
2182
+ (Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
2183
+ Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
2184
+ """
2185
+ return tri_indices(n, k, m, True)
2186
+
2187
+
2188
+ def tril_indices(n, k=0, m=None):
2189
+ """
2190
+ Returns the indices for the lower-triangle of an (n, m) array.
2191
+
2192
+ Args:
2193
+ n (int): The size of the arrays for which the returned indices will be valid.
2194
+ k (int, optional): Diagonal offset, default: ``0`` .
2195
+ m (int, optional): The column dimension of the arrays for which the returned
2196
+ arrays will be valid. By default `m` is taken equal to `n`. Default: ``None`` .
2197
+
2198
+ Returns:
2199
+ The indices for the triangle. The returned tuple contains two tensors, each
2200
+ with the indices along one dimension of the tensor.
2201
+
2202
+ Raises:
2203
+ TypeError: If `n`, `k`, `m` are not numbers.
2204
+
2205
+ Supported Platforms:
2206
+ ``Ascend`` ``GPU`` ``CPU``
2207
+
2208
+ Examples:
2209
+ >>> import mindspore.numpy as np
2210
+ >>> print(np.tril_indices(3))
2211
+ (Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
2212
+ Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
2213
+ """
2214
+ return tri_indices(n, k, m, False)
2215
+
2216
+
2217
+ def triu_indices_from(arr, k=0):
2218
+ """
2219
+ Returns the indices for the upper-triangle of `arr`.
2220
+
2221
+ Args:
2222
+ arr (Union[Tensor, list, tuple]): 2-dimensional array.
2223
+ k (int, optional): Diagonal offset, default: ``0`` .
2224
+
2225
+ Returns:
2226
+ triu_indices_from, tuple of 2 tensor, shape(N)
2227
+ Indices for the upper-triangle of `arr`.
2228
+
2229
+ Raises:
2230
+ TypeError: If `arr` cannot be converted to tensor, or `k` is not a number.
2231
+ ValueError: If `arr` cannot be converted to a 2-dimensional tensor.
2232
+
2233
+ Supported Platforms:
2234
+ ``Ascend`` ``GPU`` ``CPU``
2235
+
2236
+ Examples:
2237
+ >>> import mindspore.numpy as np
2238
+ >>> tensor = np.ones((3,3))
2239
+ >>> print(np.triu_indices_from(tensor))
2240
+ (Tensor(shape=[6], dtype=Int32, value= [0, 0, 0, 1, 1, 2]),
2241
+ Tensor(shape=[6], dtype=Int32, value= [0, 1, 2, 1, 2, 2]))
2242
+ """
2243
+ arr = asarray(arr)
2244
+ if arr.ndim != 2:
2245
+ _raise_value_error("input array must be 2-d")
2246
+ return triu_indices(arr.shape[-2], k=k, m=arr.shape[-1])
2247
+
2248
+
2249
+ def tril_indices_from(arr, k=0):
2250
+ """
2251
+ Returns the indices for the lower-triangle of `arr`.
2252
+
2253
+ Args:
2254
+ arr (Union[Tensor, list, tuple]): 2-dimensional array.
2255
+ k (int, optional): Diagonal offset, default: ``0`` .
2256
+
2257
+ Returns:
2258
+ triu_indices_from, tuple of 2 tensor, shape(N)
2259
+ Indices for the lower-triangle of `arr`.
2260
+
2261
+ Raises:
2262
+ TypeError: If `arr` cannot be converted to tensor, or `k` is not a number.
2263
+ ValueError: If `arr` cannot be converted to a 2-dimensional tensor.
2264
+
2265
+ Supported Platforms:
2266
+ ``Ascend`` ``GPU`` ``CPU``
2267
+
2268
+ Examples:
2269
+ >>> import mindspore.numpy as np
2270
+ >>> tensor = np.ones((3,3))
2271
+ >>> print(np.tril_indices_from(tensor))
2272
+ (Tensor(shape=[6], dtype=Int32, value= [0, 1, 1, 2, 2, 2]),
2273
+ Tensor(shape=[6], dtype=Int32, value= [0, 0, 1, 0, 1, 2]))
2274
+ """
2275
+ arr = asarray(arr)
2276
+ if arr.ndim != 2:
2277
+ _raise_value_error("input array must be 2-d")
2278
+ return tril_indices(arr.shape[-2], k=k, m=arr.shape[-1])
2279
+
2280
+
2281
+ def histogram_bin_edges(a, bins=10, range=None, weights=None): # pylint: disable=redefined-builtin
2282
+ """
2283
+ Function to calculate only the edges of the bins used by the histogram function.
2284
+
2285
+ Note:
2286
+ String values for `bins` is not supported.
2287
+
2288
+ Args:
2289
+ a (Union[int, float, bool, list, tuple, Tensor]): Input data. The histogram
2290
+ is computed over the flattened array.
2291
+ bins (Union[int, tuple, list, Tensor], optional): If `bins` is an int, it defines the number
2292
+ of equal-width bins in the given range (10, by default). If `bins` is a
2293
+ sequence, it defines the bin edges, including the rightmost edge,
2294
+ allowing for non-uniform bin widths.
2295
+ range ((float, float), optional): The lower and upper range of the bins. If
2296
+ not provided, `range` is simply ``(a.min(), a.max())``. Values outside
2297
+ the range are ignored. The first element of the range must be less than
2298
+ or equal to the second. Default: ``None`` .
2299
+ weights (Union[int, float, bool, list, tuple, Tensor], optional): An array of weights,
2300
+ of the same shape as `a`. Each value in `a` only contributes its associated weight
2301
+ towards the bin count (instead of 1). This is currently not used by any of the bin
2302
+ estimators, but may be in the future. Default: ``None`` .
2303
+
2304
+ Returns:
2305
+ Tensor, the edges to pass into `histogram`.
2306
+
2307
+ Supported Platforms:
2308
+ ``Ascend`` ``GPU`` ``CPU``
2309
+
2310
+ Raises:
2311
+ TypeError: If `bins` is an array and not one-dimensional.
2312
+
2313
+ Examples:
2314
+ >>> import mindspore.numpy as np
2315
+ >>> arr = np.array([0, 0, 0, 1, 2, 3, 3, 4, 5])
2316
+ >>> print(np.histogram_bin_edges(arr, bins=2))
2317
+ [0. 2.5 5. ]
2318
+ """
2319
+ a = _to_tensor(a)
2320
+ if weights is not None:
2321
+ weights = _to_tensor(weights)
2322
+ if F.shape(a) != F.shape(weights):
2323
+ _raise_value_error('weights should have the same shape as a')
2324
+ if isinstance(bins, (tuple, list, Tensor)):
2325
+ bins = _to_tensor(bins)
2326
+ if F.rank(bins) != 1:
2327
+ _raise_value_error('`bins` must be 1d, when an array')
2328
+ return bins
2329
+ if isinstance(bins, str):
2330
+ # linspace does not support Tensor for num
2331
+ _raise_unimplemented_error('string value for `bins` not implemented')
2332
+ a = a.ravel().astype(mstype.float32)
2333
+ if range is None:
2334
+ start = F.reduce_min(a)
2335
+ end = F.reduce_max(a)
2336
+ else:
2337
+ if not isinstance(range, (list, tuple)) or len(range) != 2:
2338
+ _raise_value_error('`range` should take the form (start, end)')
2339
+ start, end = range
2340
+ if start > end:
2341
+ _raise_value_error('max must be larger than min in range parameter')
2342
+ start, end = _to_tensor(start, end)
2343
+ no_range = (end - start) == 0
2344
+ start = where(no_range, start - 0.5, start)
2345
+ end = where(no_range, end + 0.5, end)
2346
+ return linspace(start, end, bins + 1)
2347
+
2348
+
2349
+ def _pad_empty(arr, pad_width):
2350
+ """
2351
+ pads the array with constant values, used in mode: "empty"
2352
+ """
2353
+ dtype = arr.dtype
2354
+ for i in range(arr.ndim):
2355
+ shape = arr.shape
2356
+ pad_before = ()
2357
+ pad_after = ()
2358
+ # To avoid any memory issues, we don't make tensor with 0s in their shapes
2359
+ if pad_width[i][0] > 0:
2360
+ pad_before += (empty(_tuple_setitem(shape, i, pad_width[i][0]), dtype=dtype),)
2361
+ if pad_width[i][1] > 0:
2362
+ pad_after += (empty(_tuple_setitem(shape, i, pad_width[i][1]), dtype=dtype),)
2363
+ tensor_with_pad = pad_before + (arr,) + pad_after
2364
+ arr = concatenate(tensor_with_pad, axis=i)
2365
+ return arr
2366
+
2367
+
2368
+ def _pad_constant(arr, pad_width, value):
2369
+ """
2370
+ pads the array with constant values, used in mode: "constant"
2371
+ """
2372
+ dtype = arr.dtype
2373
+ for i in range(arr.ndim):
2374
+ shape = arr.shape
2375
+ pad_before = ()
2376
+ pad_after = ()
2377
+ # To avoid any memory issues, we don't make tensor with 0s in their shapes
2378
+ if pad_width[i][0] > 0:
2379
+ pad_before += (full(_tuple_setitem(shape, i, pad_width[i][0]), value[i][0], dtype=dtype),)
2380
+ if pad_width[i][1] > 0:
2381
+ pad_after += (full(_tuple_setitem(shape, i, pad_width[i][1]), value[i][1], dtype=dtype),)
2382
+ tensor_with_pad = pad_before + (arr,) + pad_after
2383
+ arr = concatenate(tensor_with_pad, axis=i)
2384
+ return arr
2385
+
2386
+
2387
+ def _pad_statistic(arr, pad_width, stat_length, stat_op):
2388
+ """
2389
+ pads the array with values calculated along the given axis, used in mode: "maximum",
2390
+ "minimum", "mean"
2391
+ """
2392
+ ndim = arr.ndim
2393
+ shape = arr.shape
2394
+ if stat_length is None:
2395
+ stat_length = _make_stat_length(shape)
2396
+ else:
2397
+ stat_length = _convert_pad_to_nd(stat_length, ndim)
2398
+ stat_length = _limit_stat_length(stat_length, shape)
2399
+ for i in range(ndim):
2400
+ pad_before = stat_op(_slice_along_axis(arr, i, 0, stat_length[i][0]), i)
2401
+ pad_before = (F.tile(pad_before, _tuple_setitem((1,) * ndim, i, pad_width[i][0])),)
2402
+ pad_after = stat_op(_slice_along_axis(arr, i, shape[i] - stat_length[i][1], shape[i]), i)
2403
+ pad_after = (F.tile(pad_after, _tuple_setitem((1,) * ndim, i, pad_width[i][1])),)
2404
+ tensor_with_pad = pad_before + (arr,) + pad_after
2405
+ arr = concatenate(tensor_with_pad, axis=i)
2406
+ return arr
2407
+
2408
+
2409
+ def _pad_edge(arr, pad_width):
2410
+ """pad_edge is equivalent to pad_statistic with stat_lenght=1, used in mode:"edge"."""
2411
+
2412
+ def identity_op(arr, axis):
2413
+ return arr
2414
+
2415
+ return _pad_statistic(arr, pad_width, 1, identity_op)
2416
+
2417
+
2418
+ def _pad_wrap(arr, pad_width):
2419
+ """The behaviour of wrap mode is consistent with jax.numpy, used in mode:"wrap"."""
2420
+ ndim = arr.ndim
2421
+ shape = arr.shape
2422
+ for i in range(ndim):
2423
+ padsize_before = pad_width[i][0] % shape[i]
2424
+ padsize_after = pad_width[i][1] % shape[i]
2425
+ total_repeats = pad_width[i][0] // shape[i] + 1 + pad_width[i][1] // shape[i]
2426
+ tensor_with_pad = ()
2427
+ # To avoid any memory issues, we don't make tensor with 0s in their shapes
2428
+ if padsize_before > 0:
2429
+ tensor_with_pad += (_slice_along_axis(arr, i, shape[i] - padsize_before, shape[i]),)
2430
+ tensor_with_pad += (F.tile(arr, _tuple_setitem((1,) * ndim, i, total_repeats)),)
2431
+ if padsize_after > 0:
2432
+ tensor_with_pad += (_slice_along_axis(arr, i, 0, padsize_after),)
2433
+ arr = concatenate(tensor_with_pad, axis=i)
2434
+ return arr
2435
+
2436
+
2437
+ def _pad_linear(arr, pad_width, end_values):
2438
+ """Pads the arr with linear range values, used in mode: "linear_ramp"."""
2439
+ ndim = arr.ndim
2440
+ shape = arr.shape
2441
+ dtype = arr.dtype
2442
+ end_values = _convert_pad_to_nd(end_values, ndim)
2443
+ for i in range(ndim):
2444
+ left_value = _slice_along_axis(arr, i, 0, 1)
2445
+ right_value = _slice_along_axis(arr, i, shape[i] - 1, shape[i])
2446
+ pad_before = ()
2447
+ pad_after = ()
2448
+ if pad_width[i][0] > 0:
2449
+ pad_before = (linspace(end_values[i][0], left_value, num=pad_width[i][0],
2450
+ endpoint=False, dtype=dtype, axis=i).squeeze(i + 1),)
2451
+ if pad_width[i][1] > 0:
2452
+ pad_after = linspace(right_value, end_values[i][1], num=pad_width[i][1] + 1,
2453
+ endpoint=True, dtype=dtype, axis=i).squeeze(i + 1)
2454
+ pad_after = (_slice_along_axis(pad_after, i, 1, pad_width[i][1] + 1),)
2455
+ tensor_with_pad = pad_before + (arr,) + pad_after
2456
+ arr = concatenate(tensor_with_pad, axis=i)
2457
+ return arr
2458
+
2459
+
2460
+ def _add_pads_before(arr, pad_args, mode):
2461
+ """handle pads before the array"""
2462
+ idx, array_length, times_to_pad_before, additional_pad_before, reflect_type = pad_args
2463
+ curr_pad = None
2464
+ endpoint_adder = None
2465
+ edge_before = _slice_along_axis(arr, idx, 0, 1)
2466
+ if mode == "reflect":
2467
+ endpoint_adder = 1
2468
+ else:
2469
+ endpoint_adder = 0
2470
+ # Deal with paddings before the original array
2471
+ for times in range(times_to_pad_before):
2472
+ if times < times_to_pad_before - 1:
2473
+ endpoint = array_length
2474
+ else:
2475
+ endpoint = additional_pad_before + endpoint_adder
2476
+ if endpoint != endpoint_adder:
2477
+ curr_pad = _slice_along_axis(arr, idx, endpoint_adder, endpoint)
2478
+ curr_pad = flip(curr_pad, axis=idx)
2479
+ if reflect_type == "odd":
2480
+ curr_pad = 2 * edge_before - curr_pad
2481
+ arr = P.Concat(idx)((curr_pad, arr))
2482
+ edge_before = _slice_along_axis(arr, idx, 0, 1)
2483
+ return arr
2484
+
2485
+
2486
+ def _add_pads_after(arr, pad_args, mode):
2487
+ """handle pads after the array"""
2488
+ idx, array_length, times_to_pad_after, additional_pad_after, reflect_type = pad_args
2489
+ curr_pad = None
2490
+ endpoint_adder = None
2491
+ edge_end = _slice_along_axis(arr, idx, arr.shape[idx] - 1, arr.shape[idx])
2492
+ if mode == "reflect":
2493
+ endpoint_adder = 1
2494
+ else:
2495
+ endpoint_adder = 0
2496
+ # Deal with paddings after the original array
2497
+ for times in range(times_to_pad_after):
2498
+ if times < times_to_pad_after - 1:
2499
+ startpoint = arr.shape[idx] - array_length
2500
+ else:
2501
+ startpoint = arr.shape[idx] - additional_pad_after - endpoint_adder
2502
+ if startpoint != arr.shape[idx] - endpoint_adder:
2503
+ curr_pad = _slice_along_axis(arr, idx, startpoint, arr.shape[idx] - endpoint_adder)
2504
+ curr_pad = flip(curr_pad, axis=idx)
2505
+ if reflect_type == "odd":
2506
+ curr_pad = 2 * edge_end - curr_pad
2507
+ arr = P.Concat(idx)((arr, curr_pad))
2508
+ edge_end = _slice_along_axis(arr, idx, arr.shape[idx] - 1, arr.shape[idx])
2509
+ return arr
2510
+
2511
+
2512
+ def _pad_symmetric(arr, pad_width, reflect_type):
2513
+ """pad the array with symmetric paddings"""
2514
+ for i in range(arr.ndim):
2515
+ array_length = arr.shape[i]
2516
+
2517
+ has_pad_before = (pad_width[i][0] > 0)
2518
+ has_pad_after = (pad_width[i][1] > 0)
2519
+
2520
+ times_to_pad_before = pad_width[i][0] // array_length + 1
2521
+ additional_pad_before = pad_width[i][0] % array_length
2522
+ times_to_pad_after = pad_width[i][1] // array_length + 1
2523
+ additional_pad_after = pad_width[i][1] % array_length
2524
+ if has_pad_before:
2525
+ # Deal with paddings before the original array
2526
+ pad_args = (i, array_length, times_to_pad_before, additional_pad_before, reflect_type)
2527
+ arr = _add_pads_before(arr, pad_args, "symmetric")
2528
+ if has_pad_after:
2529
+ # Deal with paddings after the original array
2530
+ pad_args = (i, array_length, times_to_pad_after, additional_pad_after, reflect_type)
2531
+ arr = _add_pads_after(arr, pad_args, "symmetric")
2532
+ return arr
2533
+
2534
+
2535
+ def _pad_reflect(arr, pad_width, reflect_type):
2536
+ """
2537
+ pad the array with reflect paddings, this is very similar to symmetric paddings,
2538
+ but differs at how edges are selected.
2539
+ """
2540
+ for i in range(arr.ndim):
2541
+ array_length = arr.shape[i]
2542
+ if array_length == 1:
2543
+ total_repeats = pad_width[i][0] + pad_width[i][1] + 1
2544
+ arr = F.tile(arr, _tuple_setitem((1,) * arr.ndim, i, total_repeats))
2545
+ else:
2546
+ has_pad_before = (pad_width[i][0] > 0)
2547
+ has_pad_after = (pad_width[i][1] > 0)
2548
+
2549
+ pad_size = array_length - 1
2550
+ times_to_pad_before = pad_width[i][0] // pad_size + 1
2551
+ additional_pad_before = pad_width[i][0] % pad_size
2552
+ times_to_pad_after = pad_width[i][1] // pad_size + 1
2553
+ additional_pad_after = pad_width[i][1] % pad_size
2554
+ if has_pad_before:
2555
+ # Deal with paddings before the original array
2556
+ pad_args = (i, array_length, times_to_pad_before, additional_pad_before, reflect_type)
2557
+ arr = _add_pads_before(arr, pad_args, "reflect")
2558
+ if has_pad_after:
2559
+ # Deal with paddings after the original array
2560
+ pad_args = (i, array_length, times_to_pad_after, additional_pad_after, reflect_type)
2561
+ arr = _add_pads_after(arr, pad_args, "reflect")
2562
+ return arr
2563
+
2564
+
2565
+ def _pad_func(arr, pad_width, func, **kwargs):
2566
+ """applies padding function over different axis."""
2567
+ # first creates a padded array with fixed length.
2568
+ arr_dim = arr.ndim
2569
+ pad_width = _convert_pad_to_nd(pad_width, arr_dim)
2570
+ arr = _pad_empty(arr, pad_width)
2571
+ for i in range(arr_dim):
2572
+ # function signature: padding_func(tensor, iaxis_pad_width, iaxis, kwargs)
2573
+ arr = apply_along_axis(func, i, arr, pad_width[i], i, kwargs)
2574
+ return arr
2575
+
2576
+
2577
+ @_primexpr
2578
+ def _make_stat_length(shape):
2579
+ """converts the stat_length values."""
2580
+ return tuple((shape[i], shape[i]) for i, _ in enumerate(shape))
2581
+
2582
+
2583
+ @_primexpr
2584
+ def _limit_stat_length(stat_length, shape):
2585
+ """limits the stat_length to current array length along given dimension."""
2586
+ return tuple((min(stat_pair[0], shape[i]), min(stat_pair[1], shape[i])) for i, stat_pair in enumerate(stat_length))
2587
+
2588
+
2589
+ def _convert_pad_to_nd(pad_values, ndim):
2590
+ """broadcasts the pad_values to (ndim * 2)"""
2591
+ if not isinstance(pad_values, (int, list, tuple, Tensor)):
2592
+ raise TypeError(
2593
+ "pad_width, stat_length, constant_values or end_values should only be int, list, tuple or tensor")
2594
+ pad_tensor = _to_tensor(pad_values)
2595
+ pad_shape = pad_tensor.shape
2596
+ if not pad_shape:
2597
+ pad_values = tuple((((pad_values,) * 2) for i in range(ndim)))
2598
+ elif pad_shape == (1,):
2599
+ pad_values = tuple((tuple(pad_values) * 2) for i in range(ndim))
2600
+ elif pad_shape == (2,):
2601
+ pad_values = tuple(tuple(pad_values) for i in range(ndim))
2602
+ elif pad_shape == (1, 2):
2603
+ pad_values = tuple(tuple(pad_values[0]) for i in range(ndim))
2604
+ elif pad_shape == (ndim, 2):
2605
+ pad_values = tuple(tuple(pad_pair) for pad_pair in pad_values)
2606
+ else:
2607
+ raise ValueError(f"input values must be able to broadcast to {(ndim, 2)}")
2608
+ return pad_values
2609
+
2610
+
2611
+ def pad(arr, pad_width, mode="constant", stat_length=None, constant_values=0,
2612
+ end_values=0, reflect_type="even", **kwargs):
2613
+ """
2614
+ Pads an array.
2615
+
2616
+ Note:
2617
+ Currently, `median` mode is not supported. `reflect` and `symmetric` mode
2618
+ only supports GPU backend.
2619
+
2620
+ Args:
2621
+ arr (Union[list, tuple, Tensor]): The array to pad.
2622
+ pad_width (Union[int, tuple, list]): Number of values padded to the edges of
2623
+ each axis. ``((before_1, after_1), ... (before_N, after_N))`` creates
2624
+ unique pad widths for each axis. ``((before, after),)`` yields same
2625
+ before and after pad for each axis. ``(pad,)`` or int is a shortcut
2626
+ for ``before = after = pad width`` for all axes.
2627
+ mode (string, optional):
2628
+ One of the following string values:
2629
+
2630
+ - constant (default): Pads with a constant value.
2631
+ - edge: Pads with the edge values of `arr`.
2632
+ - linear_ramp: Pads with the linear ramp between end_value and the `arr` edge value.
2633
+ - maximum: Pads with the maximum value of all or part of the vector along each axis.
2634
+ - mean: Pads with the mean value of all or part of the vector along each axis.
2635
+ - median: Pads with the median value of all or part of the vector along each axis.
2636
+ - minimum: Pads with the minimum value of all or part of the vector along each axis.
2637
+ - reflect: Pads with the reflection of the vector mirrored on the first
2638
+ and last values of the vector along each axis.
2639
+ - symmetric: Pads with the reflection of the vector mirrored along the edge
2640
+ of the `arr`.
2641
+ - wrap: Pads with the wrap of the vector along the axis. The first values
2642
+ are used to pad the end and the end values are used to pad the beginning.
2643
+ - empty: Pads with undefined values.
2644
+ - <function>: The padding function, if used, should modify and return a new 1-d tensor.
2645
+ It has the following signature: ``padding_func(tensor, iaxis_pad_width, iaxis, kwargs)``
2646
+ stat_length (Union[tuple, list, int], optional): Used in \'maximum\', \'mean\',
2647
+ \'median\', and \'minimum\'. Number of values at edge of each axis used
2648
+ to calculate the statistic value. ``((before_1, after_1), ... (before_N, after_N))``
2649
+ creates unique statistic lengths for each axis. ``((before, after),)``
2650
+ yields same before and after statistic lengths for each axis. ``(stat_length,)``
2651
+ or int is a shortcut for ``before = after = statistic length`` for all
2652
+ axes. Default: ``None``, to use the entire axis.
2653
+ constant_values (Union[tuple, list, int], optional):
2654
+ Used in ``constant mode``. The values to set the padded values for each
2655
+ axis. ``((before_1, after_1), ... (before_N, after_N))`` creates unique pad
2656
+ constants for each axis. ``((before, after),)`` yields same before and
2657
+ after constants for each axis. ``(constant,)`` or ``constant`` is
2658
+ a shortcut for ``before = after = constant`` for all axes. Default: ``0`` .
2659
+ end_values (Union[tuple, list, int], optional): Used in 'linear_ramp'. The values
2660
+ used for the ending value of the linear_ramp and that will form the edge of
2661
+ the padded `arr`. ``((before_1, after_1), ... (before_N, after_N))``
2662
+ unique end values for each axis. ``((before, after),)`` yields same before
2663
+ and after end values for each axis. ``(constant,)`` or ``constant``
2664
+ is a shortcut for ``before = after = constant`` for all axes. Default: ``0`` .
2665
+ reflect_type(string, optional) can choose between \'even\' and \'odd\'. Used in
2666
+ \'reflect\', and \'symmetric\'. The \'even\' style is the default with an
2667
+ unaltered reflection around the edge value. For the \'odd\' style, the extended
2668
+ part of the `arr` is created by subtracting the reflected values from two times
2669
+ the edge value.
2670
+ kwargs (anytype, optional): Any keyword arguments that will be used only in <function>
2671
+ mode.
2672
+
2673
+ Returns:
2674
+ Padded tensor of rank equal to `arr` with shape increased according to `pad_width`.
2675
+
2676
+ Raises:
2677
+ TypeError: If `arr`, `pad_width`, `stat_length`, `constant_values` or `end_values`
2678
+ have types not specified above.
2679
+ ValueError: If `mode` cannot be recognized, or if `pad_width`, `stat_length`,
2680
+ `constant_values`, `end_values` cannot broadcast to ``(arr.ndim, 2)``,
2681
+ or if keyword arguments got unexpected inputs.
2682
+ NotImplementedError: If mode is function or \'median\'.
2683
+
2684
+ Supported Platforms:
2685
+ ``Ascend`` ``GPU`` ``CPU``
2686
+
2687
+ Examples:
2688
+ >>> import mindspore.numpy as np
2689
+ >>> tensor = np.array([1., 2., 3., 4., 5.])
2690
+ >>> print(np.pad(tensor, (3, 4)))
2691
+ [0. 0. 0. 1. 2. 3. 4. 5. 0. 0. 0. 0.]
2692
+ >>> print(np.pad(tensor, (3, 4), mode="wrap"))
2693
+ [3. 4. 5. 1. 2. 3. 4. 5. 1. 2. 3. 4.]
2694
+ >>> print(np.pad(tensor, (3, 4), mode="linear_ramp", end_values=(10, 10)))
2695
+ [10. 7. 4. 1. 2. 3. 4. 5. 6.25 7.5 8.75 10. ]
2696
+ """
2697
+ arr = _to_tensor(arr)
2698
+ if arr.ndim == 0:
2699
+ return arr
2700
+ pad_width = _convert_pad_to_nd(pad_width, arr.ndim)
2701
+ stat_func = {"maximum": _reduce_max_keepdims,
2702
+ "minimum": _reduce_min_keepdims,
2703
+ "mean": _reduce_mean_keepdims,
2704
+ "median": "not implemented"}
2705
+
2706
+ if mode not in ("constant", "maximum", "minimum", "mean", "median", "edge",
2707
+ "wrap", "linear_ramp", "symmetric", "reflect", "empty") and \
2708
+ not _callable(arr, mode):
2709
+ _raise_value_error("Input mode not supported.")
2710
+
2711
+ if mode == "constant":
2712
+ constant_values = _convert_pad_to_nd(constant_values, arr.ndim)
2713
+ return _pad_constant(arr, pad_width, constant_values)
2714
+ if mode in ("maximum", "minimum", "mean", "median"):
2715
+ # support median mode once P.Sort/P.Median is supported on GPU/CPU
2716
+ if mode == "median":
2717
+ _raise_unimplemented_error("median mode is not supported yet")
2718
+ return _pad_statistic(arr, pad_width, stat_length, stat_func[mode])
2719
+ if mode == "edge":
2720
+ return _pad_edge(arr, pad_width)
2721
+ if mode == "wrap":
2722
+ return _pad_wrap(arr, pad_width)
2723
+ if mode == "linear_ramp":
2724
+ return _pad_linear(arr, pad_width, end_values)
2725
+ if mode == "symmetric":
2726
+ return _pad_symmetric(arr, pad_width, reflect_type)
2727
+ if mode == "reflect":
2728
+ return _pad_reflect(arr, pad_width, reflect_type)
2729
+ if mode == 'empty':
2730
+ return _pad_empty(arr, pad_width)
2731
+ return _pad_func(arr, pad_width, mode, **kwargs)