mindspore 2.4.0__cp310-cp310-macosx_11_0_arm64.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,4475 @@
1
+ # This is the Python adaptation and derivative work of Myia (https://github.com/mila-iqia/myia/).
2
+ #
3
+ # Copyright 2020-2024 Huawei Technologies Co., Ltd
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ # ============================================================================
17
+ """standard_method"""
18
+
19
+ from __future__ import absolute_import
20
+ from mindspore import Tensor, CSRTensor, COOTensor
21
+ from mindspore import dtype as mstype
22
+ from mindspore._c_expression import Tensor as Tensor_
23
+ from mindspore.common import mutable
24
+ import mindspore.common._monad as monad
25
+ from mindspore.common.sparse_tensor import RowTensorInner
26
+ from mindspore.ops.composite.base import _append, _insert, _pop, _list_clear, _reverse, \
27
+ _extend, _dict_setitem, _dict_clear, _haskey, _update, _fromkeys
28
+ from mindspore.ops.operations._sequence_ops import TensorToTuple
29
+ from mindspore.ops.auto_generate import trace_v2_op, inplace_addmm_op
30
+
31
+ from ... import _checkparam as validator
32
+ from ..._checkparam import check_is_number, check_reshape_shp, check_axis_in_range, \
33
+ check_axis_valid, check_and_canonicalize_axes
34
+ from ...ops import functional as F
35
+ from ...ops import operations as P
36
+ from ...ops import composite
37
+ from ...ops.operations import array_ops
38
+ from ...ops.composite import MultitypeFuncGraph, env_get, hyper_add, \
39
+ zeros_like, ones_like, repeat_elements, multitype_ops
40
+ from ...ops.composite.multitype_ops import _constexpr_utils as const_utils
41
+ from ...ops.composite.multitype_ops import _compile_utils as compile_utils
42
+ from ...ops.operations.math_ops import Median
43
+ from ...ops.operations._inner_ops import Format
44
+ from ...ops.operations import _csr_ops
45
+ from ...ops.operations import _map_tensor_ops
46
+ from ...ops.operations._sequence_ops import TensorToScalar
47
+ from ...ops.primitive import constexpr, _primexpr
48
+ from ...common import dtype as mstype
49
+ from ...ops.operations._sequence_ops import ListAppend, ListInsert, SequenceMax, SequenceMin, \
50
+ SequenceIndex
51
+
52
+ __all__ = ['MultitypeFuncGraph', 'env_get',
53
+ 'hyper_add', 'zeros_like', 'ones_like']
54
+
55
+ shape_ = P.Shape()
56
+ dtype_ = P.DType()
57
+ abs_ = P.Abs()
58
+ ndim_ = P.Rank()
59
+ cumsum_ = P.CumSum()
60
+ size_op_ = P.Size()
61
+ _format = Format()
62
+ _reduce_sum_default = P.ReduceSum()
63
+ _reduce_sum_keepdims = P.ReduceSum(True)
64
+ _csr_mm = _csr_ops.CSRMM()
65
+
66
+ itemsize_map = {mstype.bool_: 1, mstype.int8: 1, mstype.uint8: 1,
67
+ mstype.float16: 2, mstype.int16: 2, mstype.uint16: 2,
68
+ mstype.float32: 4, mstype.int32: 4, mstype.uint32: 4,
69
+ mstype.float64: 8, mstype.int64: 8, mstype.uint64: 8}
70
+
71
+ nan_tensor = Tensor(float('nan'), dtype=mstype.float32)
72
+
73
+ _map = composite.HyperMap()
74
+
75
+
76
+ def hypermap_dynamic_tuple(func, *inputs):
77
+ """Make hypermap for dynamic shape tuple."""
78
+ iter_len = len(inputs[0])
79
+ i = 0
80
+ ret = F.make_tuple()
81
+ while i < iter_len:
82
+ cur_input = F.make_tuple()
83
+ for m in inputs:
84
+ cur_input = cur_input + F.make_tuple(m[i])
85
+ new_out = _map(func, *cur_input)
86
+ ret = ret + F.make_tuple(new_out)
87
+ i = i + 1
88
+ return ret
89
+
90
+
91
+ def hypermap_dynamic_list(func, *inputs):
92
+ """Make hypermap for dynamic shape list."""
93
+ iter_len = len(inputs[0])
94
+ i = 0
95
+ ret = F.make_list()
96
+ while i < iter_len:
97
+ cur_input = F.make_tuple()
98
+ for m in inputs:
99
+ cur_input = cur_input + F.make_tuple(m[i])
100
+ new_out = _map(func, *cur_input)
101
+ ret = ret + F.make_list(new_out)
102
+ i = i + 1
103
+ return ret
104
+
105
+
106
+ def mean(x, axis=None, keep_dims=False):
107
+ """
108
+ Reduces a dimension of a tensor by averaging all elements in the dimension.
109
+
110
+ Args:
111
+ axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction,
112
+ when axis is None or empty tuple, reduce all dimensions. Default: ().
113
+ keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
114
+
115
+ Returns:
116
+ Tensor, has the same data type as input tensor.
117
+
118
+ Supported Platforms:
119
+ ``Ascend`` ``GPU`` ``CPU``
120
+
121
+ Examples:
122
+ >>> import numpy as np
123
+ >>> from mindspore import Tensor
124
+ >>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
125
+ >>> output = input_x.mean()
126
+ >>> print(output)
127
+ 2.0
128
+ """
129
+ return F.mean(x, axis, keep_dims)
130
+
131
+
132
+ def ndimension(x):
133
+ """Return the number of tensor dimensions."""
134
+ return len(x.shape)
135
+
136
+
137
+ def prod(input, axis=None, keep_dims=False, dtype=None):
138
+ """
139
+ Reduces a dimension of a tensor by product all elements in the dimension.
140
+
141
+ Args:
142
+ input (Tensor): Input Tensor.
143
+ axis (Union[None, int, tuple(int), list(int)]): Dimensions of reduction,
144
+ when axis is None or empty tuple, reduce all dimensions. Default: ``None``.
145
+ keep_dims (bool): Whether to keep the reduced dimensions. Default: False.
146
+ dtype (:class:`mindspore.dtype`): The desired data type of returned Tensor. Default: ``None`` .
147
+
148
+ Returns:
149
+ Tensor, has the same data type as input tensor.
150
+
151
+ Supported Platforms:
152
+ ``Ascend`` ``GPU`` ``CPU``
153
+
154
+ Examples:
155
+ >>> import numpy as np
156
+ >>> from mindspore import Tensor
157
+ >>> input_x = Tensor(np.array([1, 2, 3], dtype=np.float32))
158
+ >>> output = input_x.prod()
159
+ >>> print(output)
160
+ 6.0
161
+ """
162
+ return F.prod(input, axis, keep_dims, dtype)
163
+
164
+
165
+ def addcdiv(input, tensor1, tensor2, value=1):
166
+ """
167
+ Performs the element-wise division of tensor tensor1 by tensor tensor2,
168
+ multiply the result by the scalar value and add it to input_data.
169
+
170
+ Args:
171
+ input (Tensor): The tensor to be added.
172
+ tensor1 (Tensor): The numerator tensor.
173
+ tensor1 (Tensor): The denominator tensor.
174
+ value (Union[Tensor, Number]): The multiplier for tensor1/tensor2. Default: 1.
175
+
176
+ Returns:
177
+ Tensor, has the same shape and dtype as tensor1 / tensor2.
178
+ """
179
+ return F.addcdiv(input, tensor1, tensor2, value)
180
+
181
+
182
+ def addcmul(input, tensor1, tensor2, value=1):
183
+ """
184
+ Performs the element-wise product of tensor tensor1 and tensor tensor2,
185
+ multiply the result by the scalar value and add it to input_data.
186
+
187
+ Args:
188
+ input (Tensor): The tensor to be added.
189
+ tensor1 (Tensor): The tensor to be multiplied.
190
+ tensor2 (Tensor): The tensor to be multiplied.
191
+ value (Union[Tensor, Number]): The multiplier for tensor1*tensor2. Default: 1.
192
+
193
+ Returns:
194
+ Tensor, has the same shape and dtype as tensor1 * tensor2.
195
+ """
196
+ return F.addcmul(input, tensor1, tensor2, value)
197
+
198
+
199
+ def all_(x, axis=(), keep_dims=False):
200
+ """
201
+ Check all array elements along a given axis evaluate to True.
202
+
203
+ Args:
204
+ x (Tensor): A Tensor to be reduced.
205
+ axis (Union[None, int, tuple(int)): Dimensions of reduction.
206
+ keep_dims (bool): Whether to keep the reduced dimensions.
207
+
208
+ Returns:
209
+ Tensor, has the same data type as x.
210
+ """
211
+ return F.all(x, axis, keep_dims)
212
+
213
+
214
+ def angle(x):
215
+ r"""
216
+ For details, please refer to :func:`mindspore.ops.angle`.
217
+ """
218
+ return F.angle(x)
219
+
220
+
221
+ def any_(x, axis=(), keep_dims=False):
222
+ """
223
+ Check any array element along a given axis evaluate to True.
224
+
225
+ Args:
226
+ x (Tensor): A Tensor to be reduced.
227
+ axis (Union[None, int, tuple(int)): Dimensions of reduction.
228
+ keep_dims (bool): Whether to keep the reduced dimensions.
229
+
230
+ Returns:
231
+ Tensor, has the same data type as x.
232
+ """
233
+ if axis is None:
234
+ axis = ()
235
+ reduce_any = P.ReduceAny(keep_dims)
236
+ return reduce_any(x, axis)
237
+
238
+
239
+ def atan2(input, other):
240
+ r"""
241
+ Computes the first input tensor multiplied by the logarithm of second input tensor element-wise.
242
+ Refer to :func:`mindspore.ops.atan2` for more details.
243
+ """
244
+ return F.atan2(input, other)
245
+
246
+
247
+ def bincount(x, weights=None, minlength=0):
248
+ r"""
249
+ For details, please refer to :func:`mindspore.ops.bincount`.
250
+ """
251
+ return F.bincount(x, weights, minlength)
252
+
253
+
254
+ def H(x):
255
+ """Returns a view of a matrix (2-D tensor) conjugated and transposed."""
256
+ output = x.swapaxes(0, 1)
257
+ if x.dtype in (mstype.complex64, mstype.complex128):
258
+ return output.conj()
259
+ return output
260
+
261
+
262
+ def histc(x, bins=100, min=0., max=0.):
263
+ """
264
+ For details, please refer to :func:`mindspore.ops.histc`.
265
+ """
266
+ return F.histc(x, bins, min, max)
267
+
268
+
269
+ def geqrf(x):
270
+ """
271
+ For details, please refer to :func:`mindspore.ops.geqrf`.
272
+ """
273
+ return F.geqrf(x)
274
+
275
+
276
+ def size_(x):
277
+ """
278
+ Return the number of elements in tensor `x`.
279
+
280
+ Note:
281
+ To strictly follow Numpy's behaviour, return 1 for tensor scalar.
282
+
283
+ Args:
284
+ x (Tensor): Input tensor.
285
+
286
+ Returns:
287
+ size(int).
288
+ """
289
+ return size_op_(x)
290
+
291
+
292
+ def itemsize_(x):
293
+ """
294
+ Return length of one tensor element in bytes.
295
+
296
+ Args:
297
+ x (Tensor): Input tensor.
298
+
299
+ Returns:
300
+ itemsize(int).
301
+ """
302
+ return get_itemsize(x.dtype)
303
+
304
+
305
+ def nbytes_(x):
306
+ """
307
+ Return total number of bytes taken by the tensor.
308
+
309
+ Args:
310
+ x (Tensor): Input tensor.
311
+
312
+ Returns:
313
+ nbytes(int).
314
+ """
315
+ return itemsize_(x) * F.shape_mul(shape_(x))
316
+
317
+
318
+ def strides_(x):
319
+ """
320
+ Return the tuple of bytes to step in each dimension when traversing a tensor.
321
+
322
+ Args:
323
+ x (Tensor): Input tensor.
324
+
325
+ Returns:
326
+ strides (tuple[int]).
327
+ """
328
+ strides = ()
329
+ ndim = P.Rank()(x)
330
+ tensor_shape = shape_(x)
331
+ for i in F.make_range(0, ndim):
332
+ stride = itemsize_(x)
333
+ for j in F.make_range(i + 1, ndim):
334
+ stride *= tensor_shape[j]
335
+ strides += (stride,)
336
+ return strides
337
+
338
+
339
+ def slogdet(x):
340
+ r"""
341
+ For details, please refer to :func:`mindspore.ops.slogdet`.
342
+ """
343
+ return F.slogdet(x)
344
+
345
+
346
+ def cauchy(x, median=0.0, sigma=1.0):
347
+ r"""
348
+ Fills the tensor with numbers drawn from the Cauchy distribution. It is
349
+ defined as follows:
350
+
351
+ .. math::
352
+ f(x)= \frac{1}{\pi} \frac{\sigma}{(x-median)^2 +\sigma^2}
353
+
354
+ Args:
355
+ x (Tensor): Input tensor.
356
+ median (float, optional): the location parameter, specifying the location
357
+ of the peak of the distribution. Default: 0.0.
358
+ sigma (float, optional): the scale parameter which specifies the half-width
359
+ at half-maximum. Default: 1.0.
360
+
361
+ Returns:
362
+ Tensor. A Tensor with the same type and shape of input.
363
+ """
364
+ out = P.Cauchy(list(x.shape), median, sigma)()
365
+ return F.cast(out, x.dtype)
366
+
367
+
368
+ def log_normal(x, mean=1.0, std=2.0):
369
+ r"""
370
+ Fills the elements of the input tensor with log normal values initialized by
371
+ given mean and std:
372
+
373
+ .. math::
374
+ \text{f}(x;1.0,2.0)=\frac{1}{x\delta \sqrt[]{2\pi} }e^{-\frac{(\ln x-\mu )^2}{2\delta ^2} }
375
+
376
+ where \mu, \delta is mean and standard deviation of log normal distribution respectively.
377
+
378
+ Args:
379
+ x (Tensor): Input tensor.
380
+ mean (float, optional): the mean of normal distribution. With float data type.
381
+ Default: 1.0.
382
+ std (float, optional): the std of normal distribution. With float data type.
383
+ Default: 2.0.
384
+
385
+ Returns:
386
+ Tensor. A Tensor with the same type and shape of input.
387
+ """
388
+ log_normal = P.LogNormalReverse(mean, std)
389
+ return log_normal(x)
390
+
391
+
392
+ def chunk(x, chunks, axis=0):
393
+ r"""
394
+ For details, please refer to :func:`mindspore.ops.chunk`.
395
+ """
396
+ return F.chunk(x, chunks, axis)
397
+
398
+
399
+ def tril(x, diagonal=0):
400
+ r"""
401
+ For details, please refer to :func:`mindspore.ops.tril`.
402
+ """
403
+ return F.tril(x, diagonal)
404
+
405
+
406
+ def hasattr(x, attr): # pylint: disable=redefined-builtin
407
+ """
408
+ Return whether an object has the attribute.
409
+
410
+ Args:
411
+ x (object): Input object.
412
+ attr (string): The name of attribute
413
+
414
+ Returns:
415
+ Boolean value, indicates whether the object x has attribute attr.
416
+ """
417
+ out = getattr(x, attr, mstype._null)
418
+ return not isinstance(out, mstype._NullType)
419
+
420
+
421
+ def astype(x, dtype, copy=True): # pylint: disable=redefined-outer-name
422
+ """
423
+ Return a copy of the tensor, casted to a specified type.
424
+
425
+ Args:
426
+ dtype (Union[:class:`mindspore.dtype`, str]): Designated tensor dtype, can be in format
427
+ of :class:`mindspore.dtype.float32` or `float32`.
428
+ Default: :class:`mindspore.dtype.float32`.
429
+ copy (bool, optional): By default, astype always returns a newly allocated
430
+ tensor. If this is set to false, the input tensor is returned instead
431
+ of a copy if possible. Default: True.
432
+
433
+ Returns:
434
+ Tensor, with the designated dtype.
435
+
436
+ Raises:
437
+ TypeError: If `dtype` has types not specified above, or values cannot be understood.
438
+
439
+ Supported Platforms:
440
+ ``Ascend`` ``GPU`` ``CPU``
441
+
442
+ Examples:
443
+ >>> import numpy as np
444
+ >>> from mindspore import Tensor
445
+ >>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
446
+ >>> x = x.astype("int32")
447
+ >>> print(x.dtype)
448
+ Int32
449
+ """
450
+ dtype = check_astype_dtype_const(dtype)
451
+ if not copy and dtype == x.dtype:
452
+ return x
453
+ return F.cast(x, dtype)
454
+
455
+
456
+ def minimum(x, y):
457
+ r"""
458
+ Computes the minimum of input tensors element-wise.
459
+
460
+ Refer to :func:`mindspore.ops.minimum` for more detail.
461
+ """
462
+ return F.minimum(x, y)
463
+
464
+
465
+ def multinomial(input, num_samples, replacement=True, seed=None):
466
+ r"""
467
+ Returns a tensor sampled from the multinomial probability distribution located in the corresponding
468
+ row of the input tensor.
469
+
470
+ Refer to :func:`mindspore.ops.multinomial` for more detail.
471
+ """
472
+ return F.multinomial(input, num_samples, replacement, seed)
473
+
474
+
475
+ def tile(x, reps):
476
+ r"""
477
+ Replicates an input tensor with given reps times.
478
+
479
+ Creates a new tensor by replicating `input_x` `reps` times. The i'th dimension of
480
+ output tensor has `input_x.shape[i] * reps[i]` elements, and the values of `input_x`
481
+ are replicated `reps[i]` times along the i'th dimension.
482
+
483
+ Note:
484
+ The length of `reps` must be greater or equal to the length of dimension in `input_x`.
485
+
486
+ Args:
487
+ reps (tuple[int]): The parameter that specifies the number of replications,
488
+ the parameter type is tuple, and the data type is int, i.e., :math:`(y_1, y_2, ..., y_S)`.
489
+ The length of `reps` cannot be smaller than the length of the shape of `input_x`.
490
+ Only constant value is allowed.
491
+
492
+ Returns:
493
+ Tensor, has the same data type as the `input_x`. Suppose the length of `reps` is `d`,
494
+ the dimension of `input_x` is `input_x.dim`, and the shape of `input_x` is :math:`(x_1, x_2, ..., x_S)`.
495
+
496
+ - If `input_x.dim = d`, then the shape of their corresponding positions can be multiplied, and
497
+ the shape of Outputs is :math:`(x_1*y_1, x_2*y_2, ..., x_S*y_R)`.
498
+ - If `input_x.dim < d`, fill in multiple 1 in the length of the shape of `input_x` until their
499
+ lengths are consistent. Such as set the shape of `input_x` as :math:`(1, ..., x_1, x_2, ..., x_S)`,
500
+ then the shape of their corresponding positions can be multiplied, and the shape of Outputs is
501
+ :math:`(1*y_1, ..., x_S*y_R)`.
502
+
503
+ Raises:
504
+ TypeError: If `reps` is not a tuple or its elements are not all int.
505
+ ValueError: If the elements of `reps` are not all greater than 0.
506
+ ValueError: If the length of `reps` are smaller than the length of dimension in `input_x`.
507
+
508
+ Supported Platforms:
509
+ ``Ascend`` ``GPU`` ``CPU``
510
+
511
+ Examples:
512
+ >>> import mindspore as ms
513
+ >>> from mindspore import Tensor
514
+ >>> input_x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.float32)
515
+ >>> reps = (2, 3)
516
+ >>> output = input_x.tile(reps)
517
+ >>> print(output)
518
+ [[1. 2. 1. 2. 1. 2.]
519
+ [3. 4. 3. 4. 3. 4.]
520
+ [1. 2. 1. 2. 1. 2.]
521
+ [3. 4. 3. 4. 3. 4.]]
522
+ >>> reps = (2, 3, 2)
523
+ >>> output = input_x.tile(reps)
524
+ >>> print(output)
525
+ [[[1. 2. 1. 2.]
526
+ [3. 4. 3. 4.]
527
+ [1. 2. 1. 2.]
528
+ [3. 4. 3. 4.]
529
+ [1. 2. 1. 2.]
530
+ [3. 4. 3. 4.]]
531
+ [[1. 2. 1. 2.]
532
+ [3. 4. 3. 4.]
533
+ [1. 2. 1. 2.]
534
+ [3. 4. 3. 4.]
535
+ [1. 2. 1. 2.]
536
+ [3. 4. 3. 4.]]]
537
+ """
538
+ return F.tile(x, reps)
539
+
540
+
541
+ def short(x):
542
+ """
543
+ Return a copy of the tensor, cast to int16 type, equivalent to self.astype(ms.int16).
544
+ """
545
+ return F.cast(x, mstype.int16)
546
+
547
+
548
+ def transpose(x, *axis):
549
+ r"""
550
+ Return a view of the tensor with axes transposed.
551
+
552
+ For a 1-D tensor this has no effect, as a transposed vector is simply the
553
+ same vector. For a 2-D tensor, this is a standard matrix transpose. For a
554
+ n-D tensor, if axes are given, their order indicates how the axes are permuted.
555
+ If axes are not provided and tensor.shape = (i[0], i[1],...i[n-2], i[n-1]),
556
+ then tensor.transpose().shape = (i[n-1], i[n-2], ... i[1], i[0]).
557
+
558
+ Args:
559
+ axes(Union[None, tuple(int), list(int), int], optional): If axes is None or
560
+ blank, tensor.transpose() will reverse the order of the axes. If axes is tuple(int)
561
+ or list(int), tensor.transpose() will transpose the tensor to the new axes order.
562
+ If axes is int, this form is simply intended as a convenience alternative to the
563
+ tuple/list form.
564
+
565
+ Returns:
566
+ Tensor, has the same dimension as input tensor, with axes suitably permuted.
567
+
568
+ Raises:
569
+ TypeError: If input arguments have types not specified above.
570
+ ValueError: If the number of `axes` is not euqal to a.ndim.
571
+
572
+ Supported Platforms:
573
+ ``Ascend`` ``GPU`` ``CPU``
574
+
575
+ Examples:
576
+ >>> import numpy as np
577
+ >>> from mindspore import Tensor
578
+ >>> x = Tensor(np.ones((1,2,3), dtype=np.float32))
579
+ >>> x = x.transpose()
580
+ >>> print(x.shape)
581
+ (3, 2, 1)
582
+ """
583
+ ndim = F.rank(x)
584
+ perm = validator.check_transpose_axis(axis, ndim)
585
+ return F.transpose(x, perm)
586
+
587
+
588
+ def T(x):
589
+ """
590
+ Return the transposed tensor.
591
+ """
592
+ if x.ndim <= 1:
593
+ return x
594
+ return transpose(x)
595
+
596
+
597
+ # `tensor.T` is used as a property in graph mode
598
+ T_ = T
599
+
600
+
601
+ def reshape(x, *shape):
602
+ """
603
+ Give a new shape to a tensor without changing its data.
604
+
605
+ Args:
606
+ shape(Union[int, tuple(int), list(int)]): The new shape should be compatible
607
+ with the original shape. If an integer, then the result will be a 1-D
608
+ array of that length. One shape dimension can be -1. In this case, the
609
+ value is inferred from the length of the array and remaining dimensions.
610
+
611
+ Returns:
612
+ Tensor, with new specified shape.
613
+
614
+ Raises:
615
+ TypeError: If new_shape is not integer, list or tuple, or `x` is not tensor.
616
+ ValueError: If new_shape is not compatible with the original shape.
617
+
618
+ Supported Platforms:
619
+ ``Ascend`` ``GPU`` ``CPU``
620
+
621
+ Examples:
622
+ >>> from mindspore import Tensor
623
+ >>> from mindspore import dtype as mstype
624
+ >>> x = Tensor([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]], dtype=mstype.float32)
625
+ >>> output = x.reshape((3, 2))
626
+ >>> print(output)
627
+ [[-0.1 0.3]
628
+ [ 3.6 0.4]
629
+ [ 0.5 -3.2]]
630
+ """
631
+ new_shape = check_reshape_shp(shape)
632
+ return F.reshape(x, new_shape)
633
+
634
+
635
+ def reshape_as(x, other):
636
+ """
637
+ Rearranges the input Tensor based on the `other` shape.
638
+ """
639
+ return F.reshape(x, other.shape)
640
+
641
+
642
+ def reverse(x, axis):
643
+ """
644
+ Reverses specific dimensions of a tensor.
645
+
646
+ .. warning::
647
+ The value range of "axis" is [-dims, dims - 1]. "dims" is the dimension length of "input_x".
648
+
649
+ Args:
650
+ - **x** (Tensor) - The target tensor. The data type is Number except float64.
651
+ The shape is :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
652
+ - **axis** (Union[tuple(int), list(int)]): The indices of the dimensions to reverse.
653
+
654
+ Outputs:
655
+ Tensor, has the same shape and type as `x`.
656
+
657
+ Raises:
658
+ TypeError: If `axis` is neither list nor tuple.
659
+ TypeError: If element of `axis` is not an int.
660
+
661
+ Supported Platforms:
662
+ ``Ascend`` ``GPU`` ``CPU``
663
+
664
+ Examples:
665
+ >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32)
666
+ >>> output = ops.reverse(input_x, axis=[1])
667
+ >>> print(output)
668
+ [[4 3 2 1]
669
+ [8 7 6 5]]
670
+ >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32)
671
+ >>> output = ops.reverse(input_x, axis=[1, 0])
672
+ >>> print(output)
673
+ [[8 7 6 5]
674
+ [4 3 2 1]]
675
+ """
676
+ return F.reverse(x, axis)
677
+
678
+
679
+ def reverse_sequence(x, seq_lengths, seq_dim, batch_dim=0):
680
+ """
681
+ Reverses variable length slices.
682
+
683
+ Args:
684
+ x (Tensor): The input to reverse, supporting all number types including bool.
685
+ seq_lengths (Tensor): Must be a 1-D vector with int32 or int64 types.
686
+ seq_dim (int): The dimension where reversal is performed. Required.
687
+ batch_dim (int): The input is sliced in this dimension. Default: 0.
688
+
689
+ Returns:
690
+ Reversed tensor with the same shape and data type as input.
691
+
692
+ Raises:
693
+ TypeError: If `seq_dim` or `batch_dim` is not an int.
694
+ ValueError: If value of `batch_dim` is equal to or greater than length of shape of input.
695
+
696
+ Supported Platforms:
697
+ ``Ascend`` ``GPU`` ``CPU``
698
+
699
+ Examples:
700
+ >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
701
+ >>> seq_lengths = Tensor(np.array([1, 2, 3]))
702
+ >>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
703
+ >>> print(output)
704
+ [[1. 2. 3.]
705
+ [5. 4. 6.]
706
+ [9. 8. 7.]]
707
+ >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
708
+ >>> seq_lengths = Tensor(np.array([1, 2, 3]))
709
+ >>> output = x.reverse_sequence(seq_lengths, seq_dim=0, batch_dim=1)
710
+ >>> print(output)
711
+ [[1. 5. 9.]
712
+ [4. 2. 6.]
713
+ [7. 8. 3.]]
714
+ >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
715
+ >>> seq_lengths = Tensor(np.array([2, 2, 3]))
716
+ >>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
717
+ >>> print(output)
718
+ [[2. 1. 3.]
719
+ [5. 4. 6.]
720
+ [9. 8. 7.]]
721
+ >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
722
+ >>> seq_lengths = Tensor(np.array([3, 2, 3]))
723
+ >>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
724
+ >>> print(output)
725
+ [[3. 2. 1.]
726
+ [5. 4. 6.]
727
+ [9. 8. 7.]]
728
+ >>> x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.float32)
729
+ >>> seq_lengths = Tensor(np.array([4, 4]))
730
+ >>> output = x.reverse_sequence(seq_lengths, seq_dim=1)
731
+ >>> print(output)
732
+ [[4. 3. 2. 1.]
733
+ [8. 7. 6. 5.]]
734
+ """
735
+ return F.reverse_sequence(x, seq_lengths, seq_dim, batch_dim)
736
+
737
+
738
+ def ravel(x):
739
+ """
740
+ Return a contiguous flattened tensor.
741
+
742
+ Returns:
743
+ Tensor, a 1-D tensor, containing the same elements of the input.
744
+
745
+ Supported Platforms:
746
+ ``Ascend`` ``GPU`` ``CPU``
747
+
748
+ Examples:
749
+ >>> import numpy as np
750
+ >>> from mindspore import Tensor
751
+ >>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
752
+ >>> output = x.ravel()
753
+ >>> print(output.shape)
754
+ (24,)
755
+ """
756
+ return reshape(x, (-1,))
757
+
758
+
759
+ def flatten(x, order='C', *, start_dim=0, end_dim=-1):
760
+ r"""
761
+ Flatten a tensor along dimensions from `start_dim` to `start_dim`.
762
+
763
+ Args:
764
+ x (Tensor): Input tensor.
765
+ order (str, optional): Only 'C' and 'F' are supported. 'C' means to flatten in row-major (C-style) order.
766
+ 'F' means to flatten in column-major (Fortran-style) order. Default: 'C'.
767
+
768
+ Keyword Args:
769
+ start_dim (int, optional): The first dimension to flatten. Default: 0.
770
+ end_dim (int, optional): The last dimension to flatten. Default: -1.
771
+
772
+ Returns:
773
+ Tensor. If `x` is a 0-dimensional, a 1-dimensional Tensor will be returned.
774
+
775
+ Supported Platforms:
776
+ ``Ascend`` ``GPU`` ``CPU``
777
+
778
+ Raises:
779
+ TypeError: If `order` is not string type.
780
+ ValueError: If `order` is string type, but not 'C' or 'F'.
781
+ TypeError: If `start_dim` or `end_dim` is not int.
782
+ ValueError: If `start_dim` is greater than `end_dim` after canonicalized.
783
+ ValueError: If `start_dim` or `end_dim` is not in range of [-x.dim, x.dim-1].
784
+
785
+ Examples:
786
+ >>> import numpy as np
787
+ >>> from mindspore import Tensor
788
+ >>> x = Tensor(np.ones((2,3,4), dtype=np.float32))
789
+ >>> output = x.flatten()
790
+ >>> print(output.shape)
791
+ (24,)
792
+ """
793
+ return F.flatten(x, order, start_dim=start_dim, end_dim=end_dim)
794
+
795
+
796
+ def scatter(self, axis, index, src):
797
+ """
798
+ Update the value in `src` to tensor according to the specified index.
799
+ """
800
+ return F.scatter(self, axis, index, src)
801
+
802
+
803
+ def slice_scatter(input, src, axis=0, start=None, end=None, step=1):
804
+ r"""
805
+ Embeds the src into the input Tensor according to `axis`.
806
+ """
807
+ return F.slice_scatter(input, src, axis, start, end, step)
808
+
809
+
810
+ def select_scatter(input, src, axis, index):
811
+ r"""
812
+ On the specified dimension `axis` of `input` , `src` is scattered into `input` on the specified `index` of `input` .
813
+ """
814
+ return F.select_scatter(input, src, axis, index)
815
+
816
+
817
+ def swapaxes(input, axis0, axis1):
818
+ """
819
+ Interchange two axes of a tensor.
820
+ """
821
+ return F.swapaxes(input, axis0, axis1)
822
+
823
+
824
+ def swapdims(x, dim0, dim1):
825
+ """
826
+ Interchange two dims of a tensor.
827
+ """
828
+ return F.swapdims(x, dim0, dim1)
829
+
830
+
831
+ def squeeze(x, axis=None):
832
+ """
833
+ Remove single-dimensional entries from the shape of a tensor.
834
+
835
+ Args:
836
+ axis (Union[None, int, list(int), tuple(int)], optional): Default is None.
837
+
838
+ Returns:
839
+ Tensor, with all or a subset of the dimensions of length 1 removed.
840
+
841
+ Raises:
842
+ TypeError: If input arguments have types not specified above.
843
+ ValueError: If specified axis has shape entry :math:`> 1`.
844
+
845
+ Supported Platforms:
846
+ ``Ascend`` ``GPU`` ``CPU``
847
+
848
+ Examples:
849
+ >>> import numpy as np
850
+ >>> from mindspore import Tensor
851
+ >>> x = Tensor(np.ones((1,2,2,1), dtype=np.float32))
852
+ >>> x = x.squeeze()
853
+ >>> print(x.shape)
854
+ (2, 2)
855
+ """
856
+ return F.squeeze(x, axis)
857
+
858
+
859
+ def unbind(input, dim=0):
860
+ """For details, please refer to :func:`mindspore.ops.unbind`."""
861
+ return P.Unstack(axis=dim)(input)
862
+
863
+
864
+ def argmax(x, axis=None, keepdims=False):
865
+ """
866
+ Returns the indices of the maximum values of a tensor across a dimension.
867
+
868
+ Args:
869
+ axis (Union[int, None], optional): The dimension to reduce.
870
+ If `axis` is None, the indices of the maximum value within the
871
+ flattened input will be returned. Default: ``None``.
872
+ keepdims (bool, optional): Whether the output tensor retains the
873
+ specified dimension. Ignored if `axis` is None. Default: False.
874
+
875
+ Returns:
876
+ Tensor, indices of the maximum values across a dimension.
877
+
878
+ Raises:
879
+ ValueError: if `axis` is out of range.
880
+
881
+ Supported Platforms:
882
+ ``Ascend`` ``GPU`` ``CPU``
883
+
884
+ Examples:
885
+ >>> import numpy as np
886
+ >>> from mindspore import Tensor
887
+ >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
888
+ >>> print(a.argmax())
889
+ 5
890
+ """
891
+ return F.argmax(x, axis, keepdims)
892
+
893
+
894
+ def argmin(x, axis=None, keepdims=False):
895
+ """
896
+ Returns the indices of the minimum values along an axis.
897
+
898
+ Args:
899
+ a (Union[int, float, bool, list, tuple, Tensor]): Input array.
900
+ axis (int, optional): By default, the index is into
901
+ the flattened array, otherwise along the specified axis.
902
+ Defaults to None.
903
+ keepdims (boolean, optional): Whether the output tensor retains the specified
904
+ dimension. Ignored if `axis` is None. Default: False.
905
+
906
+ Returns:
907
+ Tensor, array of indices into the array. It has the same
908
+ shape as a.shape with the dimension along axis removed.
909
+
910
+ Raises:
911
+ ValueError: if axis is out of range.
912
+
913
+ Supported Platforms:
914
+ ``Ascend`` ``GPU`` ``CPU``
915
+
916
+ Examples:
917
+ >>> import numpy as np
918
+ >>> from mindspore import Tensor
919
+ >>> a = Tensor(np.arange(10, 16).reshape(2, 3).astype("float32"))
920
+ >>> print(a.argmin())
921
+ 0
922
+ """
923
+ # P.Argmin only supports float
924
+ x = x.astype(mstype.float32)
925
+ is_axis_none = False
926
+ if axis is None:
927
+ x = ravel(x)
928
+ axis = 0
929
+ is_axis_none = True
930
+ else:
931
+ axis = check_axis_in_range(axis, F.rank(x))
932
+ out = P.Argmin(axis)(x)
933
+ if keepdims and not is_axis_none:
934
+ out = expand_dims(out, axis)
935
+ return out
936
+
937
+
938
+ def argmax_with_value(x, axis=0, keep_dims=False):
939
+ """Calculates the maximum value with corresponding index, and returns indices and values."""
940
+ return F.max(x, axis, keep_dims)
941
+
942
+
943
+ def argmin_with_value(x, axis=0, keep_dims=False):
944
+ """Calculates the minimum value with corresponding index, and returns indices and values."""
945
+ return F.min(x, axis, keep_dims)
946
+
947
+
948
+ def median(input, global_median, axis=0, keep_dims=False):
949
+ r"""
950
+ Computes the median of input tensor.
951
+
952
+ .. warning::
953
+ When attr `global_median` is True, the second output Tensor value is meaningless.
954
+
955
+ """
956
+ check_axis_in_range(axis, input.ndim)
957
+ median_ = Median(global_median, axis, keep_dims)
958
+ return median_(input)
959
+
960
+
961
+ def msort(x):
962
+ """
963
+ For details, please refer to :func:`mindspore.ops.msort`.
964
+ """
965
+ return F.msort(x)
966
+
967
+
968
+ def mm(mat1, mat2):
969
+ """
970
+ For details, please refer to :func:`mindspore.ops.mm`.
971
+ """
972
+ return F.mm(mat1, mat2)
973
+
974
+
975
+ def mT(x):
976
+ """
977
+ Returns a view of this tensor with the last two dimensions transposed.
978
+ x.mT is equivalent to x.transpose(-2, -1).
979
+ """
980
+ return swapaxes(x, -2, -1)
981
+
982
+
983
+ def nan_to_num(x, nan=0.0, posinf=None, neginf=None):
984
+ """
985
+ For details, please refer to :func:`mindspore.ops.nan_to_num`.
986
+ """
987
+ return F.nan_to_num(x, nan, posinf, neginf)
988
+
989
+
990
+ def cumsum(x, axis=None, dtype=None):
991
+ """
992
+ Returns the cumulative sum of the elements along a given axis.
993
+
994
+ Note:
995
+ If ``x.dtype`` is :class:`int8`, :class:`int16` or :class:`bool`, the result
996
+ `dtype` will be elevated to :class:`int32`, :class:`int64` is not supported.
997
+
998
+ Args:
999
+ x (Tensor): Input tensor.
1000
+ axis (int, optional): Axis along which the cumulative sum is computed. The
1001
+ default (None) is to compute the cumsum over the flattened array.
1002
+ dtype (:class:`mindspore.dtype`, optional): If not specified, stay the same as original,
1003
+ tensor, unless it has an integer dtype with a precision less than :class:`float32`.
1004
+ In that case, :class:`float32` is used.
1005
+
1006
+ Returns:
1007
+ Tensor.
1008
+
1009
+ Supported Platforms:
1010
+ ``Ascend`` ``GPU`` ``CPU``
1011
+
1012
+ Examples:
1013
+ >>> import numpy as np
1014
+ >>> from mindspore import Tensor
1015
+ >>> a = Tensor(np.ones((3,3)).astype("float32"))
1016
+ >>> output = a.cumsum(axis=0)
1017
+ >>> print(output)
1018
+ [[1. 1. 1.]
1019
+ [2. 2. 2.]
1020
+ [3. 3. 3.]]
1021
+ """
1022
+ original_dtype = x.dtype
1023
+ # If original tensor is int, and has precision less then int32, convert
1024
+ # to int32
1025
+ if x.dtype in (mstype.bool_, mstype.int8, mstype.int16, mstype.uint8, mstype.int16):
1026
+ x = x.astype(mstype.int32)
1027
+ if axis is None:
1028
+ x = x.ravel()
1029
+ axis = 0
1030
+ check_axis_in_range(axis, x.ndim)
1031
+ if dtype is not None:
1032
+ dtype = check_astype_dtype_const(dtype)
1033
+ if original_dtype != dtype:
1034
+ return cumsum_(x, axis).astype(dtype, copy=False)
1035
+ return cumsum_(x, axis)
1036
+
1037
+
1038
+ def cummin(x, axis):
1039
+ """
1040
+ Returns the cumulative minimum of elements and the index.
1041
+ """
1042
+ return F.cummin(x, axis)
1043
+
1044
+
1045
+ def cummax(x, axis):
1046
+ """
1047
+ Returns the cumulative maximum of elements and the index.
1048
+ """
1049
+ return F.cummax(x, axis)
1050
+
1051
+
1052
+ def index_fill(x, axis, index, value):
1053
+ """
1054
+ Fills the elements under the axis dimension of the input Tensor with the input value
1055
+ by selecting the indices in the order given in index.
1056
+ """
1057
+ return F.index_fill(x, axis, index, value)
1058
+
1059
+
1060
+ def index_select(x, axis, index):
1061
+ """
1062
+ Returns a new tensor which indexes the `x` tensor along dimension `axis` using the entries in `index` .
1063
+ """
1064
+ return F.index_select(x, axis, index)
1065
+
1066
+
1067
+ def copy(x):
1068
+ """
1069
+ Returns a copy of the tensor.
1070
+
1071
+ Note:
1072
+ The current implementation does not support `order` argument.
1073
+
1074
+ Args:
1075
+ x (Tensor): Input tensor.
1076
+
1077
+ Returns:
1078
+ Copied tensor.
1079
+
1080
+ Supported Platforms:
1081
+ ``Ascend`` ``GPU`` ``CPU``
1082
+
1083
+ Examples:
1084
+ >>> import numpy as np
1085
+ >>> from mindspore import Tensor
1086
+ >>> a = Tensor(np.ones((3,3)).astype("float32"))
1087
+ >>> output = a.copy()
1088
+ >>> print(output)
1089
+ [[1. 1. 1.]
1090
+ [1. 1. 1.]
1091
+ [1. 1. 1.]]
1092
+ """
1093
+ if x.size == 0:
1094
+ return x
1095
+ origin_dtype = x.dtype
1096
+ if origin_dtype == mstype.bool_:
1097
+ return F.logical_not(F.logical_not(x))
1098
+ if origin_dtype != mstype.float64:
1099
+ x = x.astype(mstype.float32)
1100
+ x = x / 1.0
1101
+ x = x.astype(origin_dtype)
1102
+ return x
1103
+
1104
+
1105
+ def max(input, axis=None, keepdims=False, *, initial=None, # pylint: disable=redefined-builtin
1106
+ where=True, return_indices=False): # pylint: disable=redefined-outer-name
1107
+ """
1108
+ Returns the maximum of a tensor or maximum along an axis.
1109
+
1110
+ Args:
1111
+ x (Tensor): Input Tensor.
1112
+ axis (None or int or tuple of ints, optional): defaults to None. Axis or
1113
+ axes along which to operate. By default, flattened input is used. If
1114
+ this is a tuple of ints, the maximum is selected over multiple axes,
1115
+ instead of a single axis or all the axes as before.
1116
+ keepdims (bool, optional): defaults to False.
1117
+ If this is set to True, the axes which are reduced are left in the
1118
+ result as dimensions with size one. With this option, the result will
1119
+ broadcast correctly against the input array.
1120
+
1121
+ Keyword Args:
1122
+ initial (scalar, optional):
1123
+ The minimum value of an output element. Must be present to allow
1124
+ computation on empty slice.
1125
+ where (bool Tensor, optional): defaults to True.
1126
+ A boolean array which is broadcasted to match the dimensions of array,
1127
+ and selects elements to include in the reduction. If non-default value
1128
+ is passed, initial must also be provided.
1129
+ return_indices (bool, optional): Whether to return the index of the minimum value. Default: False.
1130
+ If `axis` is a list or tuple of ints, it must be False.
1131
+
1132
+ Returns:
1133
+ Tensor or scalar, maximum of input tensor. If `axis` is None, the result is a scalar
1134
+ value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
1135
+
1136
+ Raises:
1137
+ TypeError: if the input is not a tensor.
1138
+
1139
+ Supported Platforms:
1140
+ ``Ascend`` ``GPU`` ``CPU``
1141
+
1142
+ Examples:
1143
+ >>> import numpy as np
1144
+ >>> from mindspore import Tensor
1145
+ >>> import mindspore.numpy as np
1146
+ >>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
1147
+ >>> output = a.max()
1148
+ >>> print(output)
1149
+ 3.0
1150
+ """
1151
+ if isinstance(axis, (list, tuple)):
1152
+ return compile_utils.reduce_(input, P.ReduceMax(keepdims), cmp_fn=F.maximum,
1153
+ axis=axis, keepdims=keepdims, initial=initial, where=where)
1154
+ values, indices = F.max(input, axis, keepdims, initial=initial, where=where)
1155
+ if not return_indices:
1156
+ return values
1157
+ return values, indices
1158
+
1159
+
1160
+ def min(input, axis=None, keepdims=False, *, initial=None, # pylint: disable=redefined-builtin
1161
+ where=True, return_indices=False): # pylint: disable=redefined-outer-name
1162
+ """
1163
+ Returns the minimum of a tensor or minimum along an axis.
1164
+
1165
+ Args:
1166
+ a (Tensor): Input data.
1167
+ axis (None or int or tuple of ints, optional): defaults to None. Axis or
1168
+ axes along which to operate. By default, flattened input is used. If
1169
+ this is a tuple of ints, the minimum is selected over multiple axes,
1170
+ instead of a single axis or all the axes as before.
1171
+ keepdims (bool, optional): defaults to False.
1172
+ If this is set to True, the axes which are reduced are left in the
1173
+ result as dimensions with size one. With this option, the result will
1174
+ broadcast correctly against the input array.
1175
+
1176
+ Keyword Args:
1177
+ initial (scalar, optional):
1178
+ The maximum value of an output element. Must be present to allow
1179
+ computation on empty slice.
1180
+ where (bool Tensor, optional): defaults to True.
1181
+ A boolean array which is broadcasted to match the dimensions of array,
1182
+ and selects elements to include in the reduction. If non-default value
1183
+ is passed, initial must also be provided.
1184
+ return_indices (bool, optional): Whether to return the index of the minimum value. Default: False.
1185
+ If `axis` is a list or tuple of ints, it must be False.
1186
+
1187
+ Returns:
1188
+ Tensor or scalar, minimum of `a`. If axis is None, the result is a scalar
1189
+ value. If `axis` is given, the result is an array of dimension ``a.ndim - 1``.
1190
+
1191
+ Raises:
1192
+ TypeError: if the input is not a tensor.
1193
+
1194
+ Supported Platforms:
1195
+ ``Ascend`` ``GPU`` ``CPU``
1196
+
1197
+ Examples:
1198
+ >>> import numpy as np
1199
+ >>> from mindspore import Tensor
1200
+ >>> import mindspore.numpy as np
1201
+ >>> a = Tensor(np.arange(4).reshape((2,2)).astype('float32'))
1202
+ >>> output = a.min()
1203
+ >>> print(output)
1204
+ 0.0
1205
+ """
1206
+ if isinstance(axis, (list, tuple)):
1207
+ return compile_utils.reduce_(input, P.ReduceMin(keepdims), cmp_fn=F.minimum,
1208
+ axis=axis, keepdims=keepdims, initial=initial, where=where)
1209
+ values, indices = F.min(input, axis, keepdims, initial=initial, where=where)
1210
+ if not return_indices:
1211
+ return values
1212
+ return values, indices
1213
+
1214
+
1215
+ def pow(x, y): # pylint: disable=redefined-builtin
1216
+ """
1217
+ Calculate the power of Tensor.
1218
+ """
1219
+ return F.pow(x, y)
1220
+
1221
+
1222
+ def log(x):
1223
+ """
1224
+ Calculate the logarithm of Tensor.
1225
+ """
1226
+ return F.log(x)
1227
+
1228
+
1229
+ def log10(input):
1230
+ """
1231
+ Calculate the base-10 logarithm of Tensor.
1232
+ """
1233
+ return F.log10(input)
1234
+
1235
+
1236
+ def log2(input):
1237
+ """
1238
+ Calculate the base-2 logarithm of Tensor.
1239
+ """
1240
+ return F.log2(input)
1241
+
1242
+
1243
+ def logaddexp(input, other):
1244
+ """
1245
+ Computes the logarithm of the sum of exponentiations of the inputs.
1246
+ """
1247
+ return F.logaddexp(input, other)
1248
+
1249
+
1250
+ def logaddexp2(input, other):
1251
+ """
1252
+ Computes the logarithm of the sum of exponentiations in base of 2 of the inputs.
1253
+ """
1254
+ return F.logaddexp2(input, other)
1255
+
1256
+
1257
+ def logcumsumexp(input, axis):
1258
+ """
1259
+ Computes the logarithm of the sum of exponentiations of the inputs along specified dimension.
1260
+ """
1261
+ return F.logcumsumexp(input, axis)
1262
+
1263
+
1264
+ def logsumexp(input, axis, keepdims=False):
1265
+ """
1266
+ Reduces a dimension of a tensor by calculating exponential for all elements in the dimension,
1267
+ then calculate logarithm of the sum.
1268
+ """
1269
+ return F.logsumexp(input, axis, keepdims)
1270
+
1271
+
1272
+ def round_(x):
1273
+ """
1274
+ Returns half to even of a tensor element-wise.
1275
+ """
1276
+ return F.round(x)
1277
+
1278
+
1279
+ def roll(x, shifts, dims):
1280
+ """
1281
+ Rolls the elements of a tensor along an axis.
1282
+ """
1283
+ dims = dims if dims is not None else 0
1284
+ return F.Roll(shifts, dims)(x)
1285
+
1286
+
1287
+ def rot90(x, k, dims):
1288
+ """
1289
+ Rotate a n-D tensor by 90 degrees in the plane specified by dims axis.
1290
+ """
1291
+ return F.rot90(x, k, dims)
1292
+
1293
+
1294
+ def rad2deg(x):
1295
+ """
1296
+ Returns a new tensor with each of the elements of `x` converted from angles in radians to degrees.
1297
+ """
1298
+ return F.rad2deg(x)
1299
+
1300
+
1301
+ def deg2rad(x):
1302
+ """
1303
+ Calculates a new tensor with each of the elements of `x` converted from angles in degrees to radians.
1304
+ """
1305
+ return F.deg2rad(x)
1306
+
1307
+
1308
+ def dot(input, other):
1309
+ r"""
1310
+ For details, please refer to :func:`mindspore.ops.dot`.
1311
+ """
1312
+ return composite.dot(input, other)
1313
+
1314
+
1315
+ def copysign(x, other):
1316
+ """
1317
+ Create a new floating-point tensor with the magnitude of `x` and the sign of `other`, element-wise.
1318
+ """
1319
+ return F.copysign(x, other)
1320
+
1321
+
1322
+ def numel(input):
1323
+ """
1324
+ Returns a Scalar of type int that represents the total number of elements in the Tensor.
1325
+ """
1326
+ return F.numel(input)
1327
+
1328
+
1329
+ def permute(input, *axis):
1330
+ """
1331
+ Permutes the dimensions of the input tensor according to input permutation.
1332
+ """
1333
+ ndim = F.rank(input)
1334
+ perm = validator.check_transpose_axis(axis, ndim)
1335
+ return F.permute(input, perm)
1336
+
1337
+
1338
+ def positive(input):
1339
+ """
1340
+ Return self Tensor.
1341
+ """
1342
+ return F.positive(input)
1343
+
1344
+
1345
+ def remainder(input, divisor):
1346
+ """
1347
+ Returns element-wise remainder of division.
1348
+ """
1349
+ return F.remainder(input, divisor)
1350
+
1351
+
1352
+ def unique_consecutive(input, return_idx=False, return_counts=False, axis=None):
1353
+ """
1354
+ Returns the elements that are unique in each consecutive group of equivalent elements in the input tensor.
1355
+ """
1356
+ return F.unique_consecutive(input, return_idx, return_counts, axis)
1357
+
1358
+
1359
+ def unique_with_pad(x, pad_num):
1360
+ """
1361
+ Returns unique elements and relative indexes in 1-D tensor, filled with padding num.
1362
+ """
1363
+ return F.unique_with_pad(x, pad_num)
1364
+
1365
+
1366
+ def resize(x, *new_shape):
1367
+ """
1368
+ Changes shape and size of array in-place.
1369
+
1370
+ Note:
1371
+ Instead of changing the size of the input array and returns nothing as in numpy,
1372
+ this method returns a new Tensor with the input size.
1373
+ Numpy argument `refcheck` is not supported.
1374
+
1375
+ Args:
1376
+ new_shape (Union[ints, tuple of ints]): Shape of resized array.
1377
+
1378
+ Returns:
1379
+ Tensor.
1380
+
1381
+ Supported Platforms:
1382
+ ``Ascend`` ``GPU`` ``CPU``
1383
+
1384
+ Examples:
1385
+ >>> from mindspore import numpy as np
1386
+ >>> x = np.array([[0, 1], [2, 3]])
1387
+ >>> x = x.resize(2, 3)
1388
+ >>> print(x)
1389
+ [[0 1 2]
1390
+ [3 0 0]]
1391
+ """
1392
+ if not new_shape:
1393
+ return x
1394
+ if len(new_shape) == 1:
1395
+ if isinstance(new_shape[0], tuple):
1396
+ new_shape = new_shape[0]
1397
+ flattened = x.ravel()
1398
+ cur_size = F.shape_mul(x.shape)
1399
+ new_size = F.shape_mul(new_shape)
1400
+ diff_size = new_size - cur_size
1401
+ if diff_size > 0:
1402
+ pad_val = F.fill(x.dtype, (diff_size,), 0)
1403
+ res = P.Concat()((flattened, pad_val))
1404
+ else:
1405
+ res = flattened[:new_size]
1406
+ return res.reshape(new_shape)
1407
+
1408
+
1409
+ def det(input):
1410
+ """
1411
+ Computes the determinant of one or more square matrices.
1412
+ """
1413
+ return F.det(input)
1414
+
1415
+
1416
+ def diagonal(x, offset=0, axis1=0, axis2=1):
1417
+ """
1418
+ Returns specified diagonals.
1419
+
1420
+ Args:
1421
+ offset (int, optional): Offset of the diagonal from the main diagonal.
1422
+ Can be positive or negative. Defaults to main diagonal.
1423
+ axis1 (int, optional): Axis to be used as the first axis of the 2-D
1424
+ sub-arrays from which the diagonals should be taken. Defaults to
1425
+ first axis (0).
1426
+ axis2 (int, optional): Axis to be used as the second axis of the 2-D
1427
+ sub-arrays from which the diagonals should be taken. Defaults to
1428
+ second axis.
1429
+
1430
+ Returns:
1431
+ Tensor, if `a` is 2-D, then `a` 1-D array containing the diagonal.
1432
+
1433
+ Raises:
1434
+ ValueError: if the input tensor has less than two dimensions.
1435
+
1436
+ Supported Platforms:
1437
+ ``Ascend`` ``GPU`` ``CPU``
1438
+
1439
+ Examples:
1440
+ >>> import mindspore.numpy as np
1441
+ >>> a = np.arange(4).reshape(2,2)
1442
+ >>> print(a)
1443
+ [[0 1]
1444
+ [2 3]]
1445
+ >>> output = a.diagonal()
1446
+ >>> print(output)
1447
+ [0 3]
1448
+ """
1449
+ ndim = x.ndim
1450
+ if ndim < 2:
1451
+ const_utils.raise_value_error(
1452
+ 'diagonal requires an array of at least two dimensions')
1453
+ return F.diagonal(x, offset, axis1, axis2)
1454
+
1455
+
1456
+ def diagonal_scatter(input, src, offset, dim1=0, dim2=1):
1457
+ r"""
1458
+ Embed `src` into the diagonal of `input` according to the `dim1` and `dim2`.
1459
+ """
1460
+ return F.diagonal_scatter(input, src, offset, dim1, dim2)
1461
+
1462
+
1463
+ def digamma(input):
1464
+ """
1465
+ Computes the logarithmic derivative of the gamma function on input.
1466
+ """
1467
+ return F.digamma(input)
1468
+
1469
+
1470
+ def lgamma(input):
1471
+ """
1472
+ Computes the natural logarithm of the absolute value of the gamma function on input.
1473
+ """
1474
+ return F.lgamma(input)
1475
+
1476
+
1477
+ def i0(x):
1478
+ """
1479
+ For details, please refer to :func:`mindspore.ops.i0`.
1480
+ """
1481
+ return F.i0(x)
1482
+
1483
+
1484
+ def isclose(x1, x2, rtol=1e-05, atol=1e-08, equal_nan=False):
1485
+ """
1486
+ Returns a boolean tensor where two tensors are element-wise equal within a tolerance.
1487
+ """
1488
+ return F.isclose(x1, x2, rtol, atol, equal_nan)
1489
+
1490
+
1491
+ def isneginf(input):
1492
+ """
1493
+ Tests element-wise for negative infinity, returns result as bool array.
1494
+ """
1495
+ return F.isneginf(input)
1496
+
1497
+
1498
+ def isposinf(input):
1499
+ """
1500
+ Tests element-wise for positive infinity, returns result as bool array.
1501
+ """
1502
+ return F.isposinf(input)
1503
+
1504
+
1505
+ def isreal(input):
1506
+ """
1507
+ Tests element-wise for real number.
1508
+ """
1509
+ return F.isreal(input)
1510
+
1511
+
1512
+ def flip(x, dims):
1513
+ """
1514
+ For details, please refer to :func:`mindspore.ops.flip`.
1515
+ """
1516
+ return F.flip(x, dims)
1517
+
1518
+
1519
+ def fliplr(x):
1520
+ """
1521
+ For details, please refer to :func:`mindspore.ops.fliplr`.
1522
+ """
1523
+ return F.fliplr(x)
1524
+
1525
+
1526
+ def flipud(x):
1527
+ """
1528
+ For details, please refer to :func:`mindspore.ops.flipud`.
1529
+ """
1530
+ return F.flipud(x)
1531
+
1532
+
1533
+ def float_power(x, exponent):
1534
+ """
1535
+ For details, please refer to :func:`mindspore.ops.float_power`.
1536
+ """
1537
+ return F.float_power(x, exponent)
1538
+
1539
+
1540
+ def fmax(input, other):
1541
+ """
1542
+ For details, please refer to :func:`mindspore.ops.fmax`.
1543
+ """
1544
+ return F.fmax(input, other)
1545
+
1546
+
1547
+ def fmin(input, other):
1548
+ """
1549
+ For details, please refer to :func:`mindspore.ops.fmin`.
1550
+ """
1551
+ return F.fmin(input, other)
1552
+
1553
+
1554
+ def fmod(x, other):
1555
+ """
1556
+ For details, please refer to :func:`mindspore.ops.fmod`.
1557
+ """
1558
+ return F.fmod(x, other)
1559
+
1560
+
1561
+ def is_floating_point(x):
1562
+ """
1563
+ For details, please refer to :func:`mindspore.ops.is_floating_point`.
1564
+ """
1565
+ return F.is_floating_point(x)
1566
+
1567
+
1568
+ def is_signed(x):
1569
+ """
1570
+ For details, please refer to :func:`mindspore.ops.is_signed`.
1571
+ """
1572
+ return x.dtype in mstype.signed_type
1573
+
1574
+
1575
+ def is_complex(x):
1576
+ """
1577
+ For details, please refer to :func:`mindspore.ops.is_complex`.
1578
+ """
1579
+ return F.is_complex(x)
1580
+
1581
+
1582
+ def inv(x):
1583
+ """
1584
+ Computes Reciprocal of input tensor element-wise.
1585
+ """
1586
+ return F.inv(x)
1587
+
1588
+
1589
+ def inverse(input):
1590
+ """
1591
+ Computes the inverse of a square matrix.
1592
+ """
1593
+ return F.inverse(input)
1594
+
1595
+
1596
+ def invert(x):
1597
+ """
1598
+ Flips all bits of input tensor element-wise.
1599
+ """
1600
+ return F.invert(x)
1601
+
1602
+
1603
+ def trace(x, offset=0, axis1=0, axis2=1, dtype=None):
1604
+ """
1605
+ Returns the sum along diagonals of the array.
1606
+
1607
+ Args:
1608
+ offset (int, optional): Offset of the diagonal from the main diagonal.
1609
+ Can be positive or negative. Defaults to main diagonal.
1610
+ axis1 (int, optional): Axis to be used as the first axis of the 2-D
1611
+ sub-arrays from which the diagonals should be taken. Defaults to
1612
+ first axis (0).
1613
+ axis2 (int, optional): Axis to be used as the second axis of the 2-D
1614
+ sub-arrays from which the diagonals should be taken. Defaults to
1615
+ second axis.
1616
+ dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
1617
+ output Tensor.
1618
+
1619
+ Returns:
1620
+ Tensor, sum_along_diagonals.
1621
+
1622
+ Raises:
1623
+ ValueError: if the input tensor has less than two dimensions.
1624
+
1625
+ Supported Platforms:
1626
+ ``Ascend`` ``GPU`` ``CPU``
1627
+
1628
+ Examples:
1629
+ >>> import mindspore.numpy as np
1630
+ >>> x = np.eye(3)
1631
+ >>> print(x.trace())
1632
+ 3.0
1633
+ """
1634
+ return trace_v2_op(x, offset, axis1, axis2, dtype)
1635
+
1636
+
1637
+ def take(x, indices, axis=None, mode='clip'):
1638
+ """
1639
+ Takes elements from an array along an axis.
1640
+
1641
+ Args:
1642
+ a (Tensor): Source array with shape `(Ni…, M, Nk…)`.
1643
+ indices (Tensor): The indices with shape `(Nj...)` of the values to extract.
1644
+ axis (int, optional): The axis over which to select values. By default,
1645
+ the flattened input array is used. Defaults to None.
1646
+ mode ('raise', 'wrap', 'clip', optional): Defaults to "clip".
1647
+
1648
+ - edge: Pads with the edge values of `arr`.
1649
+ - raise: Raises an error;
1650
+ - wrap: Wraps around;
1651
+ - clip: Clips to the range. 'clip' mode means that all indices that are
1652
+ too large are replaced by the index that addresses the last element
1653
+ along that axis. Note that this disables indexing with negative numbers.
1654
+
1655
+ Returns:
1656
+ Tensor, the indexed result.
1657
+
1658
+ Raises:
1659
+ ValueError: if axis is out of range.
1660
+ TypeError: if the input is not a Tensor.
1661
+
1662
+ Supported Platforms:
1663
+ ``Ascend`` ``GPU`` ``CPU``
1664
+
1665
+ Examples:
1666
+ >>> import mindspore.numpy as np
1667
+ >>> a = np.array([4, 3, 5, 7, 6, 8])
1668
+ >>> indices = np.array([0, 1, 4])
1669
+ >>> output = a.take(indices)
1670
+ >>> print(output)
1671
+ [4 3 6]
1672
+ """
1673
+ if mode not in ('raise', 'wrap', 'clip'):
1674
+ const_utils.raise_value_error(
1675
+ 'raise should be one of "raise", "wrap", or "clip"')
1676
+ if axis is None:
1677
+ a = x.ravel()
1678
+ axis = 0
1679
+ else:
1680
+ a = x
1681
+ ndim = a.ndim
1682
+ axis = check_axis_in_range(axis, ndim)
1683
+
1684
+ shape_a = a.shape
1685
+ shape_indices = indices.shape
1686
+ size_indices = indices.size
1687
+ indices = compile_utils.check_indices(shape_a[axis], indices, mode)
1688
+
1689
+ # reshapes indices to shape (Ni..., Nj..., Nk)
1690
+ shape_ni = tuple_slice(shape_a, None, axis)
1691
+ shape_nk = tuple_slice(shape_a, axis + 1, None)
1692
+ shape_out = shape_ni + shape_indices + shape_nk
1693
+ shape_indices = expanded_shape(ndim, size_indices, axis)
1694
+ indices = indices.reshape(shape_indices)
1695
+ shape_indices = shape_ni + (indices.size,) + shape_nk
1696
+ indices = F.broadcast_to(indices, shape_indices)
1697
+
1698
+ res = F.gather_d(a, axis, indices)
1699
+ return res.reshape(shape_out)
1700
+
1701
+
1702
+ def ms_type(input, dtype=None):
1703
+ r"""
1704
+ Change the dtype of the Tensor to the `dtype` . Return the type if `dtype` is None.
1705
+ """
1706
+ if dtype is None:
1707
+ return str(input.dtype)
1708
+ return input.astype(dtype)
1709
+
1710
+
1711
+ def type_as(input, other):
1712
+ r"""
1713
+ Change the dtype of `input` to the dtype of `other`.
1714
+ """
1715
+ return input.astype(other.dtype)
1716
+
1717
+
1718
+ def _infer_out_shape(*shapes):
1719
+ """
1720
+ Returns shape of output after broadcasting. Raises ValueError if shapes cannot be broadcast.
1721
+ """
1722
+ shape_out = list()
1723
+ max_len = ms_max([len(it) for it in shapes])
1724
+ for i in range(max_len):
1725
+ items = [it[i - (max_len - len(it))] if i - (max_len - len(it))
1726
+ >= 0 else 1 for it in shapes]
1727
+ max_size = 0 if 0 in items else ms_max(items)
1728
+ shape_out.append(max_size)
1729
+ return tuple(shape_out)
1730
+
1731
+
1732
+ def choose(x, choices, mode='clip'):
1733
+ """
1734
+ Construct an array from an index array and a list of arrays to choose from.
1735
+
1736
+ Args:
1737
+ choices (sequence of arrays): Choice arrays. `a` and all of the `choices` must
1738
+ be broadcastable to the same shape. If `choices` is itself an array, then
1739
+ its outermost dimension (i.e., the one corresponding to ``choices.shape[0]``)
1740
+ is taken as defining the "sequence".
1741
+ mode ('raise', 'wrap', 'clip', optional): Specifies how indices outside
1742
+ ``[0, n-1]`` will be treated:
1743
+
1744
+ 'raise' – raise an error (default);
1745
+
1746
+ 'wrap' – wrap around;
1747
+
1748
+ 'clip' – clip to the range. 'clip' mode means that all indices that are
1749
+ too large are replaced by the index that addresses the last element
1750
+ along that axis. Note that this disables indexing with negative numbers.
1751
+
1752
+ Returns:
1753
+ Tensor, the merged result.
1754
+
1755
+ Supported Platforms:
1756
+ ``Ascend`` ``GPU`` ``CPU``
1757
+
1758
+ Raises:
1759
+ ValueError: if ``len(condlist) != len(choicelist)``.
1760
+
1761
+ Examples:
1762
+ >>> import mindspore.numpy as np
1763
+ >>> choices = [[0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33]]
1764
+ >>> x = np.array([2, 3, 1, 0])
1765
+ >>> print(x.choose(choices))
1766
+ [20 31 12 3]
1767
+ """
1768
+ if check_is_tensor(F.typeof(choices)):
1769
+ shape_choice = _infer_out_shape(x.shape, choices.shape[1:])
1770
+ choices = F.broadcast_to(choices, (choices.shape[0],) + shape_choice)
1771
+ else:
1772
+ # broadcasts choices to the same shape if choices is a sequence
1773
+ choicelist = []
1774
+ shapes = ()
1775
+ for choice in choices:
1776
+ if not check_is_tensor(F.typeof(choice)):
1777
+ choice = const_utils.make_tensor(choice)
1778
+ shapes += (choice.shape,)
1779
+ choicelist.append(choice)
1780
+ shape_choice = _infer_out_shape(x.shape, *shapes)
1781
+ tmp = []
1782
+ for choice in choicelist:
1783
+ tmp.append(F.broadcast_to(choice, shape_choice))
1784
+ choices = F.stack(tmp)
1785
+
1786
+ if x.ndim == 0 or choices.ndim == 0:
1787
+ const_utils.raise_value_error('input cannot be scalars')
1788
+ a = F.broadcast_to(x, shape_choice)
1789
+ dtype = choices.dtype
1790
+ # adjusts dtype for F.tensor_mul and F.gather_nd
1791
+ a = a.astype(mstype.int32)
1792
+ choices = choices.astype(mstype.int32)
1793
+ a = compile_utils.check_indices(
1794
+ choices.shape[0], a, mode, allow_negative_index=False)
1795
+
1796
+ grids = []
1797
+ ndim = len(a.shape)
1798
+ for i in range(ndim):
1799
+ dim_grid = const_utils.make_tensor(
1800
+ F.make_range(a.shape[i]), mstype.int32)
1801
+ dim_shape = expanded_shape(ndim, a.shape[i], i)
1802
+ dim_grid = F.broadcast_to(dim_grid.reshape(dim_shape), a.shape)
1803
+ grids.append(dim_grid)
1804
+ grid = P.Stack(-1)(grids)
1805
+ indices = P.Concat(-1)((a.reshape(a.shape + (1,)), grid))
1806
+ return F.gather_nd(choices, indices).astype(dtype)
1807
+
1808
+
1809
+ def searchsorted(x, v, side='left', sorter=None):
1810
+ """
1811
+ Finds indices where elements should be inserted to maintain order.
1812
+
1813
+ Args:
1814
+ v (Union[int, float, bool, list, tuple, Tensor]): Values to insert into `a`.
1815
+ side ('left', 'right', optional): If 'left', the index of the first suitable
1816
+ location found is given. If 'right', return the last such index. If there is
1817
+ no suitable index, return either 0 or N (where N is the length of `a`).
1818
+ sorter (Union[int, float, bool, list, tuple, Tensor]): 1-D optional array of
1819
+ integer indices that sort array `a` into ascending order. They are typically
1820
+ the result of argsort. CPU and GPU can only use default values
1821
+
1822
+ Returns:
1823
+ Tensor, array of insertion points with the same shape as `v`.
1824
+
1825
+ Raises:
1826
+ ValueError: if argument for `side` or `sorter` is invalid.
1827
+
1828
+ Supported Platforms:
1829
+ ``Ascend`` ``GPU`` ``CPU``
1830
+
1831
+ Examples:
1832
+ >>> from mindspore import numpy as np
1833
+ >>> x = np.array([1,2,3,4,5])
1834
+ >>> print(x.searchsorted(3))
1835
+ 2
1836
+ """
1837
+
1838
+ if side not in ('left', 'right'):
1839
+ raise ValueError(f"For 'Tensor.searchsorted', the argument 'side' should be one of in "
1840
+ f"['left', 'right'], but got {side}.")
1841
+ if not isinstance(v, Tensor):
1842
+ v = const_utils.make_tensor(v)
1843
+ if sorter is not None:
1844
+ if not isinstance(sorter, (int, list, tuple, Tensor)):
1845
+ raise TypeError("For Tensor.searchsorted, the type of the argument 'sorter' must be one of 'int', "
1846
+ "'list', 'tuple', 'Tensor', but got {}.".format(type(sorter)))
1847
+ if not isinstance(sorter, Tensor):
1848
+ sorter = const_utils.make_tensor(sorter)
1849
+ if sorter.size != x.size:
1850
+ raise ValueError('The size of sorter must be the same as the Tensor')
1851
+
1852
+ dtype = mstype.int32
1853
+ right = (side == 'right')
1854
+ search_sorted_ = P.SearchSorted(dtype, right)
1855
+ return search_sorted_(x, v, sorter)
1856
+
1857
+
1858
+ def fill(x, value):
1859
+ """
1860
+ `Tensor.fill` is deprecated, please use `ops.fill` instead.
1861
+ """
1862
+ if value is None:
1863
+ if x.dtype not in (mstype.float16, mstype.float32, mstype.float64):
1864
+ const_utils.raise_type_error("If None is used as value, the original Tensor's dtype must be float.")
1865
+ value = nan_tensor
1866
+ return F.tile(value, x.shape).astype(x.dtype)
1867
+ return F.fill(x.dtype, x.shape, value)
1868
+
1869
+
1870
+ def fills(x, value):
1871
+ """
1872
+ `Tensor.fills` is deprecated, please use `ops.fill` instead.
1873
+ """
1874
+ return F.fills(x, value)
1875
+
1876
+
1877
+ def fill_diagonal(x, fill_value, wrap=False):
1878
+ """
1879
+ Fills the main diagonal of a Tensor with a specified value and returns the result. The input has at least
1880
+ 2 dimensions, and all dimensions of input must be equal in length when the dimension of input is greater than 2.
1881
+ """
1882
+
1883
+ return P.FillDiagonal(fill_value, wrap)(x)
1884
+
1885
+
1886
+ def ptp(x, axis=None, keepdims=False):
1887
+ """
1888
+ The name of the function comes from the acronym for "peak to peak".
1889
+
1890
+ Note:
1891
+ Numpy arguments `dtype` and `out` are not supported.
1892
+
1893
+ Args:
1894
+ x (Tensor): Input tensor.
1895
+ axis (Union[None, int, tuple(int)]): Axis or axes along which the range is computed.
1896
+ The default is to compute the variance of the flattened array. Default: ``None``.
1897
+ keepdims (bool): Default is False.
1898
+
1899
+ Returns:
1900
+ Tensor.
1901
+
1902
+ Raises:
1903
+ TypeError: if the input is not a tensor.
1904
+
1905
+ Supported Platforms:
1906
+ ``Ascend`` ``GPU`` ``CPU``
1907
+
1908
+ Examples:
1909
+ >>> from mindspore import Tensor
1910
+ >>> x = Tensor([[4.0, 9.0, 2.0, 10.0], [6.0, 9.0, 7.0, 12.0]]).astype("float32")
1911
+ >>> print(x.ptp(axis=1))
1912
+ [8. 6.]
1913
+ >>> print(x.ptp(axis=0))
1914
+ [2. 0. 5. 2.]
1915
+ """
1916
+ if not isinstance(keepdims, bool):
1917
+ const_utils.raise_type_error('keepdims should be boolean')
1918
+ if axis is None:
1919
+ axis = ()
1920
+ else:
1921
+ validator.check_axis_type(axis, True, True, False)
1922
+ axis = check_axis_valid(axis, x.ndim)
1923
+
1924
+ return x.max(axis, keepdims) - x.min(axis, keepdims)
1925
+
1926
+
1927
+ def clamp(x, min=None, max=None):
1928
+ """
1929
+ Clamps all elements in `x` into the range `[min, max]`.
1930
+ """
1931
+ return F.clamp(x, min, max)
1932
+
1933
+
1934
+ def clip(x, min=None, max=None):
1935
+ """
1936
+ Clamps all elements in `x` into the range `[min, max]`.
1937
+ """
1938
+ return F.clamp(x, min, max)
1939
+
1940
+
1941
+ def var(x, axis=None, ddof=0, keepdims=False):
1942
+ """
1943
+ Compute the variance along the specified axis.
1944
+ The variance is the average of the squared deviations from the mean, i.e.,
1945
+ :math:`var = mean(abs(x - x.mean())**2)`.
1946
+
1947
+ Return the variance, which is computed for the flattened array by default,
1948
+ otherwise over the specified axis.
1949
+
1950
+ Note:
1951
+ Numpy arguments `dtype`, `out` and `where` are not supported.
1952
+
1953
+ Args:
1954
+ x (Tensor): A Tensor to be calculated.
1955
+ axis (Union[None, int, tuple(int)]): Axis or axes along which the variance is computed.
1956
+ The default is to compute the variance of the flattened array. Default: `None`.
1957
+ ddof (int): Means Delta Degrees of Freedom. Default: 0.
1958
+ The divisor used in calculations is :math:`N - ddof`, where :math:`N` represents the number of elements.
1959
+ keepdims (bool): Default: `False`.
1960
+
1961
+ Supported Platforms:
1962
+ ``Ascend`` ``GPU`` ``CPU``
1963
+
1964
+ Returns:
1965
+ Standard deviation tensor.
1966
+
1967
+ Examples:
1968
+ >>> import mindspore.numpy as np
1969
+ >>> input_x = np.array([1., 2., 3., 4.])
1970
+ >>> print(input_x.var())
1971
+ 1.25
1972
+ """
1973
+ if 0 in x.shape:
1974
+ return nan_tensor.astype(x.dtype)
1975
+ if not isinstance(ddof, int) or not isinstance(keepdims, int):
1976
+ const_utils.raise_type_error("integer argument expected")
1977
+
1978
+ if axis is None:
1979
+ axis = ()
1980
+ else:
1981
+ axis = check_and_canonicalize_axes(axis, x.ndim)
1982
+ x_mean = F.mean(x, axis, True)
1983
+ x_sub = F.tensor_sub(x, x_mean)
1984
+ x_pow = F.tensor_pow(x_sub, 2)
1985
+ if keepdims:
1986
+ x_sum = _reduce_sum_keepdims(x_pow, axis)
1987
+ else:
1988
+ x_sum = _reduce_sum_default(x_pow, axis)
1989
+
1990
+ if axis == ():
1991
+ axis = F.make_range(x.ndim)
1992
+ nums = 1
1993
+ for ax in axis:
1994
+ nums *= x.shape[ax]
1995
+ return F.tensor_div(x_sum, nums - ddof)
1996
+
1997
+
1998
+ def std(x, axis=None, ddof=0, keepdims=False):
1999
+ """
2000
+ Compute the standard deviation along the specified axis.
2001
+ The standard deviation is the square root of the average of the squared deviations
2002
+ from the mean, i.e., :math:`std = sqrt(mean(abs(x - x.mean())**2))`.
2003
+
2004
+ Return the standard deviation, which is computed for the flattened array by default,
2005
+ otherwise over the specified axis.
2006
+
2007
+ Note:
2008
+ Numpy arguments `dtype`, `out` and `where` are not supported.
2009
+
2010
+ Args:
2011
+ x (Tensor): A Tensor to be calculated.
2012
+ axis (Union[None, int, tuple(int)]): Axis or axes along which the standard
2013
+ deviation is computed. Default: `None`.
2014
+
2015
+ If `None`, compute the standard deviation of the flattened array.
2016
+ ddof (int): Means Delta Degrees of Freedom. The divisor used in calculations is :math:`N - ddof`,
2017
+ where :math:`N` represents the number of elements. Default: 0.
2018
+ keepdims: Default: `False`.
2019
+
2020
+ Returns:
2021
+ Standard deviation tensor.
2022
+
2023
+ Supported Platforms:
2024
+ ``Ascend`` ``GPU`` ``CPU``
2025
+
2026
+ Examples:
2027
+ >>> import mindspore.numpy as np
2028
+ >>> input_x = np.array([1., 2., 3., 4.])
2029
+ >>> print(input_x.std())
2030
+ 1.118034
2031
+ """
2032
+ x_var = var(x, axis, ddof, keepdims)
2033
+ return F.tensor_pow(x_var, 0.5)
2034
+
2035
+
2036
+ def gather_elements(input, dim, index):
2037
+ r"""
2038
+ Gathers elements along an axis specified by dim.
2039
+
2040
+ Refer to :func:`mindspore.ops.gather_elements` for more detail.
2041
+ """
2042
+ return F.gather_elements(input, dim, index)
2043
+
2044
+
2045
+ def sum(input, axis=None, dtype=None, keepdims=False, initial=None): # pylint: disable=redefined-builtin
2046
+ """
2047
+ Return sum of array elements over a given axis.
2048
+
2049
+ Note:
2050
+ Numpy arguments `out`, `where`, `casting`, `order`, `subok`, `signature`, and
2051
+ `extobj` are not supported.
2052
+
2053
+ Args:
2054
+ input (Union[int, float, bool, list, tuple, Tensor]): Elements to sum.
2055
+ axis (Union[None, int, tuple(int)]): Axis or axes along which a sum is performed. Default: ``None``.
2056
+ If None, sum all of the elements of the input array.
2057
+ If axis is negative it counts from the last to the first axis.
2058
+ If axis is a tuple of ints, a sum is performed on all of the axes specified in the tuple
2059
+ instead of a single axis or all the axes as before.
2060
+ dtype (:class:`mindspore.dtype`, optional): defaults to None. Overrides the dtype of the
2061
+ output Tensor.
2062
+ keepdims (bool): If this is set to True, the axes which are reduced are left in the result as
2063
+ dimensions with size one. With this option, the result will broadcast correctly against the input array.
2064
+ If the default value is passed, then keepdims will not be passed through to the sum method of
2065
+ sub-classes of ndarray, however any non-default value will be. If the sub-class method does not
2066
+ implement keepdims any exceptions will be raised.
2067
+ initial (scalar): Starting value for the sum.
2068
+
2069
+ Returns:
2070
+ Tensor. A tensor with the same shape as input, with the specified axis removed.
2071
+ If input tensor is a 0-d array, or if axis is None, a scalar is returned.
2072
+
2073
+ Raises:
2074
+ TypeError: If input is not array_like or `axis` is not int or tuple of ints or
2075
+ `keepdims` is not integer or `initial` is not scalar.
2076
+ ValueError: If any axis is out of range or duplicate axes exist.
2077
+
2078
+ Supported Platforms:
2079
+ ``Ascend`` ``GPU`` ``CPU``
2080
+
2081
+ Examples:
2082
+ >>> import mindspore.numpy as np
2083
+ >>> input_x = np.array([-1, 0, 1]).astype('int32')
2084
+ >>> print(input_x.sum())
2085
+ 0
2086
+ >>> input_x = np.arange(10).reshape(2, 5).astype('float32')
2087
+ >>> print(input_x.sum(axis=1))
2088
+ [10. 35.]
2089
+ """
2090
+ if initial is not None and not isinstance(initial, (int, float, bool)):
2091
+ raise TypeError(f"For Tensor.sum, initial must be int, float or bool, but got {type(initial)}.")
2092
+ res = F.sum(input, axis, keepdims)
2093
+ if initial is not None:
2094
+ res += initial
2095
+ if dtype is not None:
2096
+ res = res.astype(dtype)
2097
+ return res
2098
+
2099
+
2100
+ @_primexpr
2101
+ def _check_sum_to_size(size, input_dim, shape_input):
2102
+ """Check the length of size of sum_to_size."""
2103
+ if len(size) > input_dim:
2104
+ raise ValueError(f"For sum_to_size, size {size} is not expandable to the tensor size {shape_input}.")
2105
+
2106
+
2107
+ @_primexpr
2108
+ def _count_axes(size, input_shape, shape_input):
2109
+ """Count the sum axes for sum_to_size."""
2110
+ axes = []
2111
+ for i in range(len(size)):
2112
+ element = size[i]
2113
+ if element != input_shape[i] and element == 1:
2114
+ axes.append(i)
2115
+ elif element != input_shape[i]:
2116
+ raise ValueError(f"For sum_to_size, size {size} is not expandable to the tensor size {shape_input}.")
2117
+ return axes
2118
+
2119
+
2120
+ def sum_to_size(input, *size):
2121
+ """
2122
+ Sum `input` to the `size`. `size` must be expandable to the Tensor size.
2123
+ """
2124
+ if len(size) == 1 and isinstance(size[0], tuple):
2125
+ size = size[0]
2126
+ shape_input = input.shape
2127
+ _check_sum_to_size(size, input.ndim, shape_input)
2128
+ if len(size) < input.ndim:
2129
+ pre_axis = tuple(axis for axis in range(input.ndim - len(size)))
2130
+ input = input.sum(pre_axis)
2131
+
2132
+ axes = _count_axes(size, input.shape, shape_input)
2133
+ if axes:
2134
+ return input.sum(tuple(axes), keepdims=True)
2135
+ return input
2136
+
2137
+
2138
+ def nansum(input, axis=None, keepdims=False, *, dtype=None):
2139
+ """
2140
+ Computes sum of all elements, treating NaNs as zero.
2141
+ """
2142
+ return F.nansum(input, axis=axis, keepdims=keepdims, dtype=dtype)
2143
+
2144
+
2145
+ def nanmean(input, axis=None, keepdims=False, *, dtype=None):
2146
+ r"""
2147
+ Computes the mean of input tensor, ignoring NaN.
2148
+ """
2149
+ return F.nanmean(input, axis, keepdims, dtype=dtype)
2150
+
2151
+
2152
+ def nanmedian(input, axis=-1, keepdims=False):
2153
+ r"""
2154
+ Computes the median and indices of input tensor, ignoring NaN.
2155
+ If all elements in the specified dimensions are NaN, the result will be NaN.
2156
+ """
2157
+ return F.nanmedian(input, axis, keepdims)
2158
+
2159
+
2160
+ def repeat(x, repeats, axis=None):
2161
+ """
2162
+ Repeat elements of an array.
2163
+
2164
+ Args:
2165
+ x (Tensor): Input tensor.
2166
+ repeats (Union[int, tuple, list]): The number of repetitions for each element.
2167
+ `repeats` is broadcasted to fit the shape of the given axis.
2168
+ axis (int, optional): The axis along which to repeat values. By default,
2169
+ use the flattened input tensor, and return a flat output tensor.
2170
+
2171
+ Returns:
2172
+ Tensor, has the same shape as input tensor except along the given axis.
2173
+
2174
+ Raises:
2175
+ ValueError: if axis is out of range.
2176
+ TypeError: if input is not a Tensor.
2177
+
2178
+ Supported Platforms:
2179
+ ``Ascend`` ``GPU`` ``CPU``
2180
+
2181
+ Examples:
2182
+ >>> import mindspore.numpy as np
2183
+ >>> x = np.array(3)
2184
+ >>> print(x.repeat(4))
2185
+ [3 3 3 3]
2186
+ >>> x = np.array([[1,2],[3,4]])
2187
+ >>> print(x.repeat(2))
2188
+ [1 1 2 2 3 3 4 4]
2189
+ >>> print(x.repeat(3, axis=1))
2190
+ [[1 1 1 2 2 2]
2191
+ [3 3 3 4 4 4]]
2192
+ >>> print(x.repeat([1,2], axis=0))
2193
+ [[1 2]
2194
+ [3 4]
2195
+ [3 4]]
2196
+ """
2197
+ if not isinstance(repeats, (tuple, list)):
2198
+ repeats = (repeats,)
2199
+ for element in repeats:
2200
+ if not isinstance(element, int):
2201
+ const_utils.raise_type_error("Each element should be integer")
2202
+ if axis is None:
2203
+ x = ravel(x)
2204
+ axis = 0
2205
+ if not isinstance(axis, int):
2206
+ const_utils.raise_type_error('axes should be integers')
2207
+ check_axis_in_range(axis, x.ndim)
2208
+ axis = axis + x.ndim if axis < 0 else axis
2209
+
2210
+ if len(repeats) == 1:
2211
+ repeats = repeats[0]
2212
+ if repeats == 0:
2213
+ return empty_tensor(x.dtype)
2214
+ return repeat_elements(x, repeats, axis)
2215
+ size = x.shape[axis]
2216
+ if len(repeats) != size:
2217
+ const_utils.raise_value_error(
2218
+ 'operands could not be broadcast together')
2219
+ subs = P.Split(axis, size)(x)
2220
+ repeated_subs = []
2221
+ for sub_item, rep in zip(subs, repeats):
2222
+ if rep != 0:
2223
+ repeated_subs.append(repeat_elements(sub_item, rep, axis))
2224
+ return P.Concat(axis)(repeated_subs)
2225
+
2226
+
2227
+ def repeat_interleave(x, repeats, dim=None):
2228
+ """
2229
+ For details, please refer to :func:`mindspore.ops.repeat_interleave`.
2230
+ """
2231
+ return F.repeat_interleave(x, repeats, dim)
2232
+
2233
+
2234
+ def hardshrink(x, lambd=0.5):
2235
+ r"""
2236
+ Apply the Hard Shrink function for a tensor. Calculates the output according to the input elements.
2237
+
2238
+ The formula is defined as follows:
2239
+
2240
+ .. math::
2241
+ \text{HardShrink}(x) =
2242
+ \begin{cases}
2243
+ x, & \text{ if } x > \lambda \\
2244
+ x, & \text{ if } x < -\lambda \\
2245
+ 0, & \text{ otherwise }
2246
+ \end{cases}
2247
+
2248
+ Args:
2249
+ x (Tensor): Input tensor.
2250
+ lambd (float): The threshold :math:`\lambda` defined by the Hard Shrink formula. Default: 0.5.
2251
+
2252
+ Returns:
2253
+ Tensor, has the same shape and data type as input tensor.
2254
+
2255
+ Raises:
2256
+ TypeError: If `lambd` is not a float.
2257
+ TypeError: If dtype of the input tensor is neither float16 nor float32.
2258
+
2259
+ Supported Platforms:
2260
+ ``Ascend`` ``GPU`` ``CPU``
2261
+
2262
+ Examples:
2263
+ >>> import mindspore.numpy as np
2264
+ >>> x = np.array([[0.5, 1, 2.0], [0.0533, 0.0776, -2.1233]])
2265
+ >>> print(x.hardshrink())
2266
+ [[ 0. 1. 2. ]
2267
+ [ 0. 0. -2.1233]]
2268
+ """
2269
+ return P.HShrink(lambd)(x)
2270
+
2271
+
2272
+ def heaviside(x, values):
2273
+ r"""
2274
+ For details, please refer to :func:`mindspore.ops.heaviside`.
2275
+ """
2276
+ return F.heaviside(x, values)
2277
+
2278
+
2279
+ def hypot(x, other):
2280
+ r'''
2281
+ For details, please refer to :func:`mindspore.ops.hypot`.
2282
+ '''
2283
+ return F.hypot(x, other)
2284
+
2285
+
2286
+ def softmax(input, axis, dtype=None):
2287
+ return F.softmax(input, axis, dtype=dtype)
2288
+
2289
+
2290
+ def soft_shrink(input, lambd=0.5):
2291
+ """Apply the soft shrink function for a tensor. Calculates the output according to the input elements."""
2292
+ return F.soft_shrink(input, lambd)
2293
+
2294
+
2295
+ def matrix_determinant(input):
2296
+ """Computes the determinant of one or more square matrices."""
2297
+ return F.matrix_determinant(input)
2298
+
2299
+
2300
+ def log_matrix_determinant(input):
2301
+ """Computes the sign and the log of the absolute value of the determinant of one or more square matrices."""
2302
+ return F.log_matrix_determinant(input)
2303
+
2304
+
2305
+ def getitem(data, index):
2306
+ """Implementation of `getitem`."""
2307
+ return data.__getitem__(index)
2308
+
2309
+
2310
+ def setitem(data, index, value):
2311
+ """Implementation of `setitem`."""
2312
+ return data.__setitem__(index, value)
2313
+
2314
+
2315
+ def item(data, *args):
2316
+ """Implementation of `item`."""
2317
+ return compile_utils.tensor_item(data, *args)
2318
+
2319
+
2320
+ def itemset(data, *args):
2321
+ """Implementation of `itemset`."""
2322
+ return compile_utils.tensor_itemset(data, *args)
2323
+
2324
+
2325
+ @constexpr
2326
+ def cast_to_str(data):
2327
+ return str(data)
2328
+
2329
+
2330
+ def str_func(*data):
2331
+ """Implementation of `str`."""
2332
+ data_len = len(data)
2333
+ if data_len >= 2:
2334
+ const_utils.raise_type_error("str() requires 0 or 1 arguments.")
2335
+ if data_len == 0:
2336
+ return ''
2337
+ data = data[0]
2338
+ if F.isconstant(data):
2339
+ return cast_to_str(data)
2340
+ return data.__str__()
2341
+
2342
+
2343
+ @constexpr
2344
+ def cast_to_bool(data):
2345
+ return bool(data)
2346
+
2347
+
2348
+ def bool_func(*data):
2349
+ """Implementation of `bool`."""
2350
+ data_len = len(data)
2351
+ if data_len >= 2:
2352
+ const_utils.raise_type_error("bool() requires 0 or 1 arguments.")
2353
+ if data_len == 0:
2354
+ return False
2355
+ data = data[0]
2356
+ if isinstance(data, (Tensor, Tensor_)):
2357
+ tensor_shape = F.shape(data)
2358
+ tensor_shape_len = len(tensor_shape)
2359
+ if tensor_shape_len == 0 or (tensor_shape_len == 1 and tensor_shape[0] == 1):
2360
+ data = F.cast(data, mstype.bool_)
2361
+ return TensorToScalar()(data)
2362
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2363
+ if not F.isconstant(data):
2364
+ if hasattr(data, "__bool__"):
2365
+ return data.__bool__()
2366
+ if hasattr(data, "__len__"):
2367
+ return len(data) != 0
2368
+ return F.scalar_cast(data, mstype.bool_)
2369
+ if isinstance(data, (CSRTensor, COOTensor, RowTensorInner)):
2370
+ raise TypeError("bool() does not support sparse tensor input.")
2371
+ return cast_to_bool(data)
2372
+
2373
+
2374
+ @constexpr
2375
+ def cast_to_int(*data):
2376
+ target = data[0]
2377
+ if isinstance(target, (Tensor, Tensor_)):
2378
+ target = Tensor(target, internal=True)
2379
+ if len(data) == 1:
2380
+ return int(target)
2381
+ return int(target, data[1])
2382
+
2383
+
2384
+ def int_func(*data):
2385
+ """Implementation of `int`."""
2386
+ data_len = len(data)
2387
+ if data_len >= 3:
2388
+ const_utils.raise_type_error("int() requires 0, 1 or 2 arguments.")
2389
+ if data_len == 0:
2390
+ return 0
2391
+ target = data[0]
2392
+ base = 10
2393
+ if data_len == 2:
2394
+ base = data[1]
2395
+ if not F.isconstant(target):
2396
+ if base != 10:
2397
+ const_utils.raise_type_error("int() does not support non-constant input when 'base' is specified.")
2398
+ if isinstance(target, Tensor):
2399
+ tensor_shape = F.shape(target)
2400
+ tensor_shape_len = len(tensor_shape)
2401
+ if tensor_shape_len == 0 or (tensor_shape_len == 1 and tensor_shape[0] == 1):
2402
+ target = F.cast(target, mstype.int64)
2403
+ return TensorToScalar()(target)
2404
+ raise ValueError(f"Can not convert Tensor with more than one element to Scalar, "
2405
+ f"while the data's shape is : {tensor_shape}")
2406
+ return F.scalar_cast(target, mstype.int64)
2407
+ if isinstance(target, (CSRTensor, COOTensor, RowTensorInner)):
2408
+ const_utils.raise_type_error(
2409
+ "int() does not support sparse tensor input.")
2410
+ return cast_to_int(*data)
2411
+
2412
+
2413
+ @constexpr
2414
+ def cast_to_float(data):
2415
+ if isinstance(data, (Tensor, Tensor_)):
2416
+ data = Tensor(data, internal=True)
2417
+ return float(data)
2418
+
2419
+
2420
+ def float_func(*data):
2421
+ """Implementation of `float`."""
2422
+ data_len = len(data)
2423
+ if data_len >= 2:
2424
+ const_utils.raise_type_error("float() requires 0 or 1 arguments.")
2425
+ if data_len == 0:
2426
+ return 0.0
2427
+ data = data[0]
2428
+ if not F.isconstant(data):
2429
+ if isinstance(data, Tensor):
2430
+ tensor_shape = F.shape(data)
2431
+ tensor_shape_len = len(tensor_shape)
2432
+ if tensor_shape_len == 0 or (tensor_shape_len == 1 and tensor_shape[0] == 1):
2433
+ data = F.cast(data, mstype.float32)
2434
+ return TensorToScalar()(data)
2435
+ raise ValueError(f"Can not convert Tensor with more than one element to Scalar, "
2436
+ f"while the data's shape is: {tensor_shape}")
2437
+ return F.scalar_cast(data, mstype.float32)
2438
+ if isinstance(data, (CSRTensor, COOTensor, RowTensorInner)):
2439
+ const_utils.raise_type_error(
2440
+ "float() does not support sparse tensor input.")
2441
+ return cast_to_float(data)
2442
+
2443
+
2444
+ def list_func(data):
2445
+ """Implementation of `list`."""
2446
+ if isinstance(data, (CSRTensor, COOTensor, RowTensorInner)):
2447
+ raise TypeError(
2448
+ "list() does not support single sparse tensor input.")
2449
+ if isinstance(data, dict):
2450
+ data = data.keys()
2451
+ if isinstance(data, (tuple, list)) and F.is_sequence_shape_unknown(data):
2452
+ ret = mutable([], True)
2453
+ if F.is_dynamic_sequence_element_unknown(data):
2454
+ return ret
2455
+ else:
2456
+ ret = F.make_list()
2457
+ for i in data:
2458
+ ret = ret + F.make_list(i)
2459
+ return ret
2460
+
2461
+
2462
+ def tuple_func(data):
2463
+ """Implementation of `tuple`."""
2464
+ if isinstance(data, (CSRTensor, COOTensor, RowTensorInner)):
2465
+ raise TypeError("tuple() does not support single sparse tensor input.")
2466
+ if isinstance(data, dict):
2467
+ data = data.keys()
2468
+ if isinstance(data, (tuple, list)) and F.is_sequence_shape_unknown(data):
2469
+ ret = mutable((), True)
2470
+ if F.is_dynamic_sequence_element_unknown(data):
2471
+ return ret
2472
+ else:
2473
+ ret = F.make_tuple()
2474
+ for i in data:
2475
+ ret = ret + F.make_tuple(i)
2476
+ return ret
2477
+
2478
+
2479
+ def ms_zip(*data):
2480
+ """Packs elements in the corresponding positions in multiple sequences into tuples."""
2481
+ x = ()
2482
+ for i in data:
2483
+ if isinstance(i, Tensor):
2484
+ if len(F.shape(i)) == 0:
2485
+ raise TypeError("Cannot iterate over a scalar tensor.")
2486
+ i = tuple(i)
2487
+ x = x + (i,)
2488
+ return composite.zip_operation(*x)
2489
+
2490
+
2491
+ def max_tensor(*data):
2492
+ """Get the max of tensor inputs."""
2493
+ if len(data) == 1:
2494
+ data = data[0]
2495
+ max_tensor_data = data[0]
2496
+ for input_data in data:
2497
+ max_tensor_data = P.Maximum()(max_tensor_data, input_data)
2498
+ return max_tensor_data
2499
+
2500
+
2501
+ def get_max_min_data_len(*data):
2502
+ """Get the real length of data."""
2503
+ len_data = 0
2504
+ if isinstance(data, tuple) and len(data) == 1 and isinstance(data[0], (dict, list, tuple)):
2505
+ data = data[0]
2506
+ if isinstance(data, dict):
2507
+ data = iter(data)
2508
+ if isinstance(data, (dict, list, tuple)):
2509
+ len_data = len(data)
2510
+ else:
2511
+ raise TypeError("max() or min() does not support the data type.")
2512
+ return len_data
2513
+
2514
+
2515
+ def get_tensor_num(data):
2516
+ """Get the number of tensor in data."""
2517
+ tensor_num = 0
2518
+ for input_data in data:
2519
+ if isinstance(input_data, Tensor):
2520
+ tensor_shape = F.shape(input_data)
2521
+ tensor_shape_len = len(tensor_shape)
2522
+ if tensor_shape_len != 0 and not (tensor_shape_len == 1 and tensor_shape[0] == 1):
2523
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2524
+ tensor_num = tensor_num + 1
2525
+ return tensor_num
2526
+
2527
+
2528
+ def exist_tensor(data):
2529
+ """Check if tensor exist in sequence."""
2530
+ for input_data in data:
2531
+ if isinstance(input_data, Tensor):
2532
+ return True
2533
+ if isinstance(input_data, (list, tuple)):
2534
+ if exist_tensor(input_data):
2535
+ return True
2536
+ return False
2537
+
2538
+
2539
+ def check_sequence_all_variable_scalar(x, str_info):
2540
+ """Check whether x can be used in SequenceMax and SequenceMin"""
2541
+ if F.is_sequence_shape_unknown(x):
2542
+ if F.is_dynamic_sequence_element_unknown(x):
2543
+ raise ValueError(str_info + "() arg is an empty sequence.")
2544
+ if not isinstance(x[0], (int, float)):
2545
+ raise ValueError(
2546
+ "When the input to " + str_info + "() is dynamic length sequence, only support scalar type input")
2547
+ return True
2548
+ contain_variable_scalar = False
2549
+ for i in x:
2550
+ if not isinstance(i, (int, float)):
2551
+ return False
2552
+ if not contain_variable_scalar and not F.isconstant(i):
2553
+ contain_variable_scalar = True
2554
+ return contain_variable_scalar
2555
+
2556
+
2557
+ def ms_max_one_element(x):
2558
+ """Implementation of `max` which inputs has only one element."""
2559
+ if isinstance(x, Tensor):
2560
+ tensor_shape = F.shape(x)
2561
+ tensor_shape_len = len(tensor_shape)
2562
+ if tensor_shape_len == 0:
2563
+ raise TypeError("Cannot iterate over a scalar tensor.")
2564
+ if tensor_shape_len >= 2:
2565
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2566
+ return x.max()
2567
+ # Deal with Tensor in tuple or list
2568
+ if isinstance(x, (list, tuple)):
2569
+ if check_sequence_all_variable_scalar(x, "max"):
2570
+ return SequenceMax()(x)
2571
+ if len(x) == 0:
2572
+ raise ValueError("max() arg is an empty sequence.")
2573
+ tensor_num = get_tensor_num(x)
2574
+ if F.isconstant(tensor_num) and F.isconstant(len(x)) and tensor_num == len(x):
2575
+ return max_tensor(x)
2576
+ if tensor_num != 0:
2577
+ return F._py_interpret("max(x)", {}, {"x": x})
2578
+ if exist_tensor(x):
2579
+ raise TypeError("max() cannot support tensor in list or tuple nested now.")
2580
+ if not isinstance(x, (int, float, bool)):
2581
+ return F._py_interpret("max(x)", {}, {"x": x})
2582
+ raise TypeError("The object is not iterable.")
2583
+
2584
+
2585
+ def ms_max(*data):
2586
+ """Implementation of `max`."""
2587
+ len_data = get_max_min_data_len(data)
2588
+ if len_data <= 0: # pylint: disable=no-else-raise
2589
+ raise TypeError("max() requires 1 argument at least.")
2590
+ elif len_data == 1:
2591
+ x = data[0]
2592
+ return ms_max_one_element(x)
2593
+ elif len_data >= 2:
2594
+ tensor_num = get_tensor_num(data)
2595
+ # All inputs is Tensor
2596
+ if F.isconstant(tensor_num) and F.isconstant(len_data) and tensor_num == len_data:
2597
+ return max_tensor(*data)
2598
+ if tensor_num != 0:
2599
+ return F._py_interpret("max(data)", {}, {"data": data})
2600
+ # exist tensor in list/tuple
2601
+ if exist_tensor(data):
2602
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2603
+ return F._py_interpret("max(data)", {}, {"data": data})
2604
+
2605
+
2606
+ def min_tensor(*data):
2607
+ """Get the min of tensor inputs."""
2608
+ if len(data) == 1:
2609
+ data = data[0]
2610
+ min_tensor_data = data[0]
2611
+ for input_data in data:
2612
+ min_tensor_data = P.Minimum()(min_tensor_data, input_data)
2613
+ return min_tensor_data
2614
+
2615
+
2616
+ def min_list_tuple(seq1, seq2):
2617
+ """Get the min of two sequence."""
2618
+ if len(seq1) == 0:
2619
+ return seq1
2620
+ if len(seq2) == 0:
2621
+ return seq2
2622
+ min_len = min(len(seq1), len(seq2))
2623
+ for i in min_len:
2624
+ if seq1[i] == seq2[i]:
2625
+ continue
2626
+ iter_min = ms_min([seq1[i], seq2[i]])
2627
+ if iter_min == seq1[i]:
2628
+ return seq1
2629
+ return seq2
2630
+ return seq1
2631
+
2632
+
2633
+ def ms_min_one_element(x):
2634
+ """Implementation of `min` which inputs has only one element."""
2635
+ if isinstance(x, Tensor):
2636
+ tensor_shape = F.shape(x)
2637
+ tensor_shape_len = len(tensor_shape)
2638
+ if tensor_shape_len == 0:
2639
+ raise TypeError("Cannot iterate over a scalar tensor.")
2640
+ if tensor_shape_len >= 2:
2641
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2642
+ return x.min()
2643
+ # Deal with Tensor in tuple or list
2644
+ if isinstance(x, (list, tuple)):
2645
+ if check_sequence_all_variable_scalar(x, "min"):
2646
+ return SequenceMin()(x)
2647
+ if len(x) == 0:
2648
+ raise ValueError("min() arg is an empty sequence.")
2649
+ tensor_num = get_tensor_num(x)
2650
+ if F.isconstant(tensor_num) and F.isconstant(len(x)) and tensor_num == len(x):
2651
+ return min_tensor(x)
2652
+ if tensor_num != 0:
2653
+ return F._py_interpret("min(x)", {}, {"x": x})
2654
+ if exist_tensor(x):
2655
+ raise TypeError("min() cannot support tensor in list or tuple nested now.")
2656
+ if not isinstance(x, (int, float, bool)):
2657
+ return F._py_interpret("min(x)", {}, {"x": x})
2658
+ raise TypeError("The object is not iterable.")
2659
+
2660
+
2661
+ def ms_min(*data):
2662
+ """Implementation of `min`."""
2663
+ len_data = get_max_min_data_len(data)
2664
+ if len_data <= 0: # pylint: disable=no-else-raise
2665
+ raise TypeError("min() requires 1 argument at least.")
2666
+ elif len_data == 1:
2667
+ x = data[0]
2668
+ return ms_min_one_element(x)
2669
+ elif len_data >= 2:
2670
+ tensor_num = get_tensor_num(data)
2671
+ # All inputs is Tensor
2672
+ if F.isconstant(tensor_num) and F.isconstant(len_data) and tensor_num == len_data:
2673
+ return min_tensor(*data)
2674
+ if tensor_num != 0:
2675
+ return F._py_interpret("min(data)", {}, {"data": data})
2676
+ # exist tensor in list/tuple
2677
+ if exist_tensor(data):
2678
+ raise ValueError("The truth value of an array with more than one element is ambiguous.")
2679
+ return F._py_interpret("min(data)", {}, {"data": data})
2680
+
2681
+
2682
+ def ms_sum(*data):
2683
+ """Implementation of `sum`."""
2684
+ len_data = len(data)
2685
+ if len_data <= 0 or len_data > 2:
2686
+ raise TypeError("sum() requires 1 or 2 arguments.")
2687
+ x = data[0]
2688
+ if isinstance(x, (int, float, bool)):
2689
+ data_type = F.typeof(x)
2690
+ raise TypeError(str(data_type) + " object is not iterable.")
2691
+ if isinstance(x, Tensor):
2692
+ tensor_shape = F.shape(x)
2693
+ if len(tensor_shape) == 0:
2694
+ raise TypeError("Cannot iterate over a scalar tensor.")
2695
+ if isinstance(x, dict):
2696
+ x = x.keys()
2697
+ result = 0
2698
+ if len_data == 2:
2699
+ result = data[1]
2700
+ if isinstance(x, Tensor):
2701
+ result += x.sum(0)
2702
+ else:
2703
+ for element in x:
2704
+ result += element
2705
+ return result
2706
+
2707
+
2708
+ def ms_len(data):
2709
+ """Implementation of `len`."""
2710
+ return data.__len__()
2711
+
2712
+
2713
+ def floor(x):
2714
+ """Rounds a tensor down to the closest integer element-wise."""
2715
+ return F.floor(x)
2716
+
2717
+
2718
+ def floor_divide(input, other):
2719
+ r"""
2720
+ Divides the first input tensor by the second input tensor element-wise and round down to the closest integer.
2721
+ """
2722
+ return F.floor_divide(input, other)
2723
+
2724
+
2725
+ def uadd(x):
2726
+ """Implementation of `uadd`."""
2727
+ return x.__pos__()
2728
+
2729
+
2730
+ def usub(x):
2731
+ """Implementation of `usub`."""
2732
+ return x.__neg__()
2733
+
2734
+
2735
+ def scalar_truediv(x, y):
2736
+ """Implementation of `scalar_truediv`."""
2737
+ return x.__truediv__(y)
2738
+
2739
+
2740
+ def scalar_floordiv(x, y):
2741
+ """Implementation of `scalar_floordiv`."""
2742
+ return x.__floordiv__(y)
2743
+
2744
+
2745
+ def bool_(x):
2746
+ """Implementation of `bool`."""
2747
+ return x.__bool__()
2748
+
2749
+
2750
+ def check_len_(x):
2751
+ """Check length is not 0"""
2752
+ return x.__len__() != 0
2753
+
2754
+
2755
+ def real_bool_(x):
2756
+ """bool function to get truth value"""
2757
+ return bool(x)
2758
+
2759
+
2760
+ def enumerate_(x, start=0):
2761
+ """Enumerate list or tuple or tensor."""
2762
+ x_type = F.typeof(x)
2763
+ ret = ()
2764
+ op_name = "enumerate"
2765
+ if isinstance(x, (int, float, bool)):
2766
+ raise TypeError(f"For 'enumerate', the 'first input' should be tuple or list or tensor, but got {type(x)}.")
2767
+ if check_is_const_int(start, op_name, "start"):
2768
+ if check_is_tensor(x_type):
2769
+ for i in range(x.shape[0]):
2770
+ ret += ((start + i, x[i]),)
2771
+ else:
2772
+ ret = zip(range(start, start + len(x)), x)
2773
+ return ret
2774
+
2775
+
2776
+ def expand_tensor_as(x, y):
2777
+ """Expand tensor"""
2778
+ return F.broadcast_to(x, shape_(y))
2779
+
2780
+
2781
+ def broadcast_to(x, shape):
2782
+ """Broadcasts tensor to a given shape."""
2783
+ return F.broadcast_to(x, shape)
2784
+
2785
+
2786
+ def expand_dims(x, axis):
2787
+ """
2788
+ Insert a dimension of shape 1 at the specified axis of Tensor.
2789
+ """
2790
+ validator.check_is_int(axis, 'axis')
2791
+ return P.ExpandDims()(x, axis)
2792
+
2793
+
2794
+ def unsqueeze(input, dim):
2795
+ """For details, please refer to :func:`mindspore.ops.unsqueeze`."""
2796
+ return P.ExpandDims()(input, dim)
2797
+
2798
+
2799
+ def masked_fill(x, mask, value):
2800
+ """
2801
+ Fills elements of Tensor with value where mask is True.
2802
+ """
2803
+ check_is_tensor(mask)
2804
+ check_type_name('mask', mask.dtype, [mstype.bool_], "Tensor")
2805
+ return F.masked_fill(x, mask, value)
2806
+
2807
+
2808
+ def col2im(*inputs):
2809
+ """
2810
+ inputs: input_x, output_size, kernel_size, dilation, padding_value, stride
2811
+ Combines an array of sliding local blocks into a large containing tensor.
2812
+ """
2813
+ return F.col2im(*inputs)
2814
+
2815
+
2816
+ def narrow(input, axis, start, length):
2817
+ """
2818
+ Returns a narrowed tensor from input tensor.
2819
+ The dimension axis is input from start to start + length.
2820
+ """
2821
+ return F.narrow(input, axis, start, length)
2822
+
2823
+
2824
+ def to_csr(x):
2825
+ """
2826
+ Convert a Tensor to CSRTensor.
2827
+ Please refer to tensor.py Tensor::to_csr(self) for more details.
2828
+ """
2829
+ return F.dense_to_sparse_csr(x)
2830
+
2831
+
2832
+ def to_coo(x):
2833
+ """
2834
+ Convert a Tensor to COOTensor.
2835
+ Please refer to tensor.py Tensor::to_coo(self) for more details.
2836
+ """
2837
+ return F.dense_to_sparse_coo(x)
2838
+
2839
+
2840
+ def tolist(x):
2841
+ """
2842
+ Convert a Tensor to List, if the input is Tensor scalar, Python scalar will be returned.
2843
+ """
2844
+ return x.asnumpy().tolist()
2845
+
2846
+
2847
+ @constexpr
2848
+ def check_select_condition(cond_type):
2849
+ """
2850
+ Check select input condition.
2851
+ """
2852
+ if isinstance(cond_type, mstype.TensorType):
2853
+ return
2854
+ raise TypeError(
2855
+ f"For select, the argument condition should be Tensor, but got {cond_type}.")
2856
+
2857
+
2858
+ @constexpr
2859
+ def check_select_input(y, x_dtype):
2860
+ """
2861
+ Check select input x and y.
2862
+ """
2863
+ if not isinstance(y, (int, float)):
2864
+ raise TypeError(f"For 'Tensor.select', the argument 'y' should be Tensor, int or float,"
2865
+ f" but got {type(y)}.")
2866
+ if isinstance(y, int) and x_dtype != mstype.int32:
2867
+ raise TypeError(f"For 'Tensor.select', if the argument 'y' is int,"
2868
+ f" then the tensor type should be int32 but got {x_dtype}")
2869
+ if isinstance(y, float) and x_dtype != mstype.float32:
2870
+ raise TypeError(f"For 'Tensor.select', if the argument 'y' is float,"
2871
+ f" then the tensor type should be float32 but got {x_dtype}")
2872
+
2873
+
2874
+ def select(x, condition, y):
2875
+ """Returns the selected elements for tensor 'x' and input 'y' according to input 'condition'"""
2876
+ check_select_condition(F.typeof(condition))
2877
+ if not isinstance(y, Tensor):
2878
+ check_select_input(y, x.dtype)
2879
+ input_y = y
2880
+ if isinstance(y, (int, float)):
2881
+ input_y = F.zeros_like(x) + y
2882
+ if isinstance(y, int):
2883
+ input_y = F.cast(input_y, mstype.int32)
2884
+ else:
2885
+ input_y = F.cast(input_y, mstype.float32)
2886
+ return F.select(condition, x, input_y)
2887
+
2888
+
2889
+ def view(x, *shape):
2890
+ """Reshape tensor, if shape is -1, reshape tensor into one dimension"""
2891
+ shape = check_view_shape(shape)
2892
+ return F.reshape(x, shape)
2893
+
2894
+
2895
+ def view_as(input, other):
2896
+ """View self Tensor as the same shape as `other` ."""
2897
+ if not isinstance(other, (Tensor, Tensor_)):
2898
+ raise TypeError(f"For view_as, the input other must be a Tensor, but got {type(other)}")
2899
+ return F.reshape(input, other.shape)
2900
+
2901
+
2902
+ def bitwise_and(x, y):
2903
+ """Returns bitwise `and` of two tensors element-wise."""
2904
+ return F.bitwise_and(x, y)
2905
+
2906
+
2907
+ def bitwise_or(x, y):
2908
+ """Returns bitwise `or` of two tensors element-wise."""
2909
+ return F.bitwise_or(x, y)
2910
+
2911
+
2912
+ def bitwise_xor(x, y):
2913
+ """Returns bitwise `xor` of two tensors element-wise."""
2914
+ return F.bitwise_xor(x, y)
2915
+
2916
+
2917
+ def bitwise_left_shift(x, y):
2918
+ """Returns bitwise left shift of `x` by `other` bits."""
2919
+ return F.bitwise_left_shift(x, y)
2920
+
2921
+
2922
+ def bitwise_right_shift(x, y):
2923
+ """Returns bitwise right shift of `x` by `other` bits."""
2924
+ return F.bitwise_right_shift(x, y)
2925
+
2926
+
2927
+ def exp(x):
2928
+ """Returns exponential of a tensor element-wise."""
2929
+ return F.exp(x)
2930
+
2931
+
2932
+ def real(x):
2933
+ r"""
2934
+ For details, please refer to :func:`mindspore.ops.real`.
2935
+ """
2936
+ return F.real(x)
2937
+
2938
+
2939
+ def rsqrt(x):
2940
+ r"""
2941
+ For details, please refer to :func:`mindspore.ops.rsqrt`.
2942
+ """
2943
+ return F.rsqrt(x)
2944
+
2945
+
2946
+ def reciprocal(x):
2947
+ r"""
2948
+ For details, please refer to :func:`mindspore.ops.reciprocal`.
2949
+ """
2950
+ return F.reciprocal(x)
2951
+
2952
+
2953
+ def sqrt(x):
2954
+ """Returns sqrt of a tensor element-wise."""
2955
+ return F.sqrt(x)
2956
+
2957
+
2958
+ def square(x):
2959
+ """Returns square of a tensor element-wise."""
2960
+ return F.square(x)
2961
+
2962
+
2963
+ def sub(x, y):
2964
+ """Returns sub of a tensor element-wise."""
2965
+ return F.sub(x, y)
2966
+
2967
+
2968
+ def t(input):
2969
+ """Transposes a 2-D tensor."""
2970
+ return F.t(input)
2971
+
2972
+
2973
+ def tan(x):
2974
+ """Returns tangent of `x`."""
2975
+ return F.tan(x)
2976
+
2977
+
2978
+ def tanh(x):
2979
+ """Returns hyperbolic tangent of `x`."""
2980
+ return F.tanh(x)
2981
+
2982
+
2983
+ def cosh(x):
2984
+ """
2985
+ Computes hyperbolic cosine of `x` element-wise.
2986
+ """
2987
+ return F.cosh(x)
2988
+
2989
+
2990
+ def ger(input, vec2):
2991
+ """Ger product of `input` and `vec2`."""
2992
+ return F.ger(input, vec2)
2993
+
2994
+
2995
+ def gt(x, y):
2996
+ """Compare the value of the input parameters :math:`x > y` element-wise."""
2997
+ return F.gt(x, y)
2998
+
2999
+
3000
+ def ge(x, y):
3001
+ """Compare the value of the input parameters :math:`x >= y` element-wise."""
3002
+ return F.ge(x, y)
3003
+
3004
+
3005
+ def tensor_scatter_add(x, indices, updates):
3006
+ """
3007
+ Creates a new tensor by adding the values from the positions in `x` indicated by
3008
+ `indices`, with values from `updates`. When multiple values are given for the same
3009
+ index, the updated result will be the sum of all values.
3010
+ """
3011
+ return F.tensor_scatter_add(x, indices, updates)
3012
+
3013
+
3014
+ def tensor_scatter_sub(x, indices, updates):
3015
+ """
3016
+ Creates a new tensor by subtracting the values from the positions in `x` indicated by
3017
+ `indices`, with values from `updates`. When multiple values are given for the same
3018
+ index, the updated result will be the sum of all values.
3019
+ """
3020
+ return F.tensor_scatter_sub(x, indices, updates)
3021
+
3022
+
3023
+ def tensor_scatter_mul(input_x, indices, updates):
3024
+ """
3025
+ Create a new tensor by multiplying the values from the positions in `input_x` indicated by
3026
+ `indices`, with values from `updates`. When multiple value are given for the same index,
3027
+ the output result will be the division of values.
3028
+ """
3029
+ return F.tensor_scatter_mul(input_x, indices, updates)
3030
+
3031
+
3032
+ def tensor_sactter_div(input_x, indices, updates):
3033
+ """
3034
+ Create a new tensor by division the values from the positions in `input_x` indicated by
3035
+ `indices`, with values from `updates`. When multiple value are given for the same index,
3036
+ the output result will be the division of values.
3037
+ """
3038
+ return F.tensor_scatter_div(input_x, indices, updates)
3039
+
3040
+
3041
+ def tensor_scatter_max(x, indices, updates):
3042
+ """
3043
+ By comparing the value at the position indicated by `indices` in `x` with the value in the `updates`,
3044
+ the value at the index will eventually be equal to the largest one to create a new tensor.
3045
+ """
3046
+ return F.tensor_scatter_max(x, indices, updates)
3047
+
3048
+
3049
+ def tensor_scatter_min(x, indices, updates):
3050
+ """
3051
+ By comparing the value at the position indicated by `indices` in `x` with the value in the `updates`,
3052
+ the value at the index will eventually be equal to the smallest one to create a new tensor.
3053
+ """
3054
+ return F.tensor_scatter_min(x, indices, updates)
3055
+
3056
+
3057
+ def unsorted_segment_min(x, segment_ids, num_segments):
3058
+ """Apply the unsorted segment min function for a tensor. Calculates the output according to the input elements."""
3059
+ return F.unsorted_segment_min(x, segment_ids, num_segments)
3060
+
3061
+
3062
+ def unsorted_segment_max(x, segment_ids, num_segments):
3063
+ """Apply the unsorted segment max function for a tensor. Calculates the output according to the input elements."""
3064
+ return F.unsorted_segment_max(x, segment_ids, num_segments)
3065
+
3066
+
3067
+ def unsorted_segment_prod(x, segment_ids, num_segments):
3068
+ """Apply the unsorted segment prod function for a tensor. Calculates the output according to the input elements."""
3069
+ return F.unsorted_segment_prod(x, segment_ids, num_segments)
3070
+
3071
+
3072
+ def negative(input):
3073
+ r"""
3074
+ Return a new tensor with the negative of the elements of input.
3075
+ """
3076
+ return F.neg(input)
3077
+
3078
+
3079
+ def nonzero(input, as_tuple=False):
3080
+ """
3081
+ Return a Tensor of the positions of all non-zero values.
3082
+ """
3083
+ return F.nonzero(input, as_tuple)
3084
+
3085
+
3086
+ def new_zeros(x, size, *, dtype=None):
3087
+ r"""
3088
+ Return a tensor of `size` filled with zeros. By default, the returned tensor has the same dtype as `x`.
3089
+ """
3090
+ _dtype = x.dtype if dtype is None else dtype
3091
+ return F.zeros(size, dtype=_dtype)
3092
+
3093
+
3094
+ def new_ones(x, size, *, dtype=None):
3095
+ r"""
3096
+ Return a tensor of `size` filled with ones. By default, the returned tensor has the same dtype as `x`.
3097
+ """
3098
+ _dtype = x.dtype if dtype is None else dtype
3099
+ return F.ones(size, dtype=_dtype)
3100
+
3101
+
3102
+ def diag(x):
3103
+ """
3104
+ Constructs a diagonal tensor with a given diagonal values.
3105
+ """
3106
+ return F.diag(x)
3107
+
3108
+
3109
+ def diagflat(input, offset=0):
3110
+ """
3111
+ Creates a two-dimensional Tensor with the flattened input as a diagonal.
3112
+ """
3113
+ return F.diagflat(input, offset)
3114
+
3115
+
3116
+ def masked_select(input, mask):
3117
+ """
3118
+ Returns a new 1-D Tensor which indexes the input tensor according to the boolean mask.
3119
+ """
3120
+ return F.masked_select(input, mask)
3121
+
3122
+
3123
+ def inplace_update(x, v, indices):
3124
+ """
3125
+ Update specified rows of x with values in v according to indices.
3126
+ """
3127
+ return F.inplace_update(x, v, indices)
3128
+
3129
+
3130
+ def coo_to_csr(x):
3131
+ """convert coo to csr."""
3132
+ row_indices = x.indices[:, 0]
3133
+ col_indices = x.indices[:, 1]
3134
+ idx_dtype = x.indices.dtype
3135
+ row_indices, sort_idx = F.sort(row_indices.astype(mstype.float32))
3136
+ row_indices = row_indices.astype(idx_dtype)
3137
+ col_indices = col_indices[sort_idx]
3138
+ values = x.values[sort_idx]
3139
+ indptr = F.coo2csr(row_indices, x.shape[0])
3140
+ return CSRTensor(indptr, col_indices, values, x.shape)
3141
+
3142
+
3143
+ def coo_to_dense(x):
3144
+ """convert coo to dense."""
3145
+ zeros_tensor = F.zeros(x.shape, dtype=x.values.dtype)
3146
+ return F.tensor_scatter_update(zeros_tensor, x.indices, x.values)
3147
+
3148
+
3149
+ def coo_coalesce(x):
3150
+ """Returns the coalesced sparse tensor of the input."""
3151
+ shape = const_utils.make_tensor(x.shape)
3152
+ res_indices, res_values, _ = P.Coalesce()(
3153
+ x.indices.transpose(), x.values, shape)
3154
+ return COOTensor(res_indices.transpose(), res_values, x.shape)
3155
+
3156
+
3157
+ def csr_to_coo(x):
3158
+ """convert csr to coo."""
3159
+ if x.ndim != 2:
3160
+ const_utils.raise_value_error(
3161
+ "Currently only support 2-D CSRTensor when converting to COOTensor.")
3162
+ row_indices = F.csr2coo(x.indptr, x.values.shape[0])
3163
+ coo_indices = P.Stack(1)((row_indices, x.indices))
3164
+ return COOTensor(coo_indices, x.values, x.shape)
3165
+
3166
+
3167
+ def csr_to_dense(x):
3168
+ """convert csr to dense."""
3169
+ return F.csr_to_dense(x)
3170
+
3171
+
3172
+ def random_categorical(x, num_sample, seed=0, dtype=mstype.int64):
3173
+ r"""
3174
+ Generates random samples from a given categorical distribution tensor.
3175
+ Refer to :func:`mindspore.ops.random_categorical` for more detail.
3176
+ """
3177
+ validator.check_is_int(num_sample, 'num_sample')
3178
+ validator.check_is_int(seed, 'seed')
3179
+ return F.random_categorical(x, num_sample, seed, dtype)
3180
+
3181
+
3182
+ @constexpr
3183
+ def empty_tensor(dtype):
3184
+ """Return empty tensor"""
3185
+ return Tensor_([], dtype)
3186
+
3187
+
3188
+ @constexpr
3189
+ def get_itemsize(x_type):
3190
+ """get itemsize from tensor's dtype."""
3191
+ return itemsize_map[x_type]
3192
+
3193
+
3194
+ @constexpr(check=False)
3195
+ def check_is_tensor(x):
3196
+ """check whether x is tensor."""
3197
+ if isinstance(x, mstype.TensorType):
3198
+ return True
3199
+ return False
3200
+
3201
+
3202
+ def check_is_const_int(x, op_name, arg_name):
3203
+ """check whether x is const int."""
3204
+ if x is None:
3205
+ raise TypeError(
3206
+ f"For '{op_name}', the '{arg_name}' should be a const int number, but got not const.")
3207
+ if not isinstance(x, int):
3208
+ raise TypeError(
3209
+ f"For '{op_name}', the '{arg_name}' should be a const int number, but got {x}.")
3210
+ return True
3211
+
3212
+
3213
+ @constexpr
3214
+ def const_tensor_to_bool(x):
3215
+ """convert bool tensor to bool condition
3216
+ def const_tensor_to_bool(x):
3217
+ convert bool tensor to bool condition
3218
+ if x.shape == (1,):
3219
+ return bool(x[0])
3220
+ return bool(x)
3221
+ """
3222
+ if x is None:
3223
+ raise ValueError("Only tensor which shape is () or (1,) can be converted to bool, but got None")
3224
+ x = x.asnumpy()
3225
+ if x.shape == ():
3226
+ return bool(x)
3227
+ if x.shape == (1,):
3228
+ return bool(x[0])
3229
+ raise ValueError(
3230
+ f"Only tensor which shape is () or (1,) can be converted to bool, but got tensor shape is {x.shape}")
3231
+
3232
+
3233
+ @_primexpr
3234
+ def check_view_shape(x):
3235
+ """Check view function input shape"""
3236
+ if not x:
3237
+ raise ValueError("The shape variable should not be empty")
3238
+ if isinstance(x[0], tuple):
3239
+ if len(x) != 1:
3240
+ raise ValueError(f"Only one tuple is needed, but got {x}")
3241
+ x = x[0]
3242
+ return x
3243
+
3244
+
3245
+ check_astype_dtype_const = constexpr(validator.check_astype_dtype)
3246
+ max_ = constexpr(validator.max_)
3247
+ min_ = constexpr(validator.min_)
3248
+ expanded_shape = validator.expanded_shape
3249
+ tuple_slice = validator.tuple_slice
3250
+ check_type_support = constexpr(validator.check_type_support)
3251
+ check_type_name = constexpr(validator.check_type_name)
3252
+ check_value_type = constexpr(validator.check_value_type)
3253
+ check_is_int = constexpr(validator.check_is_int)
3254
+ check_bool_type = constexpr(validator.check_bool)
3255
+ check_is_int = constexpr(validator.check_is_int)
3256
+ check_bool = constexpr(validator.check_bool)
3257
+
3258
+
3259
+ @constexpr
3260
+ def empty_compile(dtype, shape):
3261
+ """Returns an empty Tensor."""
3262
+ return Tensor_(dtype, shape)
3263
+
3264
+
3265
+ def tensor_bool(x):
3266
+ """tensor as condition, if is constant, return immediate bool value"""
3267
+ is_cond = F.is_tensor_bool_cond(x)
3268
+ if is_cond and F.isconstant(x):
3269
+ return const_tensor_to_bool(x)
3270
+ return F.cast(x, mstype.bool_)
3271
+
3272
+
3273
+ def and_(x, y):
3274
+ """Implementation of `and` (`&`)."""
3275
+ return x.__and__(y)
3276
+
3277
+
3278
+ def or_(x, y):
3279
+ """Implementation of `or` (`|`)."""
3280
+ return x.__or__(y)
3281
+
3282
+
3283
+ def matmul(x, y):
3284
+ """Implementation of `matmul` (`@`)."""
3285
+ return F.matmul(x, y)
3286
+
3287
+
3288
+ def inner(x, other):
3289
+ """Computes the inner product of 2 tensors."""
3290
+ return F.inner(x, other)
3291
+
3292
+
3293
+ def float_bool(x):
3294
+ """Implementation of `float_bool`."""
3295
+ return x != 0.0
3296
+
3297
+
3298
+ def xdivy(x, y):
3299
+ r"""
3300
+ Divides the first input tensor by the second input tensor element-wise. Returns zero when `x` is zero.
3301
+ """
3302
+ return F.xdivy(x, y)
3303
+
3304
+
3305
+ def int_bool(x):
3306
+ """Implementation of `int_bool`."""
3307
+ return x != 0
3308
+
3309
+
3310
+ def str_bool(x):
3311
+ """Implementation of `str_bool`."""
3312
+ if x == "":
3313
+ return False
3314
+ return True
3315
+
3316
+
3317
+ def matrix_power(input, n):
3318
+ """
3319
+ Raises a square matrix to the (integer) power `n` .
3320
+ """
3321
+ return F.matrix_power(input, n)
3322
+
3323
+
3324
+ def log1p(x):
3325
+ r"""
3326
+ Returns the natural logarithm of one plus the input tensor element-wise.
3327
+ Refer to :func:`mindspore.ops.log1p` for more detail.
3328
+ """
3329
+ return F.log1p(x)
3330
+
3331
+
3332
+ def logit(x, eps=None):
3333
+ r"""
3334
+ Calculate the logit of a tensor element-wise. When eps is not None, element in 'x' is clamped to [eps, 1-eps].
3335
+ When eps is None, input 'x' is not clamped.
3336
+
3337
+ `x` refer to self tensor.
3338
+
3339
+ .. math::
3340
+ \begin{align}
3341
+ y_{i} & = \ln(\frac{z_{i}}{1 - z_{i}}) \\
3342
+ z_{i} & = \begin{cases}
3343
+ x_{i} & \text{if eps is None} \\
3344
+ \text{eps} & \text{if } x_{i} \lt \text{eps} \\
3345
+ x_{i} & \text{if } \text{eps} \leq x_{i} \leq 1 - \text{eps} \\
3346
+ 1 - \text{eps} & \text{if } x_{i} \gt 1 - \text{eps}
3347
+ \end{cases}
3348
+ \end{align}
3349
+ """
3350
+
3351
+ if eps is None:
3352
+ eps = -1.0
3353
+ check_value_type('eps', eps, (float,), 'Tensor.logit')
3354
+ return F.logit(x, eps)
3355
+
3356
+
3357
+ def logdet(x):
3358
+ """Returns the log determinant of one or batches of square matrices."""
3359
+ return F.logdet(x)
3360
+
3361
+
3362
+ def lerp(start, end, weight):
3363
+ """Does a linear interpolation of two tensors start and end based on a float or tensor weight."""
3364
+ return F.lerp(start, end, weight)
3365
+
3366
+
3367
+ # pylint: disable=redefined-builtin
3368
+ def norm(A, ord=None, dim=None, keepdim=False, *, dtype=None):
3369
+ """Returns the matrix norm or vector norm of a given tensor."""
3370
+ return F.norm(A, ord, dim, keepdim, dtype=dtype)
3371
+
3372
+
3373
+ def renorm(input_x, p, dim, maxnorm):
3374
+ """
3375
+ Renormalizes the sub-tensors along dimension `dim`, and each sub-tensor's p-norm should not exceed the
3376
+ 'maxnorm'. The values of current sub-tensor don't need change if the p-norm of the sub-tensor is less than
3377
+ `maxnorm`. Otherwise the sub-tensor needs to be modified to the original value of the corresponding position
3378
+ divided by the p-norm of the substensor and then multiplied by `maxnorm`.
3379
+ """
3380
+ return F.renorm(input_x, p, dim, maxnorm)
3381
+
3382
+
3383
+ def sequence_index(sequence, target, start=None, end=None):
3384
+ """Implementation of `tuple_index`."""
3385
+ if start is None:
3386
+ start = 0
3387
+ if end is None:
3388
+ end = len(sequence)
3389
+ return SequenceIndex()(sequence, target, start, end)
3390
+
3391
+
3392
+ def none_bool(x):
3393
+ """Implementation of `none_bool`."""
3394
+ return False
3395
+
3396
+
3397
+ def func_bool(x):
3398
+ """Implementation of `func_bool`."""
3399
+ return True
3400
+
3401
+
3402
+ def float_floordiv(x, y):
3403
+ """Implementation of `float_floordiv`."""
3404
+ return floor(x / y)
3405
+
3406
+
3407
+ def ceil(x):
3408
+ """
3409
+ Rounds a tensor up to the closest integer element-wise.
3410
+ """
3411
+ return F.ceil(x)
3412
+
3413
+
3414
+ def top_k(input_x, k, sorted=True):
3415
+ """
3416
+ `Tensor.top_k` is deprecated, please use `Tensor.topk` instead.
3417
+ """
3418
+ check_is_int(k, 'k')
3419
+ check_bool(sorted, 'sorted')
3420
+ return F.top_k(input_x, k, sorted)
3421
+
3422
+
3423
+ def topk(input_x, k, dim=None, largest=True, sorted=True):
3424
+ r"""
3425
+ For details, please refer to :func:`mindspore.ops.topk`.
3426
+ """
3427
+ check_is_int(k, 'k')
3428
+ check_bool_type(sorted, 'sorted')
3429
+ return F.topk(input_x, k, dim, largest=largest, sorted=sorted)
3430
+
3431
+
3432
+ def subtract(x, other, *, alpha=1):
3433
+ r"""
3434
+ Computes the element-wise subtraction of input tensors.
3435
+ """
3436
+ return F.sub(x, other * alpha)
3437
+
3438
+
3439
+ def true_divide(divident, divisor):
3440
+ r"""
3441
+ Computes the element-wise division of input tensors.
3442
+ """
3443
+ return F.div(divident, divisor, rounding_mode=None)
3444
+
3445
+
3446
+ # pylint: disable=redefined-outer-name
3447
+ def triu(input, diagonal=0):
3448
+ r"""
3449
+ Returns the triangular matrix based on the diagonal.
3450
+ """
3451
+ return F.triu(input, diagonal)
3452
+
3453
+
3454
+ #############
3455
+ # Iteration #
3456
+ #############
3457
+
3458
+
3459
+ def ms_hasnext(xs):
3460
+ """Whether the input has next element"""
3461
+ return len(xs) > 0
3462
+
3463
+
3464
+ def ms_next(xs):
3465
+ """Get next element and res elements"""
3466
+ return xs[0], xs[1:]
3467
+
3468
+
3469
+ def dict_next(xs):
3470
+ """Next array."""
3471
+ keys = xs.keys()
3472
+ new_keys = F.make_list()
3473
+ new_values = F.make_list()
3474
+ for i in range(1, len(keys)):
3475
+ new_keys.append(keys[i])
3476
+ new_values.append(xs[keys[i]])
3477
+ return keys[0], F.make_dict(new_keys, new_values)
3478
+
3479
+
3480
+ def list_append(self_, list_item):
3481
+ """Append into list"""
3482
+ if F.is_sequence_shape_unknown(self_):
3483
+ return ListAppend()(self_, list_item)
3484
+ return _append(self_, list_item)
3485
+
3486
+
3487
+ def list_insert(self_, index, obj):
3488
+ """Insert into list"""
3489
+ if F.is_sequence_shape_unknown(self_) or not F.isconstant(index):
3490
+ return ListInsert()(self_, index, obj)
3491
+ return _insert(self_, index, obj)
3492
+
3493
+
3494
+ def list_pop(self_, index=-1):
3495
+ """Pop from list"""
3496
+ self_, pop_val = _pop(self_, index)
3497
+ return self_, pop_val
3498
+
3499
+
3500
+ def list_clear(self_):
3501
+ """Clear the list"""
3502
+ return _list_clear(self_)
3503
+
3504
+
3505
+ def list_reverse(self_):
3506
+ """Reverse the obj in list"""
3507
+ return _reverse(self_)
3508
+
3509
+
3510
+ def list_extend(self_, obj):
3511
+ """Append obj to list"""
3512
+ return _extend(self_, obj)
3513
+
3514
+
3515
+ def dict_get(self_, key_index, default_value=None):
3516
+ """Get value by key from dict"""
3517
+ if not _haskey(self_, key_index):
3518
+ return default_value
3519
+ return F.dict_getitem(self_, key_index)
3520
+
3521
+
3522
+ def dict_setitem(self_, key, target):
3523
+ """Dictionary setitem"""
3524
+ return _dict_setitem(self_, key, target)
3525
+
3526
+
3527
+ def dict_clear(self_):
3528
+ """Clear the dict"""
3529
+ return _dict_clear(self_)
3530
+
3531
+
3532
+ def dict_haskey(self_, key_index):
3533
+ """Check if key is in dict"""
3534
+ return _haskey(self_, key_index)
3535
+
3536
+
3537
+ def dict_update(self_, dict_obj):
3538
+ """Update the dict"""
3539
+ return _update(self_, dict_obj)
3540
+
3541
+
3542
+ def dict_fromkeys(self_, seq, value=None):
3543
+ """Check if key is in dict"""
3544
+ return _fromkeys(self_, seq, value)
3545
+
3546
+
3547
+ #################
3548
+ # Array methods #
3549
+ #################
3550
+
3551
+
3552
+ def filter_(fun, iter_):
3553
+ """Support the use of built-in function filter."""
3554
+ result = []
3555
+ for elem in iter_:
3556
+ if fun(elem):
3557
+ result.append(elem)
3558
+ return result
3559
+
3560
+
3561
+ ##################
3562
+ # Sparse methods #
3563
+ ##################
3564
+
3565
+
3566
+ def csr_softmax(logits, dtype):
3567
+ """Implementation of `sum` for CSRTensor."""
3568
+ return F.sparse_matrix_softmax(logits, dtype)
3569
+
3570
+
3571
+ def csr_add(a, b, alpha, beta):
3572
+ """Implementation of "csr_add" for CSRTensor."""
3573
+ return F.csr_add(a, b, alpha, beta)
3574
+
3575
+
3576
+ def csr_astype(x, dtype):
3577
+ """Implementation of `astype` for CSRTensor."""
3578
+ data = x.values.astype(dtype)
3579
+ return F.make_csr_tensor(x.indptr, x.indices, data, x.shape)
3580
+
3581
+
3582
+ def csr_sum(x, axis):
3583
+ """Implementation of `sum` for CSRTensor."""
3584
+ return F.csr_reduce_sum(x, axis)
3585
+
3586
+
3587
+ def csr_abs(x):
3588
+ """Implementation of `abs` for CSRTensor."""
3589
+ data = F.absolute(x.values)
3590
+ return F.make_csr_tensor(x.indptr, x.indices, data, x.shape)
3591
+
3592
+
3593
+ def csr_mv(x, dense_vector):
3594
+ """Implementation of `mv` for CSRTensor."""
3595
+ return F.csr_mv(x, dense_vector)
3596
+
3597
+
3598
+ def csr_mm(x, matrix):
3599
+ """Implementation of `mm` for CSRTensor."""
3600
+ if isinstance(matrix, CSRTensor):
3601
+ return F.csr_mm(x, matrix)
3602
+ return _csr_mm(x.indptr, x.indices, x.values, x.shape, matrix)
3603
+
3604
+
3605
+ def csr_to_tuple(x):
3606
+ """Implementation of `to_tuple` for CSRTensor."""
3607
+ res = (x.indptr, x.indices, x.values, x.shape)
3608
+ return res
3609
+
3610
+
3611
+ def coo_astype(x, dtype):
3612
+ """Implementation of `astype` for COOTensor."""
3613
+ data = x.values.astype(dtype)
3614
+ return F.make_coo_tensor(x.indices, data, x.shape)
3615
+
3616
+
3617
+ def coo_to_tuple(x):
3618
+ """Implementation of `to_tuple` for COOTensor."""
3619
+ return x.indices, x.values, x.shape
3620
+
3621
+
3622
+ def coo_abs(x):
3623
+ """Implementation of `abs` for COOTensor."""
3624
+ data = F.absolute(x.values)
3625
+ return F.make_coo_tensor(x.indices, data, x.shape)
3626
+
3627
+
3628
+ def coo_add(x, y, thresh):
3629
+ """Implementation of `add` for COOTensor."""
3630
+ return F.coo_add(x, y, thresh)
3631
+
3632
+
3633
+ ################
3634
+ # Sparse Attrs #
3635
+ ################
3636
+
3637
+
3638
+ def sparse_size_(x):
3639
+ """
3640
+ Return the size of SparseTensor.values. That is the number of non-zero values in SparseTensor.
3641
+ """
3642
+ return size_(x.values)
3643
+
3644
+
3645
+ def sparse_ndim_(x):
3646
+ """
3647
+ Return the ndim of SparseTensor, according to its dense shape.
3648
+ """
3649
+ return F.tuple_len(x.shape)
3650
+
3651
+
3652
+ def bernoulli(input, p=0.5, seed=None):
3653
+ """
3654
+ Randomly draws binary numbers from a Bernoulli distribution.
3655
+ """
3656
+ return F.bernoulli(input, p, seed)
3657
+
3658
+
3659
+ def gather_nd(input_x, indices):
3660
+ r"""
3661
+ Gathers slices from a tensor by indices.
3662
+ Refer to :func:`mindspore.ops.gather_nd` for more detail.
3663
+ """
3664
+ return F.gather_nd(input_x, indices)
3665
+
3666
+
3667
+ def gather(input_x, input_indices, axis, batch_dims=0):
3668
+ r"""
3669
+ Returns the slice of the input tensor corresponding to the elements of `input_indices` on the specified `axis`.
3670
+ Refer to :func:`mindspore.ops.gather` for more detail.
3671
+ """
3672
+ return F.gather(input_x, input_indices, axis, batch_dims)
3673
+
3674
+
3675
+ def split(tensor, split_size_or_sections, axis=0):
3676
+ """
3677
+ Splits the Tensor into chunks along the given axis.
3678
+ Refer to :func:`mindspore.ops.split` for more detail.
3679
+ """
3680
+ return F.split(tensor, split_size_or_sections, axis)
3681
+
3682
+
3683
+ def tensor_split(input, indices_or_sections, axis=0):
3684
+ """
3685
+ Splits a tensor into multiple sub-tensors along the given axis.
3686
+ Refer to :func:`mindspore.ops.tensor_split` for more detail.
3687
+ """
3688
+ return F.tensor_split(input, indices_or_sections, axis=axis)
3689
+
3690
+
3691
+ def vsplit(input, indices_or_sections):
3692
+ """
3693
+ Splits a tensor into multiple sub-tensors vertically. It is equivalent to `ops.tensor_split` with :math:`axis=0` .
3694
+ Refer to :func:`mindspore.ops.vsplit` for more detail.
3695
+ """
3696
+ return F.vsplit(input, indices_or_sections)
3697
+
3698
+
3699
+ def hsplit(input, indices_or_sections):
3700
+ """
3701
+ Splits a tensor into multiple sub-tensors horizontally. It is equivalent to `ops.tensor_split` with :math:`axis=1` .
3702
+ Refer to :func:`mindspore.ops.hsplit` for more detail.
3703
+ """
3704
+ return F.hsplit(input, indices_or_sections)
3705
+
3706
+
3707
+ def dsplit(input, indices_or_sections):
3708
+ """
3709
+ Splits a tensor into multiple sub-tensors along the 3rd axis.
3710
+ It is equivalent to `ops.tensor_split` with :math:`axis=2` .
3711
+ Refer to :func:`mindspore.ops.tensor_split` for more detail.
3712
+ """
3713
+ return F.dsplit(input, indices_or_sections)
3714
+
3715
+
3716
+ def xlogy(x, y):
3717
+ r"""
3718
+ Computes the first input tensor multiplied by the logarithm of second input tensor element-wise.
3719
+ Refer to :func:`mindspore.ops.xlogy` for more details.
3720
+ """
3721
+ return F.xlogy(x, y)
3722
+
3723
+
3724
+ def eigvals(x):
3725
+ r"""
3726
+ Computes the eigenvalues of a square matrix(batch square matrices).
3727
+ Refer to :func:`mindspore.ops.eigvals` for more detail.
3728
+ """
3729
+ return F.eigvals(x)
3730
+
3731
+
3732
+ def erf(x):
3733
+ r"""
3734
+ Computes the Gauss error function of `x` element-wise.
3735
+ Refer to :func:`mindspore.ops.erf` for more detail.
3736
+ """
3737
+ return F.erf(x)
3738
+
3739
+
3740
+ def erfc(x):
3741
+ r"""
3742
+ Computes the complementary error function of `x` element-wise.
3743
+ Refer to :func:`mindspore.ops.erfc` for more details.
3744
+ """
3745
+ return F.erfc(x)
3746
+
3747
+
3748
+ def isfinite(x):
3749
+ r"""
3750
+ Determines which elements are finite for each position.
3751
+ Refer to :func:`mindspore.ops.isfinite` for more details.
3752
+ """
3753
+ return F.isfinite(x)
3754
+
3755
+
3756
+ def sin(x):
3757
+ r"""
3758
+ For details, please refer to :func:`mindspore.ops.sin`.
3759
+ """
3760
+ return F.sin(x)
3761
+
3762
+
3763
+ def sinc(x):
3764
+ r"""
3765
+ For details, please refer to :func:`mindspore.ops.sinc`.
3766
+ """
3767
+ return F.sinc(x)
3768
+
3769
+
3770
+ def cos(x):
3771
+ r"""
3772
+ Computes cosine of input element-wise.
3773
+ """
3774
+ return F.cos(x)
3775
+
3776
+
3777
+ def count_nonzero(x, axis=(), keep_dims=False, dtype=mstype.int32):
3778
+ r"""
3779
+ For details, please refer to :func:`mindspore.ops.count_nonzero`.
3780
+ """
3781
+ return F.count_nonzero(x, axis, keep_dims, dtype)
3782
+
3783
+
3784
+ def cov(x, *, correction=1, fweights=None, aweights=None):
3785
+ r"""
3786
+ For details, please refer to :func:`mindspore.ops.cov`.
3787
+ """
3788
+ return F.cov(x, correction=correction, fweights=fweights, aweights=aweights)
3789
+
3790
+
3791
+ def acos(x):
3792
+ r"""
3793
+ Computes arccosine of input tensors element-wise.
3794
+ """
3795
+ return F.acos(x)
3796
+
3797
+
3798
+ def asin(x):
3799
+ r"""
3800
+ Computes arcsine of input tensors element-wise.
3801
+ """
3802
+ return F.asin(x)
3803
+
3804
+
3805
+ def acosh(input):
3806
+ r"""
3807
+ Computes inverse hyperbolic cosine of the inputs element-wise.
3808
+ """
3809
+ return F.acosh(input)
3810
+
3811
+
3812
+ def add(input, other):
3813
+ r"""
3814
+ Computes the element-wise addition of input tensors.
3815
+ """
3816
+ return F.add(input, other)
3817
+
3818
+
3819
+ def addr(x, vec1, vec2, beta=1, alpha=1):
3820
+ r"""
3821
+ Computes the outer-product of `vec1` and `vec2` and adds it to `x`.
3822
+ """
3823
+ return F.addr(x, vec1, vec2, beta=beta, alpha=alpha)
3824
+
3825
+
3826
+ def addbmm(x, batch1, batch2, *, beta=1, alpha=1):
3827
+ r"""
3828
+ Performs matrix multiplication with a reduced sum, and add `x` to the result.
3829
+ """
3830
+ return F.addbmm(x, batch1, batch2, beta=beta, alpha=alpha)
3831
+
3832
+
3833
+ def addmm(x, mat1, mat2, *, beta=1, alpha=1):
3834
+ r"""
3835
+ Performs matrix multiplication, and add `x` to the result.
3836
+ """
3837
+ return F.addmm(x, mat1, mat2, beta=beta, alpha=alpha)
3838
+
3839
+
3840
+ def addmm_(self, mat1, mat2, *, beta=1, alpha=1):
3841
+ r"""
3842
+ For details, please refer to :func:`mindspore.ops.addmm`.
3843
+
3844
+ .. note::
3845
+ The output results are directly updated in the Tensor.
3846
+
3847
+ .. warning::
3848
+ This is an experimental API that is subject to change or deletion.
3849
+
3850
+ """
3851
+ return inplace_addmm_op(self, mat1, mat2, beta=beta, alpha=alpha)
3852
+
3853
+
3854
+ def addmv(x, mat, vec, beta=1, alpha=1):
3855
+ r"""
3856
+ Multiplies matrix `mat` and vector `vec`. The vector `x` is added to the final result.
3857
+ """
3858
+ return F.addmv(x, mat, vec, beta=beta, alpha=beta)
3859
+
3860
+
3861
+ def adjoint(x):
3862
+ r"""
3863
+ Computes the conjucated matrix with the last 2 dimensions transposed.
3864
+ """
3865
+ return F.adjoint(x)
3866
+
3867
+
3868
+ def asinh(x):
3869
+ r"""
3870
+ Computes inverse hyperbolic sine of the input element-wise.
3871
+ """
3872
+ return F.asinh(x)
3873
+
3874
+
3875
+ def atan(input):
3876
+ r"""
3877
+ Computes inverse tangent of the input element-wise.
3878
+ """
3879
+ return F.atan(input)
3880
+
3881
+
3882
+ def atanh(x):
3883
+ r"""
3884
+ Computes inverse hyperbolic tangent of the input element-wise.
3885
+ """
3886
+ return F.atanh(x)
3887
+
3888
+
3889
+ def baddbmm(x, batch1, batch2, beta=1, alpha=1):
3890
+ r"""
3891
+ For details, please refer to :func:`mindspore.ops.baddbmm`.
3892
+ """
3893
+ return F.baddbmm(x, batch1, batch2, beta=beta, alpha=alpha)
3894
+
3895
+
3896
+ def bmm(input_x, mat2):
3897
+ r"""
3898
+ Computes matrix multiplication between two tensors by batch.
3899
+ """
3900
+ return F.bmm(input_x, mat2)
3901
+
3902
+
3903
+ def value_(x):
3904
+ r"""
3905
+ Get the value of Parameter or Tensor x. If x is Parameter, will change the type from RefTensor to Tensor.
3906
+ """
3907
+ return P.Load()(x, monad.U)
3908
+
3909
+
3910
+ def to(input_x, dtype):
3911
+ r"""
3912
+ Performs tensor dtype conversion.
3913
+ """
3914
+ return P.Cast()(input_x, dtype)
3915
+
3916
+
3917
+ def to_bool(input_x):
3918
+ r"""
3919
+ Converts input tensor dtype to bool.
3920
+ """
3921
+ return P.Cast()(input_x, mstype.bool_)
3922
+
3923
+
3924
+ def to_float(input_x):
3925
+ r"""
3926
+ Converts input tensor dtype to float32.
3927
+ """
3928
+ return P.Cast()(input_x, mstype.float32)
3929
+
3930
+
3931
+ def to_half(input_x):
3932
+ r"""
3933
+ Converts input tensor dtype to float16.
3934
+ """
3935
+ return P.Cast()(input_x, mstype.float16)
3936
+
3937
+
3938
+ def to_int(input_x):
3939
+ r"""
3940
+ Converts input tensor dtype to int32.
3941
+ """
3942
+ return P.Cast()(input_x, mstype.int32)
3943
+
3944
+
3945
+ def to_long(input_x):
3946
+ r"""
3947
+ Converts input tensor dtype to int64.
3948
+ """
3949
+ return P.Cast()(input_x, mstype.int64)
3950
+
3951
+
3952
+ def cholesky(input_x, upper=False):
3953
+ r"""
3954
+ Computes the Cholesky decomposition of a symmetric positive-definite matrix
3955
+ """
3956
+ return F.cholesky(input_x, upper=upper)
3957
+
3958
+
3959
+ def cholesky_inverse(input_x, upper=False):
3960
+ r"""
3961
+ Computes the inverse of the positive definite matrix using cholesky matrix factorization.
3962
+ """
3963
+ return F.cholesky_inverse(input_x, upper=upper)
3964
+
3965
+
3966
+ def cholesky_solve(input, input2, upper=False):
3967
+ r"""
3968
+ Computes the solution of a set of linear equations with a positive definite matrix,
3969
+ according to its Cholesky decomposition factor `input2` .
3970
+ """
3971
+ return F.cholesky_solve(input, input2, upper=upper)
3972
+
3973
+
3974
+ def map_tensor_get(map_tensor, key_tensor, insert_default_value=True):
3975
+ r"""
3976
+ Get or create value according the key tensor from a map tensor.
3977
+ """
3978
+ return _map_tensor_ops.MapTensorGet(insert_default_value)(map_tensor, key_tensor)
3979
+
3980
+
3981
+ def map_tensor_put(map_tensor, key_tensor, value_tensor):
3982
+ r"""
3983
+ Insert or update key value tensor pairs to a map tensor.
3984
+ """
3985
+ return _map_tensor_ops.put(map_tensor, key_tensor, value_tensor)
3986
+
3987
+
3988
+ def map_tensor_erase(map_tensor, key_tensor):
3989
+ r"""
3990
+ Remove records according the key tensor from a map tensor.
3991
+ """
3992
+ return _map_tensor_ops.erase(map_tensor, key_tensor)
3993
+
3994
+
3995
+ def map_tensor_get_keys(map_tensor):
3996
+ r"""
3997
+ Get all keys as a tensor.
3998
+ """
3999
+ return _map_tensor_ops.get_keys(map_tensor)
4000
+
4001
+
4002
+ def map_tensor_get_values(map_tensor):
4003
+ r"""
4004
+ Get all values as a tensor.
4005
+ """
4006
+ return _map_tensor_ops.get_values(map_tensor)
4007
+
4008
+
4009
+ def map_tensor_get_data(map_tensor):
4010
+ r"""
4011
+ Get all keys and values as a tensor.
4012
+ """
4013
+ return _map_tensor_ops.get_data(map_tensor)
4014
+
4015
+
4016
+ def conj(input):
4017
+ r"""
4018
+ Computes complex conjugate of the input element-wise.
4019
+ """
4020
+ return F.conj(input)
4021
+
4022
+
4023
+ def cross(input, other, dim=None):
4024
+ r"""
4025
+ Computes the cross product of input vectors in specified dimension.
4026
+ """
4027
+ return F.cross(input, other, dim)
4028
+
4029
+
4030
+ def erfinv(input):
4031
+ r"""
4032
+ Computes the inverse error function of input tensor.
4033
+ """
4034
+ return F.erfinv(input)
4035
+
4036
+
4037
+ def less_equal(input, other):
4038
+ r"""
4039
+ Computes the boolean value of :math:`input\_x <= other` element-wise.
4040
+ """
4041
+ return F.less_equal(input, other)
4042
+
4043
+
4044
+ def lcm(x, other):
4045
+ r"""
4046
+ Computes least common multiplier of input tensors element-wise.
4047
+ """
4048
+ return F.lcm(x, other)
4049
+
4050
+
4051
+ def ldexp(x, other):
4052
+ r"""
4053
+ Multiplies input by 2**:attr:other.
4054
+ """
4055
+ return F.ldexp(x, other)
4056
+
4057
+
4058
+ def fold(input, output_size, kernel_size, dilation=1, padding=0, stride=1):
4059
+ r"""
4060
+ Combines an array of sliding local blocks into a large containing tensor.
4061
+ """
4062
+ return F.fold(input, output_size, kernel_size, dilation, padding, stride)
4063
+
4064
+
4065
+ def unfold(input, kernel_size, dilation=1, padding=0, stride=1):
4066
+ r"""
4067
+ Extracts sliding local blocks from a batched input tensor.
4068
+ """
4069
+ return F.unfold(input, kernel_size, dilation, padding, stride)
4070
+
4071
+
4072
+ def expand(input, size):
4073
+ r"""
4074
+ Returns a new view of the self tensor with singleton dimensions expanded to a larger size.
4075
+ """
4076
+ size = TensorToTuple()(size)
4077
+ return F.broadcast_to(input, size)
4078
+
4079
+
4080
+ def cumprod(input, dim, dtype=None):
4081
+ r"""
4082
+ Computes the cumulative product of the `input` tensor along dimension `dim`.
4083
+ """
4084
+ return F.cumprod(input, dim, dtype)
4085
+
4086
+
4087
+ def multiply(input, other):
4088
+ """For details, please refer to :func:`mindspore.ops.multiply`."""
4089
+ return F.multiply(input, other)
4090
+
4091
+
4092
+ def div(input, value, *, rounding_mode=None):
4093
+ r"""
4094
+ Divides the tensor `input` by the given input tensor `value` in floating-point type element-wise.
4095
+ """
4096
+ return F.div(input, value, rounding_mode=rounding_mode)
4097
+
4098
+
4099
+ def eq(input, other):
4100
+ r"""
4101
+ Computes the equivalence between the tensor `input` and the given input tensor `other` element-wise.
4102
+ """
4103
+ return F.equal(input, other)
4104
+
4105
+
4106
+ def equal(x, y):
4107
+ r"""
4108
+ Computes the equivalence between the tensor `x` and the given input tensor `y` element-wise.
4109
+ """
4110
+ return F.equal(x, y)
4111
+
4112
+
4113
+ def expm1(input_x):
4114
+ r"""
4115
+ Computes exponential then minus 1 of a tensor element-wise.
4116
+ """
4117
+ return F.expm1(input_x)
4118
+
4119
+
4120
+ @constexpr
4121
+ def _check_index_add_alpha(alpha):
4122
+ check_is_number(alpha, (int, float))
4123
+
4124
+
4125
+ def index_add(input, dim, index, source, *, alpha=1):
4126
+ r"""
4127
+ Adds tensor `alpha` times `source` to specified `dim` and `index` of input tensor.
4128
+ """
4129
+ _check_index_add_alpha(alpha)
4130
+ source = source * alpha
4131
+ return F.index_add(input, indices=index, y=source, axis=dim)
4132
+
4133
+
4134
+ def greater(input, other):
4135
+ r"""
4136
+ Computes the boolean value of :math:`input > other` element-wise.
4137
+ """
4138
+ return F.greater(input, other)
4139
+
4140
+
4141
+ def greater_equal(input, other):
4142
+ r"""
4143
+ Computes the boolean value of :math:`input >= other` element-wise.
4144
+ """
4145
+ return F.greater_equal(input, other)
4146
+
4147
+
4148
+ def igamma(input, other):
4149
+ r"""
4150
+ Computes lower regularized incomplete Gamma function.
4151
+ """
4152
+ return F.igamma(input, other)
4153
+
4154
+
4155
+ def igammac(input, other):
4156
+ r"""
4157
+ Computes upper regularized incomplete Gamma function.
4158
+ """
4159
+ return F.igammac(input, other)
4160
+
4161
+
4162
+ def isinf(input):
4163
+ r"""
4164
+ Determines which elements are inf or -inf for each position.
4165
+ """
4166
+ return F.isinf(input)
4167
+
4168
+
4169
+ def isnan(input):
4170
+ r"""
4171
+ Determines which elements are NaN for each position.
4172
+ """
4173
+ return F.isnan(input)
4174
+
4175
+
4176
+ def le(input, other):
4177
+ r"""
4178
+ Computes the boolean value of :math:`input <= other` element-wise.
4179
+ """
4180
+ return F.le(input, other)
4181
+
4182
+
4183
+ def less(input, other):
4184
+ r"""
4185
+ Computes the boolean value of :math:`input < other` element-wise.
4186
+ """
4187
+ return F.less(input, other)
4188
+
4189
+
4190
+ def logical_and(input, other):
4191
+ r"""
4192
+ Computes the "logical AND" of two tensors element-wise.
4193
+ """
4194
+ return F.logical_and(input, other)
4195
+
4196
+
4197
+ def logical_not(input):
4198
+ r"""
4199
+ Computes the "logical NOT" of input tensor element-wise.
4200
+ """
4201
+ return F.logical_not(input)
4202
+
4203
+
4204
+ def logical_or(input, other):
4205
+ r"""
4206
+ Computes the "logical OR" of two tensors element-wise.
4207
+ """
4208
+ return F.logical_or(input, other)
4209
+
4210
+
4211
+ def logical_xor(input, other):
4212
+ r"""
4213
+ Computes the "logical XOR" of two tensors element-wise.
4214
+ """
4215
+ return F.logical_xor(input, other)
4216
+
4217
+
4218
+ def lstsq(input, A):
4219
+ r"""
4220
+ Computes the solutions of the least squares and minimum norm problems of full-rank
4221
+ matrix `input` of size :math:`(m \times n)` and matrix `A` of size :math:`(m \times k)`.
4222
+ """
4223
+ return F.lstsq(input, A)
4224
+
4225
+
4226
+ def mvlgamma(input, p):
4227
+ r"""
4228
+ Computes the multivariate log-gamma function with dimension p element-wise.
4229
+ """
4230
+ return F.mvlgamma(input, p)
4231
+
4232
+
4233
+ def maximum(input, other):
4234
+ r"""
4235
+ Computes the maximum of input tensors element-wise.
4236
+ """
4237
+ return F.maximum(input, other)
4238
+
4239
+
4240
+ def mul(input, other):
4241
+ r"""
4242
+ Multiplies two tensors element-wise.
4243
+ """
4244
+ return F.mul(input, other)
4245
+
4246
+
4247
+ def neg(input):
4248
+ r"""
4249
+ Returns a tensor with negative values of the input tensor element-wise.
4250
+ """
4251
+ return F.neg(input)
4252
+
4253
+
4254
+ def ne(input, other):
4255
+ r"""
4256
+ Computes the non-equivalence of two tensors element-wise.
4257
+ """
4258
+ return F.ne(input, other)
4259
+
4260
+
4261
+ def not_equal(x, other):
4262
+ r"""
4263
+ Computes the non-equivalence of two tensors element-wise.
4264
+ """
4265
+ return F.not_equal(x, other)
4266
+
4267
+
4268
+ def sign(x):
4269
+ r"""
4270
+ For details, please refer to :func:`mindspore.ops.sign`.
4271
+ """
4272
+ return F.sign(x)
4273
+
4274
+
4275
+ def signbit(x):
4276
+ """
4277
+ For details, please refer to :func:`mindspore.ops.signbit`.
4278
+ """
4279
+ return F.signbit(x)
4280
+
4281
+
4282
+ def sgn(x):
4283
+ """
4284
+ For details, please refer to :func:`mindspore.ops.sgn`.
4285
+ """
4286
+ return F.sgn(x)
4287
+
4288
+
4289
+ def sinh(input):
4290
+ r"""
4291
+ Computes hyperbolic sine of the input element-wise.
4292
+ """
4293
+ return F.sinh(input)
4294
+
4295
+
4296
+ def sort(input, axis=-1, descending=False):
4297
+ r"""
4298
+ Sorts the elements of the input tensor along a given dimension in ascending order by value.
4299
+ """
4300
+ return F.sort(input, axis=axis, descending=descending)
4301
+
4302
+
4303
+ def argsort(input, axis=-1, descending=False):
4304
+ """For details, please refer to :func:`mindspore.ops.argsort`."""
4305
+ return F.argsort(input, axis, descending)
4306
+
4307
+
4308
+ def trunc(input):
4309
+ r"""
4310
+ Returns a new tensor with the truncated integer values of the elements of input.
4311
+ """
4312
+ return F.trunc(input)
4313
+
4314
+
4315
+ def where(x, condition, y):
4316
+ r"""
4317
+ Returns a tensor whose elements are selected from either `x` or `y` depending on `condition`.
4318
+ Please refer to :func:`mindspore.ops.where`.
4319
+ """
4320
+ return F.where(condition, x, y)
4321
+
4322
+
4323
+ def imag(input):
4324
+ r"""
4325
+ Returns a new tensor containing imaginary value of the input.
4326
+ """
4327
+ return F.imag(input)
4328
+
4329
+
4330
+ def diff(x, n=1, axis=-1, prepend=None, append=None):
4331
+ r"""
4332
+ For details, please refer to :func:`mindspore.ops.diff`.
4333
+ """
4334
+ return F.diff(x, n, axis, prepend, append)
4335
+
4336
+
4337
+ def frac(x):
4338
+ r"""
4339
+ For details, please refer to :func:`mindspore.ops.frac`.
4340
+ """
4341
+ return F.frac(x)
4342
+
4343
+
4344
+ def argwhere(input):
4345
+ r"""
4346
+ For details, please refer to :func:`mindspore.ops.argwhere`.
4347
+ """
4348
+ return F.argwhere(input)
4349
+
4350
+
4351
+ def moveaxis(input, source, destination):
4352
+ r"""
4353
+ For details, please refer to :func:`mindspore.ops.moveaxis`.
4354
+ """
4355
+ return F.moveaxis(input, source, destination)
4356
+
4357
+
4358
+ def movedim(input, source, destination):
4359
+ r"""
4360
+ For details, please refer to :func:`mindspore.ops.movedim`.
4361
+ """
4362
+ return F.movedim(input, source, destination)
4363
+
4364
+
4365
+ def nextafter(input, other):
4366
+ r"""
4367
+ For details, please refer to :func:`mindspore.ops.nextafter`.
4368
+ """
4369
+ return F.nextafter(input, other)
4370
+
4371
+
4372
+ def qr(input, some=True):
4373
+ r"""
4374
+ For details, please refer to :func:`mindspore.ops.qr`.
4375
+ """
4376
+ check_bool_type(some, 'some', 'Tensor.qr')
4377
+ return F.qr(input, 'reduced' if some else 'complete')
4378
+
4379
+
4380
+ def ormqr(input, input2, input3, left=True, transpose=False):
4381
+ r"""
4382
+ For details, please refer to :func:`mindspore.ops.ormqr`.
4383
+ """
4384
+ return F.ormqr(input, input2, input3, left, transpose)
4385
+
4386
+
4387
+ def amax(input, axis=None, keep_dims=False):
4388
+ r"""
4389
+ For details, please refer to :func:`mindspore.ops.amax`.
4390
+ """
4391
+ return F.amax(input, axis, keep_dims)
4392
+
4393
+
4394
+ def uniform(input, from_=0., to=1., generator=None):
4395
+ r"""
4396
+ Generates random numbers in the half-open interval [from_, to).
4397
+ """
4398
+ return F.uniform_ext(input, from_, to, generator)
4399
+
4400
+
4401
+ def amin(input, axis=None, keep_dims=False):
4402
+ r"""
4403
+ For details, please refer to :func:`mindspore.ops.amin`.
4404
+ """
4405
+ return F.amin(input, axis, keep_dims)
4406
+
4407
+
4408
+ def lu_solve(b, LU_data, LU_pivots):
4409
+ r"""
4410
+ For details, please refer to :func:`mindspore.Tensor.lu_solve`
4411
+ """
4412
+ return F.lu_solve(b, LU_data, LU_pivots)
4413
+
4414
+
4415
+ def masked_scatter(input, mask, tensor):
4416
+ r"""
4417
+ For details, please refer to :func:`mindspore.Tensor.masked_scatter`
4418
+ """
4419
+ return array_ops.MaskedScatter()(input, mask, tensor)
4420
+
4421
+
4422
+ def index_put(input, indices, values, accumulate=False):
4423
+ r"""
4424
+ For details, please refer to :func:`mindspore.Tensor.index_put`
4425
+ """
4426
+ check_bool_type(accumulate, 'accumulate', 'Tensor.index_put')
4427
+ _index_put = array_ops.IndexPut(0 if accumulate is False else 1)
4428
+ return _index_put(input, values, indices)
4429
+
4430
+
4431
+ def aminmax(input, *, axis=0, keepdims=False):
4432
+ r"""
4433
+ For details, please refer to :func:`mindspore.ops.aminmax`.
4434
+ """
4435
+ return F.aminmax(input, axis=axis, keepdims=keepdims)
4436
+
4437
+
4438
+ def quantile(input, q, axis=None, keepdims=False):
4439
+ r"""
4440
+ For details, please refer to :func:`mindspore.ops.quantile`.
4441
+ """
4442
+ return F.quantile(input, q, axis, keepdims)
4443
+
4444
+
4445
+ def nanquantile(input, q, axis=None, keepdims=False):
4446
+ r"""
4447
+ For details, please refer to :func:`mindspore.ops.nanquantile`.
4448
+ """
4449
+ return F.nanquantile(input, q, axis, keepdims)
4450
+
4451
+
4452
+ def orgqr(input, input2):
4453
+ r"""
4454
+ For details, please refer to :func:`mindspore.ops.orgqr`.
4455
+ """
4456
+ return F.orgqr(input, input2)
4457
+
4458
+
4459
+ def outer(input, vec2):
4460
+ r"""
4461
+ For details, please refer to :func:`mindspore.ops.vec2`.
4462
+ """
4463
+ return F.outer(input, vec2)
4464
+
4465
+ def sigmoid(input):
4466
+ r"""
4467
+ For details, please refer to :func:`mindspore.ops.sigmoid`.
4468
+ """
4469
+ return F.sigmoid(input)
4470
+
4471
+ def _getitem(data, index):
4472
+ return multitype_ops.getitem(data, index)
4473
+
4474
+ def _setitem(data, index, value):
4475
+ return multitype_ops.setitem(data, index, value)