mindspore 2.3.0__cp310-cp310-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1400) hide show
  1. mindspore/.commit_id +1 -0
  2. mindspore/ConcurrencyCheck.dll +0 -0
  3. mindspore/CppBuildInsights.dll +0 -0
  4. mindspore/CppCoreCheck.dll +0 -0
  5. mindspore/EnumIndex.dll +0 -0
  6. mindspore/EspXEngine.dll +0 -0
  7. mindspore/HResultCheck.dll +0 -0
  8. mindspore/KernelTraceControl.dll +0 -0
  9. mindspore/LocalESPC.dll +0 -0
  10. mindspore/Microsoft.Diagnostics.Tracing.EventSource.dll +0 -0
  11. mindspore/Microsoft.VisualStudio.RemoteControl.dll +0 -0
  12. mindspore/Microsoft.VisualStudio.Telemetry.dll +0 -0
  13. mindspore/Microsoft.VisualStudio.Utilities.Internal.dll +0 -0
  14. mindspore/Newtonsoft.Json.dll +0 -0
  15. mindspore/System.Runtime.CompilerServices.Unsafe.dll +0 -0
  16. mindspore/VariantClear.dll +0 -0
  17. mindspore/__init__.py +51 -0
  18. mindspore/_c_dataengine.cp310-win_amd64.pyd +0 -0
  19. mindspore/_c_expression.cp310-win_amd64.pyd +0 -0
  20. mindspore/_c_mindrecord.cp310-win_amd64.pyd +0 -0
  21. mindspore/_check_jit_forbidden_api.py +106 -0
  22. mindspore/_checkparam.py +1378 -0
  23. mindspore/_extends/__init__.py +23 -0
  24. mindspore/_extends/builtin_operations.py +224 -0
  25. mindspore/_extends/graph_kernel/__init__.py +17 -0
  26. mindspore/_extends/graph_kernel/model/__init__.py +19 -0
  27. mindspore/_extends/graph_kernel/model/graph_parallel.py +311 -0
  28. mindspore/_extends/graph_kernel/model/graph_split.py +1348 -0
  29. mindspore/_extends/graph_kernel/model/model.py +553 -0
  30. mindspore/_extends/graph_kernel/model/model_builder.py +216 -0
  31. mindspore/_extends/graph_kernel/parallel_estimate.py +60 -0
  32. mindspore/_extends/graph_kernel/splitter.py +140 -0
  33. mindspore/_extends/graph_kernel/utils.py +28 -0
  34. mindspore/_extends/parallel_compile/__init__.py +19 -0
  35. mindspore/_extends/parallel_compile/akg_compiler/__init__.py +19 -0
  36. mindspore/_extends/parallel_compile/akg_compiler/akg_process.py +269 -0
  37. mindspore/_extends/parallel_compile/akg_compiler/build_tbe_kernel.py +529 -0
  38. mindspore/_extends/parallel_compile/akg_compiler/compiler.py +56 -0
  39. mindspore/_extends/parallel_compile/akg_compiler/gen_custom_op_files.py +96 -0
  40. mindspore/_extends/parallel_compile/akg_compiler/get_file_path.py +36 -0
  41. mindspore/_extends/parallel_compile/akg_compiler/tbe_topi.py +556 -0
  42. mindspore/_extends/parallel_compile/akg_compiler/util.py +159 -0
  43. mindspore/_extends/parse/__init__.py +49 -0
  44. mindspore/_extends/parse/compile_config.py +258 -0
  45. mindspore/_extends/parse/namespace.py +136 -0
  46. mindspore/_extends/parse/parser.py +1446 -0
  47. mindspore/_extends/parse/resources.py +213 -0
  48. mindspore/_extends/parse/standard_method.py +4437 -0
  49. mindspore/_extends/parse/trope.py +97 -0
  50. mindspore/_extends/pijit/__init__.py +23 -0
  51. mindspore/_extends/pijit/pijit_func_white_list.py +343 -0
  52. mindspore/_extends/remote/__init__.py +19 -0
  53. mindspore/_extends/remote/kernel_build_server.py +199 -0
  54. mindspore/_extends/remote/kernel_build_server_akg.py +55 -0
  55. mindspore/_extends/remote/kernel_build_server_akg_v2.py +55 -0
  56. mindspore/_extends/remote/kernel_build_server_ascend.py +75 -0
  57. mindspore/_extends/utils.py +68 -0
  58. mindspore/_install_custom.py +43 -0
  59. mindspore/_profiler.py +30 -0
  60. mindspore/amp.py +419 -0
  61. mindspore/atlprov.dll +0 -0
  62. mindspore/avcodec-59.dll +0 -0
  63. mindspore/avdevice-59.dll +0 -0
  64. mindspore/avfilter-8.dll +0 -0
  65. mindspore/avformat-59.dll +0 -0
  66. mindspore/avutil-57.dll +0 -0
  67. mindspore/boost/__init__.py +42 -0
  68. mindspore/boost/adasum.py +319 -0
  69. mindspore/boost/base.py +535 -0
  70. mindspore/boost/boost.py +400 -0
  71. mindspore/boost/boost_cell_wrapper.py +790 -0
  72. mindspore/boost/dim_reduce.py +323 -0
  73. mindspore/boost/grad_accumulation.py +79 -0
  74. mindspore/boost/grad_freeze.py +382 -0
  75. mindspore/boost/group_loss_scale_manager.py +166 -0
  76. mindspore/boost/less_batch_normalization.py +174 -0
  77. mindspore/c1.dll +0 -0
  78. mindspore/c1xx.dll +0 -0
  79. mindspore/c2.dll +0 -0
  80. mindspore/cfgpersist.dll +0 -0
  81. mindspore/clang_rt.asan_dbg_dynamic-x86_64.dll +0 -0
  82. mindspore/clang_rt.asan_dynamic-x86_64.dll +0 -0
  83. mindspore/common/__init__.py +84 -0
  84. mindspore/common/_auto_dynamic.py +68 -0
  85. mindspore/common/_decorator.py +50 -0
  86. mindspore/common/_jit_fallback_utils.py +110 -0
  87. mindspore/common/_monad.py +25 -0
  88. mindspore/common/_register_for_adapter.py +74 -0
  89. mindspore/common/_register_for_recompute.py +48 -0
  90. mindspore/common/_register_for_tensor.py +45 -0
  91. mindspore/common/_stub_tensor.py +210 -0
  92. mindspore/common/_utils.py +122 -0
  93. mindspore/common/api.py +2049 -0
  94. mindspore/common/auto_dynamic_shape.py +507 -0
  95. mindspore/common/dtype.py +422 -0
  96. mindspore/common/dump.py +131 -0
  97. mindspore/common/file_system.py +48 -0
  98. mindspore/common/generator.py +260 -0
  99. mindspore/common/hook_handle.py +155 -0
  100. mindspore/common/initializer.py +880 -0
  101. mindspore/common/jit_config.py +98 -0
  102. mindspore/common/lazy_inline.py +240 -0
  103. mindspore/common/mindir_util.py +111 -0
  104. mindspore/common/mutable.py +234 -0
  105. mindspore/common/no_inline.py +54 -0
  106. mindspore/common/np_dtype.py +25 -0
  107. mindspore/common/parameter.py +1048 -0
  108. mindspore/common/recompute.py +262 -0
  109. mindspore/common/seed.py +260 -0
  110. mindspore/common/sparse_tensor.py +1171 -0
  111. mindspore/common/symbol.py +122 -0
  112. mindspore/common/tensor.py +4859 -0
  113. mindspore/communication/__init__.py +37 -0
  114. mindspore/communication/_comm_helper.py +466 -0
  115. mindspore/communication/_hccl_management.py +297 -0
  116. mindspore/communication/comm_func.py +1140 -0
  117. mindspore/communication/management.py +673 -0
  118. mindspore/config/op_info.config +533 -0
  119. mindspore/context.py +1976 -0
  120. mindspore/d3dcompiler_47.dll +0 -0
  121. mindspore/dataset/__init__.py +90 -0
  122. mindspore/dataset/audio/__init__.py +61 -0
  123. mindspore/dataset/audio/transforms.py +3690 -0
  124. mindspore/dataset/audio/utils.py +386 -0
  125. mindspore/dataset/audio/validators.py +1172 -0
  126. mindspore/dataset/callback/__init__.py +20 -0
  127. mindspore/dataset/callback/ds_callback.py +368 -0
  128. mindspore/dataset/callback/validators.py +32 -0
  129. mindspore/dataset/core/__init__.py +13 -0
  130. mindspore/dataset/core/config.py +1088 -0
  131. mindspore/dataset/core/datatypes.py +101 -0
  132. mindspore/dataset/core/py_util_helpers.py +65 -0
  133. mindspore/dataset/core/validator_helpers.py +774 -0
  134. mindspore/dataset/debug/__init__.py +21 -0
  135. mindspore/dataset/debug/debug_hook.py +97 -0
  136. mindspore/dataset/debug/pre_defined_hook.py +67 -0
  137. mindspore/dataset/engine/__init__.py +124 -0
  138. mindspore/dataset/engine/cache_admin.py +47 -0
  139. mindspore/dataset/engine/cache_client.py +129 -0
  140. mindspore/dataset/engine/datasets.py +4554 -0
  141. mindspore/dataset/engine/datasets_audio.py +911 -0
  142. mindspore/dataset/engine/datasets_standard_format.py +493 -0
  143. mindspore/dataset/engine/datasets_text.py +2161 -0
  144. mindspore/dataset/engine/datasets_user_defined.py +1114 -0
  145. mindspore/dataset/engine/datasets_vision.py +4816 -0
  146. mindspore/dataset/engine/iterators.py +342 -0
  147. mindspore/dataset/engine/obs/__init__.py +23 -0
  148. mindspore/dataset/engine/obs/config_loader.py +68 -0
  149. mindspore/dataset/engine/obs/obs_mindrecord_dataset.py +508 -0
  150. mindspore/dataset/engine/obs/util.py +475 -0
  151. mindspore/dataset/engine/offload.py +596 -0
  152. mindspore/dataset/engine/queue.py +250 -0
  153. mindspore/dataset/engine/samplers.py +895 -0
  154. mindspore/dataset/engine/serializer_deserializer.py +159 -0
  155. mindspore/dataset/engine/validators.py +2875 -0
  156. mindspore/dataset/text/__init__.py +54 -0
  157. mindspore/dataset/text/transforms.py +1703 -0
  158. mindspore/dataset/text/utils.py +715 -0
  159. mindspore/dataset/text/validators.py +642 -0
  160. mindspore/dataset/transforms/__init__.py +48 -0
  161. mindspore/dataset/transforms/c_transforms.py +638 -0
  162. mindspore/dataset/transforms/py_transforms.py +393 -0
  163. mindspore/dataset/transforms/py_transforms_util.py +255 -0
  164. mindspore/dataset/transforms/transforms.py +1260 -0
  165. mindspore/dataset/transforms/validators.py +410 -0
  166. mindspore/dataset/utils/__init__.py +19 -0
  167. mindspore/dataset/utils/browse_dataset.py +190 -0
  168. mindspore/dataset/utils/line_reader.py +124 -0
  169. mindspore/dataset/vision/__init__.py +68 -0
  170. mindspore/dataset/vision/c_transforms.py +2641 -0
  171. mindspore/dataset/vision/py_transforms.py +2120 -0
  172. mindspore/dataset/vision/py_transforms_util.py +1660 -0
  173. mindspore/dataset/vision/transforms.py +7295 -0
  174. mindspore/dataset/vision/utils.py +863 -0
  175. mindspore/dataset/vision/validators.py +1482 -0
  176. mindspore/default_config.py +2 -0
  177. mindspore/dnnl.dll +0 -0
  178. mindspore/dpcmi.dll +0 -0
  179. mindspore/experimental/__init__.py +20 -0
  180. mindspore/experimental/map_parameter.py +309 -0
  181. mindspore/experimental/optim/__init__.py +40 -0
  182. mindspore/experimental/optim/adadelta.py +161 -0
  183. mindspore/experimental/optim/adagrad.py +168 -0
  184. mindspore/experimental/optim/adam.py +193 -0
  185. mindspore/experimental/optim/adamax.py +170 -0
  186. mindspore/experimental/optim/adamw.py +205 -0
  187. mindspore/experimental/optim/asgd.py +153 -0
  188. mindspore/experimental/optim/lr_scheduler.py +1371 -0
  189. mindspore/experimental/optim/nadam.py +157 -0
  190. mindspore/experimental/optim/optimizer.py +259 -0
  191. mindspore/experimental/optim/radam.py +194 -0
  192. mindspore/experimental/optim/rmsprop.py +154 -0
  193. mindspore/experimental/optim/rprop.py +164 -0
  194. mindspore/experimental/optim/sgd.py +156 -0
  195. mindspore/hal/__init__.py +40 -0
  196. mindspore/hal/_ascend.py +57 -0
  197. mindspore/hal/_base.py +57 -0
  198. mindspore/hal/_cpu.py +56 -0
  199. mindspore/hal/_gpu.py +57 -0
  200. mindspore/hal/device.py +356 -0
  201. mindspore/hal/event.py +179 -0
  202. mindspore/hal/memory.py +326 -0
  203. mindspore/hal/stream.py +339 -0
  204. mindspore/include/OWNERS +7 -0
  205. mindspore/include/api/allocator.h +97 -0
  206. mindspore/include/api/callback/callback.h +93 -0
  207. mindspore/include/api/callback/ckpt_saver.h +41 -0
  208. mindspore/include/api/callback/loss_monitor.h +33 -0
  209. mindspore/include/api/callback/lr_scheduler.h +51 -0
  210. mindspore/include/api/callback/time_monitor.h +34 -0
  211. mindspore/include/api/callback/train_accuracy.h +37 -0
  212. mindspore/include/api/cell.h +90 -0
  213. mindspore/include/api/cfg.h +82 -0
  214. mindspore/include/api/context.h +602 -0
  215. mindspore/include/api/data_type.h +47 -0
  216. mindspore/include/api/delegate.h +178 -0
  217. mindspore/include/api/delegate_api.h +75 -0
  218. mindspore/include/api/dual_abi_helper.h +208 -0
  219. mindspore/include/api/format.h +28 -0
  220. mindspore/include/api/graph.h +46 -0
  221. mindspore/include/api/kernel.h +58 -0
  222. mindspore/include/api/kernel_api.h +168 -0
  223. mindspore/include/api/metrics/accuracy.h +36 -0
  224. mindspore/include/api/metrics/metrics.h +41 -0
  225. mindspore/include/api/model.h +438 -0
  226. mindspore/include/api/model_group.h +79 -0
  227. mindspore/include/api/model_parallel_runner.h +168 -0
  228. mindspore/include/api/serialization.h +185 -0
  229. mindspore/include/api/status.h +192 -0
  230. mindspore/include/api/types.h +431 -0
  231. mindspore/include/api/visible.h +41 -0
  232. mindspore/include/c_api/context_c.h +179 -0
  233. mindspore/include/c_api/data_type_c.h +52 -0
  234. mindspore/include/c_api/format_c.h +46 -0
  235. mindspore/include/c_api/model_c.h +347 -0
  236. mindspore/include/c_api/ms/abstract.h +67 -0
  237. mindspore/include/c_api/ms/attribute.h +197 -0
  238. mindspore/include/c_api/ms/base/handle_types.h +43 -0
  239. mindspore/include/c_api/ms/base/macros.h +32 -0
  240. mindspore/include/c_api/ms/base/status.h +33 -0
  241. mindspore/include/c_api/ms/base/types.h +283 -0
  242. mindspore/include/c_api/ms/context.h +102 -0
  243. mindspore/include/c_api/ms/graph.h +160 -0
  244. mindspore/include/c_api/ms/node.h +606 -0
  245. mindspore/include/c_api/ms/tensor.h +161 -0
  246. mindspore/include/c_api/ms/value.h +84 -0
  247. mindspore/include/c_api/status_c.h +79 -0
  248. mindspore/include/c_api/tensor_c.h +146 -0
  249. mindspore/include/c_api/types_c.h +67 -0
  250. mindspore/include/dataset/config.h +163 -0
  251. mindspore/include/dataset/constants.h +363 -0
  252. mindspore/include/dataset/execute.h +196 -0
  253. mindspore/include/dataset/text.h +1092 -0
  254. mindspore/include/dataset/transforms.h +638 -0
  255. mindspore/include/dataset/vision.h +2125 -0
  256. mindspore/include/dataset/vision_ascend.h +206 -0
  257. mindspore/include/dataset/vision_lite.h +625 -0
  258. mindspore/jpeg62.dll +0 -0
  259. mindspore/log.py +633 -0
  260. mindspore/mindrecord/__init__.py +43 -0
  261. mindspore/mindrecord/common/__init__.py +17 -0
  262. mindspore/mindrecord/common/constant.py +20 -0
  263. mindspore/mindrecord/common/enums.py +44 -0
  264. mindspore/mindrecord/common/exceptions.py +311 -0
  265. mindspore/mindrecord/config.py +809 -0
  266. mindspore/mindrecord/filereader.py +174 -0
  267. mindspore/mindrecord/filewriter.py +705 -0
  268. mindspore/mindrecord/mindpage.py +210 -0
  269. mindspore/mindrecord/shardheader.py +141 -0
  270. mindspore/mindrecord/shardindexgenerator.py +74 -0
  271. mindspore/mindrecord/shardreader.py +117 -0
  272. mindspore/mindrecord/shardsegment.py +128 -0
  273. mindspore/mindrecord/shardutils.py +185 -0
  274. mindspore/mindrecord/shardwriter.py +237 -0
  275. mindspore/mindrecord/tools/__init__.py +17 -0
  276. mindspore/mindrecord/tools/cifar10.py +140 -0
  277. mindspore/mindrecord/tools/cifar100.py +153 -0
  278. mindspore/mindrecord/tools/cifar100_to_mr.py +185 -0
  279. mindspore/mindrecord/tools/cifar10_to_mr.py +177 -0
  280. mindspore/mindrecord/tools/csv_to_mr.py +200 -0
  281. mindspore/mindrecord/tools/imagenet_to_mr.py +206 -0
  282. mindspore/mindrecord/tools/mnist_to_mr.py +259 -0
  283. mindspore/mindrecord/tools/tfrecord_to_mr.py +360 -0
  284. mindspore/mindspore_backend.dll +0 -0
  285. mindspore/mindspore_common.dll +0 -0
  286. mindspore/mindspore_core.dll +0 -0
  287. mindspore/mindspore_glog.dll +0 -0
  288. mindspore/mindspore_np_dtype.dll +0 -0
  289. mindspore/mindspore_shared_lib.dll +0 -0
  290. mindspore/mint/__init__.py +1137 -0
  291. mindspore/mint/linalg/__init__.py +22 -0
  292. mindspore/mint/nn/__init__.py +512 -0
  293. mindspore/mint/nn/functional.py +573 -0
  294. mindspore/mint/optim/__init__.py +24 -0
  295. mindspore/mint/optim/adamw.py +185 -0
  296. mindspore/msobj140.dll +0 -0
  297. mindspore/mspdb140.dll +0 -0
  298. mindspore/mspdbcore.dll +0 -0
  299. mindspore/mspdbst.dll +0 -0
  300. mindspore/mspft140.dll +0 -0
  301. mindspore/msvcdis140.dll +0 -0
  302. mindspore/msvcp140.dll +0 -0
  303. mindspore/msvcp140_1.dll +0 -0
  304. mindspore/msvcp140_2.dll +0 -0
  305. mindspore/msvcp140_atomic_wait.dll +0 -0
  306. mindspore/msvcp140_codecvt_ids.dll +0 -0
  307. mindspore/multiprocessing/__init__.py +72 -0
  308. mindspore/nn/__init__.py +48 -0
  309. mindspore/nn/cell.py +2605 -0
  310. mindspore/nn/dynamic_lr.py +482 -0
  311. mindspore/nn/extend/__init__.py +29 -0
  312. mindspore/nn/extend/basic.py +140 -0
  313. mindspore/nn/extend/embedding.py +143 -0
  314. mindspore/nn/extend/layer/__init__.py +27 -0
  315. mindspore/nn/extend/layer/normalization.py +109 -0
  316. mindspore/nn/extend/pooling.py +117 -0
  317. mindspore/nn/grad/__init__.py +21 -0
  318. mindspore/nn/grad/cell_grad.py +196 -0
  319. mindspore/nn/layer/__init__.py +63 -0
  320. mindspore/nn/layer/activation.py +1655 -0
  321. mindspore/nn/layer/basic.py +1519 -0
  322. mindspore/nn/layer/channel_shuffle.py +90 -0
  323. mindspore/nn/layer/combined.py +248 -0
  324. mindspore/nn/layer/container.py +734 -0
  325. mindspore/nn/layer/conv.py +1505 -0
  326. mindspore/nn/layer/dense.py +204 -0
  327. mindspore/nn/layer/embedding.py +751 -0
  328. mindspore/nn/layer/embedding_service.py +531 -0
  329. mindspore/nn/layer/embedding_service_layer.py +393 -0
  330. mindspore/nn/layer/image.py +661 -0
  331. mindspore/nn/layer/math.py +1069 -0
  332. mindspore/nn/layer/normalization.py +1177 -0
  333. mindspore/nn/layer/padding.py +894 -0
  334. mindspore/nn/layer/pooling.py +2148 -0
  335. mindspore/nn/layer/rnn_cells.py +388 -0
  336. mindspore/nn/layer/rnns.py +849 -0
  337. mindspore/nn/layer/thor_layer.py +963 -0
  338. mindspore/nn/layer/timedistributed.py +155 -0
  339. mindspore/nn/layer/transformer.py +823 -0
  340. mindspore/nn/learning_rate_schedule.py +512 -0
  341. mindspore/nn/loss/__init__.py +36 -0
  342. mindspore/nn/loss/loss.py +2846 -0
  343. mindspore/nn/metrics.py +53 -0
  344. mindspore/nn/optim/__init__.py +44 -0
  345. mindspore/nn/optim/_dist_optimizer_registry.py +111 -0
  346. mindspore/nn/optim/ada_grad.py +217 -0
  347. mindspore/nn/optim/adadelta.py +206 -0
  348. mindspore/nn/optim/adafactor.py +448 -0
  349. mindspore/nn/optim/adam.py +1297 -0
  350. mindspore/nn/optim/adamax.py +220 -0
  351. mindspore/nn/optim/adasum.py +548 -0
  352. mindspore/nn/optim/asgd.py +216 -0
  353. mindspore/nn/optim/ftrl.py +401 -0
  354. mindspore/nn/optim/lamb.py +296 -0
  355. mindspore/nn/optim/lars.py +202 -0
  356. mindspore/nn/optim/lazyadam.py +533 -0
  357. mindspore/nn/optim/momentum.py +239 -0
  358. mindspore/nn/optim/optimizer.py +1034 -0
  359. mindspore/nn/optim/proximal_ada_grad.py +242 -0
  360. mindspore/nn/optim/rmsprop.py +264 -0
  361. mindspore/nn/optim/rprop.py +251 -0
  362. mindspore/nn/optim/sgd.py +237 -0
  363. mindspore/nn/optim/thor.py +1310 -0
  364. mindspore/nn/probability/__init__.py +22 -0
  365. mindspore/nn/probability/bijector/__init__.py +35 -0
  366. mindspore/nn/probability/bijector/bijector.py +337 -0
  367. mindspore/nn/probability/bijector/exp.py +65 -0
  368. mindspore/nn/probability/bijector/gumbel_cdf.py +144 -0
  369. mindspore/nn/probability/bijector/invert.py +126 -0
  370. mindspore/nn/probability/bijector/power_transform.py +196 -0
  371. mindspore/nn/probability/bijector/scalar_affine.py +167 -0
  372. mindspore/nn/probability/bijector/softplus.py +189 -0
  373. mindspore/nn/probability/bnn_layers/__init__.py +29 -0
  374. mindspore/nn/probability/bnn_layers/_util.py +46 -0
  375. mindspore/nn/probability/bnn_layers/bnn_cell_wrapper.py +112 -0
  376. mindspore/nn/probability/bnn_layers/conv_variational.py +267 -0
  377. mindspore/nn/probability/bnn_layers/dense_variational.py +302 -0
  378. mindspore/nn/probability/bnn_layers/layer_distribution.py +123 -0
  379. mindspore/nn/probability/distribution/__init__.py +56 -0
  380. mindspore/nn/probability/distribution/_utils/__init__.py +34 -0
  381. mindspore/nn/probability/distribution/_utils/custom_ops.py +96 -0
  382. mindspore/nn/probability/distribution/_utils/utils.py +362 -0
  383. mindspore/nn/probability/distribution/bernoulli.py +334 -0
  384. mindspore/nn/probability/distribution/beta.py +391 -0
  385. mindspore/nn/probability/distribution/categorical.py +435 -0
  386. mindspore/nn/probability/distribution/cauchy.py +383 -0
  387. mindspore/nn/probability/distribution/distribution.py +827 -0
  388. mindspore/nn/probability/distribution/exponential.py +350 -0
  389. mindspore/nn/probability/distribution/gamma.py +391 -0
  390. mindspore/nn/probability/distribution/geometric.py +335 -0
  391. mindspore/nn/probability/distribution/gumbel.py +257 -0
  392. mindspore/nn/probability/distribution/half_normal.py +133 -0
  393. mindspore/nn/probability/distribution/laplace.py +128 -0
  394. mindspore/nn/probability/distribution/log_normal.py +272 -0
  395. mindspore/nn/probability/distribution/logistic.py +379 -0
  396. mindspore/nn/probability/distribution/normal.py +336 -0
  397. mindspore/nn/probability/distribution/poisson.py +288 -0
  398. mindspore/nn/probability/distribution/student_t.py +149 -0
  399. mindspore/nn/probability/distribution/transformed_distribution.py +235 -0
  400. mindspore/nn/probability/distribution/uniform.py +375 -0
  401. mindspore/nn/reinforcement/__init__.py +24 -0
  402. mindspore/nn/reinforcement/_batch_read_write.py +142 -0
  403. mindspore/nn/reinforcement/_tensors_queue.py +152 -0
  404. mindspore/nn/reinforcement/tensor_array.py +145 -0
  405. mindspore/nn/sparse/__init__.py +23 -0
  406. mindspore/nn/sparse/sparse.py +147 -0
  407. mindspore/nn/wrap/__init__.py +49 -0
  408. mindspore/nn/wrap/cell_wrapper.py +979 -0
  409. mindspore/nn/wrap/grad_reducer.py +608 -0
  410. mindspore/nn/wrap/loss_scale.py +680 -0
  411. mindspore/numpy/__init__.py +121 -0
  412. mindspore/numpy/array_creations.py +2734 -0
  413. mindspore/numpy/array_ops.py +2625 -0
  414. mindspore/numpy/dtypes.py +185 -0
  415. mindspore/numpy/fft.py +431 -0
  416. mindspore/numpy/logic_ops.py +935 -0
  417. mindspore/numpy/math_ops.py +5910 -0
  418. mindspore/numpy/utils.py +214 -0
  419. mindspore/numpy/utils_const.py +565 -0
  420. mindspore/opencv_core452.dll +0 -0
  421. mindspore/opencv_imgcodecs452.dll +0 -0
  422. mindspore/opencv_imgproc452.dll +0 -0
  423. mindspore/ops/__init__.py +54 -0
  424. mindspore/ops/_constants.py +30 -0
  425. mindspore/ops/_grad_experimental/__init__.py +31 -0
  426. mindspore/ops/_grad_experimental/grad_array_ops.py +830 -0
  427. mindspore/ops/_grad_experimental/grad_base.py +143 -0
  428. mindspore/ops/_grad_experimental/grad_comm_ops.py +670 -0
  429. mindspore/ops/_grad_experimental/grad_debug_ops.py +31 -0
  430. mindspore/ops/_grad_experimental/grad_implementations.py +203 -0
  431. mindspore/ops/_grad_experimental/grad_inner_ops.py +79 -0
  432. mindspore/ops/_grad_experimental/grad_math_ops.py +824 -0
  433. mindspore/ops/_grad_experimental/grad_nn_ops.py +231 -0
  434. mindspore/ops/_grad_experimental/grad_quant_ops.py +238 -0
  435. mindspore/ops/_grad_experimental/grad_sparse.py +342 -0
  436. mindspore/ops/_grad_experimental/grad_sparse_ops.py +399 -0
  437. mindspore/ops/_grad_experimental/taylor_rule.py +220 -0
  438. mindspore/ops/_op_impl/__init__.py +23 -0
  439. mindspore/ops/_op_impl/_custom_op/__init__.py +39 -0
  440. mindspore/ops/_op_impl/_custom_op/_basic.py +158 -0
  441. mindspore/ops/_op_impl/_custom_op/batch_matmul_impl.py +279 -0
  442. mindspore/ops/_op_impl/_custom_op/batchnorm_fold.py +156 -0
  443. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2.py +109 -0
  444. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2_grad.py +125 -0
  445. mindspore/ops/_op_impl/_custom_op/batchnorm_fold2_grad_reduce.py +105 -0
  446. mindspore/ops/_op_impl/_custom_op/batchnorm_fold_grad.py +124 -0
  447. mindspore/ops/_op_impl/_custom_op/cholesky_trsm_impl.py +116 -0
  448. mindspore/ops/_op_impl/_custom_op/correction_mul.py +89 -0
  449. mindspore/ops/_op_impl/_custom_op/correction_mul_grad.py +196 -0
  450. mindspore/ops/_op_impl/_custom_op/dsd_back_impl.py +366 -0
  451. mindspore/ops/_op_impl/_custom_op/dsd_impl.py +162 -0
  452. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel.py +136 -0
  453. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel_grad.py +206 -0
  454. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perchannel_grad_reduce.py +88 -0
  455. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer.py +128 -0
  456. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer_grad.py +199 -0
  457. mindspore/ops/_op_impl/_custom_op/fake_learned_scale_quant_perlayer_grad_reduce.py +88 -0
  458. mindspore/ops/_op_impl/_custom_op/fake_quant_perchannel.py +156 -0
  459. mindspore/ops/_op_impl/_custom_op/fake_quant_perchannel_grad.py +184 -0
  460. mindspore/ops/_op_impl/_custom_op/fake_quant_perlayer.py +143 -0
  461. mindspore/ops/_op_impl/_custom_op/fake_quant_perlayer_grad.py +169 -0
  462. mindspore/ops/_op_impl/_custom_op/fused_abs_max1_impl.py +548 -0
  463. mindspore/ops/_op_impl/_custom_op/img2col_impl.py +881 -0
  464. mindspore/ops/_op_impl/_custom_op/matmul_cube_dense_left_impl.py +278 -0
  465. mindspore/ops/_op_impl/_custom_op/matmul_cube_dense_right_impl.py +200 -0
  466. mindspore/ops/_op_impl/_custom_op/matmul_cube_fracz_left_cast_impl.py +334 -0
  467. mindspore/ops/_op_impl/_custom_op/matmul_cube_fracz_right_mul_impl.py +255 -0
  468. mindspore/ops/_op_impl/_custom_op/matmul_cube_impl.py +222 -0
  469. mindspore/ops/_op_impl/_custom_op/matmul_dds_grad_impl.py +644 -0
  470. mindspore/ops/_op_impl/_custom_op/matmul_dds_impl.py +488 -0
  471. mindspore/ops/_op_impl/_custom_op/matrix_combine_impl.py +87 -0
  472. mindspore/ops/_op_impl/_custom_op/minmax_update_perchannel.py +129 -0
  473. mindspore/ops/_op_impl/_custom_op/minmax_update_perlayer.py +121 -0
  474. mindspore/ops/_op_impl/_custom_op/transpose02314_impl.py +352 -0
  475. mindspore/ops/_op_impl/aicpu/__init__.py +441 -0
  476. mindspore/ops/_op_impl/aicpu/abs.py +36 -0
  477. mindspore/ops/_op_impl/aicpu/acos.py +32 -0
  478. mindspore/ops/_op_impl/aicpu/acos_grad.py +33 -0
  479. mindspore/ops/_op_impl/aicpu/acosh.py +34 -0
  480. mindspore/ops/_op_impl/aicpu/acosh_grad.py +35 -0
  481. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_2d.py +34 -0
  482. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_2d_grad.py +34 -0
  483. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_3d.py +39 -0
  484. mindspore/ops/_op_impl/aicpu/adaptive_avg_pool_3d_grad.py +39 -0
  485. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_2d.py +37 -0
  486. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_2d_grad.py +37 -0
  487. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_3d.py +42 -0
  488. mindspore/ops/_op_impl/aicpu/adaptive_max_pool_3d_grad.py +152 -0
  489. mindspore/ops/_op_impl/aicpu/add.py +43 -0
  490. mindspore/ops/_op_impl/aicpu/add_n.py +41 -0
  491. mindspore/ops/_op_impl/aicpu/add_v2.py +40 -0
  492. mindspore/ops/_op_impl/aicpu/addcdiv.py +41 -0
  493. mindspore/ops/_op_impl/aicpu/addcmul.py +47 -0
  494. mindspore/ops/_op_impl/aicpu/adjust_contrastv2.py +32 -0
  495. mindspore/ops/_op_impl/aicpu/adjust_hue.py +31 -0
  496. mindspore/ops/_op_impl/aicpu/adjust_saturation.py +32 -0
  497. mindspore/ops/_op_impl/aicpu/affine_grid.py +33 -0
  498. mindspore/ops/_op_impl/aicpu/affine_grid_grad.py +35 -0
  499. mindspore/ops/_op_impl/aicpu/angle.py +31 -0
  500. mindspore/ops/_op_impl/aicpu/arg_max.py +75 -0
  501. mindspore/ops/_op_impl/aicpu/arg_min.py +75 -0
  502. mindspore/ops/_op_impl/aicpu/argmax_with_value.py +43 -0
  503. mindspore/ops/_op_impl/aicpu/argmin_with_value.py +43 -0
  504. mindspore/ops/_op_impl/aicpu/asin.py +32 -0
  505. mindspore/ops/_op_impl/aicpu/asin_grad.py +33 -0
  506. mindspore/ops/_op_impl/aicpu/asinh.py +34 -0
  507. mindspore/ops/_op_impl/aicpu/asinh_grad.py +35 -0
  508. mindspore/ops/_op_impl/aicpu/atanh.py +34 -0
  509. mindspore/ops/_op_impl/aicpu/avgpool_grad_v1.py +37 -0
  510. mindspore/ops/_op_impl/aicpu/avgpool_v1.py +36 -0
  511. mindspore/ops/_op_impl/aicpu/bartlett_window.py +36 -0
  512. mindspore/ops/_op_impl/aicpu/batch_matmul.py +43 -0
  513. mindspore/ops/_op_impl/aicpu/batch_norm_grad_grad.py +49 -0
  514. mindspore/ops/_op_impl/aicpu/bernoulli.py +48 -0
  515. mindspore/ops/_op_impl/aicpu/bessel_i0.py +31 -0
  516. mindspore/ops/_op_impl/aicpu/betainc.py +31 -0
  517. mindspore/ops/_op_impl/aicpu/bias_add.py +44 -0
  518. mindspore/ops/_op_impl/aicpu/bias_add_grad.py +42 -0
  519. mindspore/ops/_op_impl/aicpu/bincount.py +33 -0
  520. mindspore/ops/_op_impl/aicpu/blackman_window.py +36 -0
  521. mindspore/ops/_op_impl/aicpu/broadcast_to.py +58 -0
  522. mindspore/ops/_op_impl/aicpu/bucketize.py +34 -0
  523. mindspore/ops/_op_impl/aicpu/cache_swap_table.py +102 -0
  524. mindspore/ops/_op_impl/aicpu/cast.py +225 -0
  525. mindspore/ops/_op_impl/aicpu/cauchy.py +33 -0
  526. mindspore/ops/_op_impl/aicpu/channel_shuffle.py +40 -0
  527. mindspore/ops/_op_impl/aicpu/check_numerics.py +33 -0
  528. mindspore/ops/_op_impl/aicpu/cholesky.py +32 -0
  529. mindspore/ops/_op_impl/aicpu/cholesky_inverse.py +31 -0
  530. mindspore/ops/_op_impl/aicpu/cholesky_solve.py +33 -0
  531. mindspore/ops/_op_impl/aicpu/choleskygrad.py +32 -0
  532. mindspore/ops/_op_impl/aicpu/coalesce.py +37 -0
  533. mindspore/ops/_op_impl/aicpu/col2im.py +38 -0
  534. mindspore/ops/_op_impl/aicpu/combined_non_max_suppression.py +42 -0
  535. mindspore/ops/_op_impl/aicpu/compare_and_bitpack.py +37 -0
  536. mindspore/ops/_op_impl/aicpu/complex.py +32 -0
  537. mindspore/ops/_op_impl/aicpu/complex_abs.py +31 -0
  538. mindspore/ops/_op_impl/aicpu/compute_accidental_hits.py +44 -0
  539. mindspore/ops/_op_impl/aicpu/concat.py +57 -0
  540. mindspore/ops/_op_impl/aicpu/concat_offset.py +42 -0
  541. mindspore/ops/_op_impl/aicpu/concat_offset_v1.py +31 -0
  542. mindspore/ops/_op_impl/aicpu/conj.py +42 -0
  543. mindspore/ops/_op_impl/aicpu/conjugate_transpose.py +58 -0
  544. mindspore/ops/_op_impl/aicpu/cos.py +34 -0
  545. mindspore/ops/_op_impl/aicpu/cosh.py +34 -0
  546. mindspore/ops/_op_impl/aicpu/count_nonzero.py +43 -0
  547. mindspore/ops/_op_impl/aicpu/crop_and_resize.py +69 -0
  548. mindspore/ops/_op_impl/aicpu/crop_and_resize_grad_boxes.py +68 -0
  549. mindspore/ops/_op_impl/aicpu/crop_and_resize_grad_image.py +38 -0
  550. mindspore/ops/_op_impl/aicpu/cross.py +42 -0
  551. mindspore/ops/_op_impl/aicpu/csr_sparse_matrix_to_dense.py +48 -0
  552. mindspore/ops/_op_impl/aicpu/csr_sparse_matrix_to_sparse_tensor.py +51 -0
  553. mindspore/ops/_op_impl/aicpu/ctc_greedy_decoder.py +35 -0
  554. mindspore/ops/_op_impl/aicpu/ctc_loss_v2.py +43 -0
  555. mindspore/ops/_op_impl/aicpu/ctc_loss_v2_grad.py +45 -0
  556. mindspore/ops/_op_impl/aicpu/ctcloss.py +38 -0
  557. mindspore/ops/_op_impl/aicpu/cummax.py +41 -0
  558. mindspore/ops/_op_impl/aicpu/cumprod.py +58 -0
  559. mindspore/ops/_op_impl/aicpu/cumsum.py +58 -0
  560. mindspore/ops/_op_impl/aicpu/cumulative_logsumexp.py +36 -0
  561. mindspore/ops/_op_impl/aicpu/data_format_vec_permute.py +32 -0
  562. mindspore/ops/_op_impl/aicpu/deformable_offsets.py +38 -0
  563. mindspore/ops/_op_impl/aicpu/deformable_offsets_grad.py +43 -0
  564. mindspore/ops/_op_impl/aicpu/dense_to_csr_sparse_matrix.py +49 -0
  565. mindspore/ops/_op_impl/aicpu/dense_to_dense_set_operation.py +45 -0
  566. mindspore/ops/_op_impl/aicpu/dense_to_sparse_set_operation.py +48 -0
  567. mindspore/ops/_op_impl/aicpu/depth_to_space.py +44 -0
  568. mindspore/ops/_op_impl/aicpu/diag.py +36 -0
  569. mindspore/ops/_op_impl/aicpu/diag_part.py +36 -0
  570. mindspore/ops/_op_impl/aicpu/diagonal.py +35 -0
  571. mindspore/ops/_op_impl/aicpu/digamma.py +31 -0
  572. mindspore/ops/_op_impl/aicpu/div.py +41 -0
  573. mindspore/ops/_op_impl/aicpu/div_no_nan.py +35 -0
  574. mindspore/ops/_op_impl/aicpu/dropout2d.py +42 -0
  575. mindspore/ops/_op_impl/aicpu/dropout3d.py +42 -0
  576. mindspore/ops/_op_impl/aicpu/dropout_genmask.py +41 -0
  577. mindspore/ops/_op_impl/aicpu/dropout_genmask_v3.py +32 -0
  578. mindspore/ops/_op_impl/aicpu/dynamic_stitch.py +42 -0
  579. mindspore/ops/_op_impl/aicpu/edit_distance.py +56 -0
  580. mindspore/ops/_op_impl/aicpu/eig.py +35 -0
  581. mindspore/ops/_op_impl/aicpu/embedding_lookup.py +102 -0
  582. mindspore/ops/_op_impl/aicpu/end_of_sequence.py +30 -0
  583. mindspore/ops/_op_impl/aicpu/environ_create.py +28 -0
  584. mindspore/ops/_op_impl/aicpu/environ_destroy_all.py +28 -0
  585. mindspore/ops/_op_impl/aicpu/environ_get.py +41 -0
  586. mindspore/ops/_op_impl/aicpu/environ_set.py +40 -0
  587. mindspore/ops/_op_impl/aicpu/eps.py +32 -0
  588. mindspore/ops/_op_impl/aicpu/equal.py +41 -0
  589. mindspore/ops/_op_impl/aicpu/exp.py +37 -0
  590. mindspore/ops/_op_impl/aicpu/expand.py +45 -0
  591. mindspore/ops/_op_impl/aicpu/expand_dims.py +42 -0
  592. mindspore/ops/_op_impl/aicpu/expm1.py +34 -0
  593. mindspore/ops/_op_impl/aicpu/extract_glimpse.py +35 -0
  594. mindspore/ops/_op_impl/aicpu/eye.py +44 -0
  595. mindspore/ops/_op_impl/aicpu/fft_with_size.py +47 -0
  596. mindspore/ops/_op_impl/aicpu/fill_diagonal.py +39 -0
  597. mindspore/ops/_op_impl/aicpu/fill_v2.py +58 -0
  598. mindspore/ops/_op_impl/aicpu/flatten.py +43 -0
  599. mindspore/ops/_op_impl/aicpu/floor_div.py +38 -0
  600. mindspore/ops/_op_impl/aicpu/fmax.py +36 -0
  601. mindspore/ops/_op_impl/aicpu/fmin.py +37 -0
  602. mindspore/ops/_op_impl/aicpu/fractional_avg_pool.py +41 -0
  603. mindspore/ops/_op_impl/aicpu/fractional_avg_pool_grad.py +41 -0
  604. mindspore/ops/_op_impl/aicpu/fractional_max_pool.py +41 -0
  605. mindspore/ops/_op_impl/aicpu/fractional_max_pool3d_grad_with_fixed_ksize.py +43 -0
  606. mindspore/ops/_op_impl/aicpu/fractional_max_pool3d_with_fixed_ksize.py +65 -0
  607. mindspore/ops/_op_impl/aicpu/fractional_max_pool_grad.py +42 -0
  608. mindspore/ops/_op_impl/aicpu/fractional_max_pool_grad_with_fixed_ksize.py +42 -0
  609. mindspore/ops/_op_impl/aicpu/fractional_max_pool_with_fixed_ksize.py +49 -0
  610. mindspore/ops/_op_impl/aicpu/fse_decode.py +43 -0
  611. mindspore/ops/_op_impl/aicpu/fused_sparse_adam.py +46 -0
  612. mindspore/ops/_op_impl/aicpu/fused_sparse_ftrl.py +41 -0
  613. mindspore/ops/_op_impl/aicpu/fused_sparse_lazy_adam.py +46 -0
  614. mindspore/ops/_op_impl/aicpu/fused_sparse_proximal_adagrad.py +39 -0
  615. mindspore/ops/_op_impl/aicpu/gamma.py +38 -0
  616. mindspore/ops/_op_impl/aicpu/gather.py +46 -0
  617. mindspore/ops/_op_impl/aicpu/gather_d.py +79 -0
  618. mindspore/ops/_op_impl/aicpu/gather_d_grad_v2.py +79 -0
  619. mindspore/ops/_op_impl/aicpu/gather_grad.py +54 -0
  620. mindspore/ops/_op_impl/aicpu/gather_nd.py +56 -0
  621. mindspore/ops/_op_impl/aicpu/gcd.py +32 -0
  622. mindspore/ops/_op_impl/aicpu/generate_eod_mask.py +38 -0
  623. mindspore/ops/_op_impl/aicpu/geqrf.py +32 -0
  624. mindspore/ops/_op_impl/aicpu/get_next.py +39 -0
  625. mindspore/ops/_op_impl/aicpu/glu.py +33 -0
  626. mindspore/ops/_op_impl/aicpu/glu_grad.py +34 -0
  627. mindspore/ops/_op_impl/aicpu/greater.py +41 -0
  628. mindspore/ops/_op_impl/aicpu/greater_equal.py +41 -0
  629. mindspore/ops/_op_impl/aicpu/grid_sampler_2d.py +35 -0
  630. mindspore/ops/_op_impl/aicpu/grid_sampler_2d_grad.py +38 -0
  631. mindspore/ops/_op_impl/aicpu/grid_sampler_3d.py +34 -0
  632. mindspore/ops/_op_impl/aicpu/grid_sampler_3d_grad.py +38 -0
  633. mindspore/ops/_op_impl/aicpu/hamming_window.py +57 -0
  634. mindspore/ops/_op_impl/aicpu/hard_sigmoid.py +32 -0
  635. mindspore/ops/_op_impl/aicpu/hard_sigmoid_grad.py +33 -0
  636. mindspore/ops/_op_impl/aicpu/heaviside.py +40 -0
  637. mindspore/ops/_op_impl/aicpu/histogram.py +35 -0
  638. mindspore/ops/_op_impl/aicpu/hsv_to_rgb.py +32 -0
  639. mindspore/ops/_op_impl/aicpu/hypot.py +32 -0
  640. mindspore/ops/_op_impl/aicpu/identity.py +42 -0
  641. mindspore/ops/_op_impl/aicpu/identity_n.py +41 -0
  642. mindspore/ops/_op_impl/aicpu/igamma.py +30 -0
  643. mindspore/ops/_op_impl/aicpu/igammac.py +30 -0
  644. mindspore/ops/_op_impl/aicpu/igammagrada.py +30 -0
  645. mindspore/ops/_op_impl/aicpu/im2col.py +43 -0
  646. mindspore/ops/_op_impl/aicpu/imag.py +31 -0
  647. mindspore/ops/_op_impl/aicpu/index_fill.py +54 -0
  648. mindspore/ops/_op_impl/aicpu/index_put.py +50 -0
  649. mindspore/ops/_op_impl/aicpu/init_data_set_queue.py +27 -0
  650. mindspore/ops/_op_impl/aicpu/inplace_index_add.py +39 -0
  651. mindspore/ops/_op_impl/aicpu/instance_norm_v2.py +41 -0
  652. mindspore/ops/_op_impl/aicpu/instance_norm_v2_grad.py +44 -0
  653. mindspore/ops/_op_impl/aicpu/is_finite.py +40 -0
  654. mindspore/ops/_op_impl/aicpu/is_inf.py +31 -0
  655. mindspore/ops/_op_impl/aicpu/is_nan.py +31 -0
  656. mindspore/ops/_op_impl/aicpu/kldivloss.py +34 -0
  657. mindspore/ops/_op_impl/aicpu/kldivlossgrad.py +35 -0
  658. mindspore/ops/_op_impl/aicpu/layer_norm_grad_grad.py +47 -0
  659. mindspore/ops/_op_impl/aicpu/lcm.py +32 -0
  660. mindspore/ops/_op_impl/aicpu/left_shift.py +38 -0
  661. mindspore/ops/_op_impl/aicpu/less.py +41 -0
  662. mindspore/ops/_op_impl/aicpu/less_equal.py +41 -0
  663. mindspore/ops/_op_impl/aicpu/lgamma.py +33 -0
  664. mindspore/ops/_op_impl/aicpu/linear_sum_assignment.py +57 -0
  665. mindspore/ops/_op_impl/aicpu/linspace.py +33 -0
  666. mindspore/ops/_op_impl/aicpu/list_diff.py +50 -0
  667. mindspore/ops/_op_impl/aicpu/log.py +37 -0
  668. mindspore/ops/_op_impl/aicpu/log1p.py +34 -0
  669. mindspore/ops/_op_impl/aicpu/log_matrix_determinant.py +31 -0
  670. mindspore/ops/_op_impl/aicpu/log_normal_reverse.py +33 -0
  671. mindspore/ops/_op_impl/aicpu/log_uniform_candidate_sampler.py +37 -0
  672. mindspore/ops/_op_impl/aicpu/logical_xor.py +30 -0
  673. mindspore/ops/_op_impl/aicpu/logit.py +33 -0
  674. mindspore/ops/_op_impl/aicpu/logit_grad.py +34 -0
  675. mindspore/ops/_op_impl/aicpu/logspace.py +36 -0
  676. mindspore/ops/_op_impl/aicpu/lower_bound.py +47 -0
  677. mindspore/ops/_op_impl/aicpu/lstsq.py +34 -0
  678. mindspore/ops/_op_impl/aicpu/lu.py +39 -0
  679. mindspore/ops/_op_impl/aicpu/lu_solve.py +32 -0
  680. mindspore/ops/_op_impl/aicpu/lu_unpack.py +114 -0
  681. mindspore/ops/_op_impl/aicpu/lu_unpack_grad.py +49 -0
  682. mindspore/ops/_op_impl/aicpu/masked_fill.py +42 -0
  683. mindspore/ops/_op_impl/aicpu/masked_scatter.py +40 -0
  684. mindspore/ops/_op_impl/aicpu/masked_select.py +31 -0
  685. mindspore/ops/_op_impl/aicpu/masked_select_grad.py +35 -0
  686. mindspore/ops/_op_impl/aicpu/matmul.py +39 -0
  687. mindspore/ops/_op_impl/aicpu/matrix_band_part.py +59 -0
  688. mindspore/ops/_op_impl/aicpu/matrix_determinant.py +30 -0
  689. mindspore/ops/_op_impl/aicpu/matrix_diag_part_v3.py +54 -0
  690. mindspore/ops/_op_impl/aicpu/matrix_diag_v3.py +56 -0
  691. mindspore/ops/_op_impl/aicpu/matrix_exp.py +34 -0
  692. mindspore/ops/_op_impl/aicpu/matrix_inverse.py +31 -0
  693. mindspore/ops/_op_impl/aicpu/matrix_logarithm.py +31 -0
  694. mindspore/ops/_op_impl/aicpu/matrix_power.py +37 -0
  695. mindspore/ops/_op_impl/aicpu/matrix_set_diag_v3.py +54 -0
  696. mindspore/ops/_op_impl/aicpu/matrix_solve.py +35 -0
  697. mindspore/ops/_op_impl/aicpu/matrix_solve_ls.py +36 -0
  698. mindspore/ops/_op_impl/aicpu/matrix_triangular_solve.py +36 -0
  699. mindspore/ops/_op_impl/aicpu/max_pool3d_grad_with_argmax.py +60 -0
  700. mindspore/ops/_op_impl/aicpu/max_pool3d_with_argmax.py +59 -0
  701. mindspore/ops/_op_impl/aicpu/max_unpool2d.py +57 -0
  702. mindspore/ops/_op_impl/aicpu/max_unpool2d_grad.py +58 -0
  703. mindspore/ops/_op_impl/aicpu/max_unpool3d.py +57 -0
  704. mindspore/ops/_op_impl/aicpu/max_unpool3d_grad.py +58 -0
  705. mindspore/ops/_op_impl/aicpu/maximum_grad_grad.py +40 -0
  706. mindspore/ops/_op_impl/aicpu/maxpool_grad_v1.py +46 -0
  707. mindspore/ops/_op_impl/aicpu/maxpool_v1.py +42 -0
  708. mindspore/ops/_op_impl/aicpu/median.py +39 -0
  709. mindspore/ops/_op_impl/aicpu/median_grad.py +45 -0
  710. mindspore/ops/_op_impl/aicpu/meshgrid.py +41 -0
  711. mindspore/ops/_op_impl/aicpu/minimum_grad_grad.py +40 -0
  712. mindspore/ops/_op_impl/aicpu/mirror_pad.py +50 -0
  713. mindspore/ops/_op_impl/aicpu/mirror_pad_grad.py +48 -0
  714. mindspore/ops/_op_impl/aicpu/mul.py +43 -0
  715. mindspore/ops/_op_impl/aicpu/mul_no_nan.py +42 -0
  716. mindspore/ops/_op_impl/aicpu/multi_margin_loss.py +37 -0
  717. mindspore/ops/_op_impl/aicpu/multi_margin_loss_grad.py +41 -0
  718. mindspore/ops/_op_impl/aicpu/multilabel_margin_loss_grad.py +37 -0
  719. mindspore/ops/_op_impl/aicpu/multinomial.py +47 -0
  720. mindspore/ops/_op_impl/aicpu/multinomial_with_replacement.py +35 -0
  721. mindspore/ops/_op_impl/aicpu/mvlgamma.py +32 -0
  722. mindspore/ops/_op_impl/aicpu/mvlgamma_grad.py +33 -0
  723. mindspore/ops/_op_impl/aicpu/nan_to_num.py +34 -0
  724. mindspore/ops/_op_impl/aicpu/neg.py +36 -0
  725. mindspore/ops/_op_impl/aicpu/nextafter.py +32 -0
  726. mindspore/ops/_op_impl/aicpu/nllloss.py +38 -0
  727. mindspore/ops/_op_impl/aicpu/nllloss_grad.py +39 -0
  728. mindspore/ops/_op_impl/aicpu/no_repeat_ngram.py +34 -0
  729. mindspore/ops/_op_impl/aicpu/non_deterministic_ints.py +33 -0
  730. mindspore/ops/_op_impl/aicpu/non_max_suppression.py +36 -0
  731. mindspore/ops/_op_impl/aicpu/non_max_suppression_with_overlaps.py +35 -0
  732. mindspore/ops/_op_impl/aicpu/non_zero.py +43 -0
  733. mindspore/ops/_op_impl/aicpu/not_equal.py +39 -0
  734. mindspore/ops/_op_impl/aicpu/nth_element.py +39 -0
  735. mindspore/ops/_op_impl/aicpu/nuclear_norm.py +33 -0
  736. mindspore/ops/_op_impl/aicpu/one_hot.py +116 -0
  737. mindspore/ops/_op_impl/aicpu/ones_like.py +39 -0
  738. mindspore/ops/_op_impl/aicpu/orgqr.py +34 -0
  739. mindspore/ops/_op_impl/aicpu/pad_and_shift.py +33 -0
  740. mindspore/ops/_op_impl/aicpu/pad_v3.py +61 -0
  741. mindspore/ops/_op_impl/aicpu/pad_v3_grad.py +59 -0
  742. mindspore/ops/_op_impl/aicpu/padding.py +41 -0
  743. mindspore/ops/_op_impl/aicpu/parameterized_truncated_normal.py +54 -0
  744. mindspore/ops/_op_impl/aicpu/pdist_grad.py +33 -0
  745. mindspore/ops/_op_impl/aicpu/poisson.py +37 -0
  746. mindspore/ops/_op_impl/aicpu/polar.py +32 -0
  747. mindspore/ops/_op_impl/aicpu/polygamma.py +34 -0
  748. mindspore/ops/_op_impl/aicpu/pow.py +39 -0
  749. mindspore/ops/_op_impl/aicpu/print_tensor.py +39 -0
  750. mindspore/ops/_op_impl/aicpu/priority_replay_buffer.py +113 -0
  751. mindspore/ops/_op_impl/aicpu/qr.py +36 -0
  752. mindspore/ops/_op_impl/aicpu/quant_dtype_cast.py +40 -0
  753. mindspore/ops/_op_impl/aicpu/quantile.py +35 -0
  754. mindspore/ops/_op_impl/aicpu/ragged_range.py +49 -0
  755. mindspore/ops/_op_impl/aicpu/ragged_tensor_to_sparse.py +73 -0
  756. mindspore/ops/_op_impl/aicpu/ragged_tensor_to_tensor.py +74 -0
  757. mindspore/ops/_op_impl/aicpu/random_categorical.py +68 -0
  758. mindspore/ops/_op_impl/aicpu/random_choice_with_mask.py +36 -0
  759. mindspore/ops/_op_impl/aicpu/random_gamma.py +38 -0
  760. mindspore/ops/_op_impl/aicpu/random_poisson.py +134 -0
  761. mindspore/ops/_op_impl/aicpu/random_shuffle.py +47 -0
  762. mindspore/ops/_op_impl/aicpu/randperm.py +38 -0
  763. mindspore/ops/_op_impl/aicpu/randperm_v2.py +41 -0
  764. mindspore/ops/_op_impl/aicpu/range.py +36 -0
  765. mindspore/ops/_op_impl/aicpu/range_v2.py +35 -0
  766. mindspore/ops/_op_impl/aicpu/real.py +31 -0
  767. mindspore/ops/_op_impl/aicpu/real_div.py +40 -0
  768. mindspore/ops/_op_impl/aicpu/reciprocal.py +34 -0
  769. mindspore/ops/_op_impl/aicpu/reciprocal_grad.py +35 -0
  770. mindspore/ops/_op_impl/aicpu/reduce_mean.py +57 -0
  771. mindspore/ops/_op_impl/aicpu/reduce_prod.py +57 -0
  772. mindspore/ops/_op_impl/aicpu/reduce_sum.py +57 -0
  773. mindspore/ops/_op_impl/aicpu/relu_grad_v3.py +41 -0
  774. mindspore/ops/_op_impl/aicpu/relu_v3.py +38 -0
  775. mindspore/ops/_op_impl/aicpu/reservoir_replay_buffer.py +96 -0
  776. mindspore/ops/_op_impl/aicpu/reshape.py +42 -0
  777. mindspore/ops/_op_impl/aicpu/resize_area.py +40 -0
  778. mindspore/ops/_op_impl/aicpu/resize_bicubic.py +20 -0
  779. mindspore/ops/_op_impl/aicpu/resize_bicubic_grad.py +19 -0
  780. mindspore/ops/_op_impl/aicpu/resize_bilinear.py +32 -0
  781. mindspore/ops/_op_impl/aicpu/resize_bilinear_grad.py +32 -0
  782. mindspore/ops/_op_impl/aicpu/resize_nearest_neighbor_v2.py +36 -0
  783. mindspore/ops/_op_impl/aicpu/resize_nearest_neighbor_v2_grad.py +35 -0
  784. mindspore/ops/_op_impl/aicpu/resize_v2.py +68 -0
  785. mindspore/ops/_op_impl/aicpu/resize_v2_grad.py +68 -0
  786. mindspore/ops/_op_impl/aicpu/reverse_sequence.py +55 -0
  787. mindspore/ops/_op_impl/aicpu/reversev2.py +54 -0
  788. mindspore/ops/_op_impl/aicpu/rgb_to_hsv.py +32 -0
  789. mindspore/ops/_op_impl/aicpu/right_shift.py +38 -0
  790. mindspore/ops/_op_impl/aicpu/rnnt_loss.py +35 -0
  791. mindspore/ops/_op_impl/aicpu/round.py +34 -0
  792. mindspore/ops/_op_impl/aicpu/rsqrt.py +33 -0
  793. mindspore/ops/_op_impl/aicpu/rsqrt_grad.py +36 -0
  794. mindspore/ops/_op_impl/aicpu/sample_distorted_bounding_box_v2.py +49 -0
  795. mindspore/ops/_op_impl/aicpu/scale_and_translate.py +52 -0
  796. mindspore/ops/_op_impl/aicpu/scale_and_translate_grad.py +36 -0
  797. mindspore/ops/_op_impl/aicpu/scatter.py +79 -0
  798. mindspore/ops/_op_impl/aicpu/scatter_add_with_axis.py +53 -0
  799. mindspore/ops/_op_impl/aicpu/scatter_elements.py +39 -0
  800. mindspore/ops/_op_impl/aicpu/scatter_nd.py +59 -0
  801. mindspore/ops/_op_impl/aicpu/scatter_nd_max.py +54 -0
  802. mindspore/ops/_op_impl/aicpu/scatter_nd_min.py +54 -0
  803. mindspore/ops/_op_impl/aicpu/scatter_nd_update.py +59 -0
  804. mindspore/ops/_op_impl/aicpu/search_sorted.py +44 -0
  805. mindspore/ops/_op_impl/aicpu/segment_max.py +52 -0
  806. mindspore/ops/_op_impl/aicpu/segment_mean.py +56 -0
  807. mindspore/ops/_op_impl/aicpu/segment_min.py +52 -0
  808. mindspore/ops/_op_impl/aicpu/segment_prod.py +56 -0
  809. mindspore/ops/_op_impl/aicpu/segment_sum.py +56 -0
  810. mindspore/ops/_op_impl/aicpu/select.py +45 -0
  811. mindspore/ops/_op_impl/aicpu/self_adjoint_eig.py +34 -0
  812. mindspore/ops/_op_impl/aicpu/sequence_add.py +34 -0
  813. mindspore/ops/_op_impl/aicpu/sequence_add_offset.py +34 -0
  814. mindspore/ops/_op_impl/aicpu/sequence_addn.py +38 -0
  815. mindspore/ops/_op_impl/aicpu/sequence_concat.py +40 -0
  816. mindspore/ops/_op_impl/aicpu/sequence_stack.py +40 -0
  817. mindspore/ops/_op_impl/aicpu/set_size.py +38 -0
  818. mindspore/ops/_op_impl/aicpu/sign.py +36 -0
  819. mindspore/ops/_op_impl/aicpu/sin.py +34 -0
  820. mindspore/ops/_op_impl/aicpu/sinc.py +43 -0
  821. mindspore/ops/_op_impl/aicpu/sinh.py +34 -0
  822. mindspore/ops/_op_impl/aicpu/slice.py +59 -0
  823. mindspore/ops/_op_impl/aicpu/slice_grad.py +76 -0
  824. mindspore/ops/_op_impl/aicpu/smooth_l1_loss.py +35 -0
  825. mindspore/ops/_op_impl/aicpu/smooth_l1_loss_grad.py +37 -0
  826. mindspore/ops/_op_impl/aicpu/sort.py +39 -0
  827. mindspore/ops/_op_impl/aicpu/space_to_depth.py +44 -0
  828. mindspore/ops/_op_impl/aicpu/sparse_addmm.py +87 -0
  829. mindspore/ops/_op_impl/aicpu/sparse_apply_adagrad_da.py +80 -0
  830. mindspore/ops/_op_impl/aicpu/sparse_apply_centered_rms_prop.py +105 -0
  831. mindspore/ops/_op_impl/aicpu/sparse_apply_momentum.py +80 -0
  832. mindspore/ops/_op_impl/aicpu/sparse_apply_proximal_gradient_descent.py +79 -0
  833. mindspore/ops/_op_impl/aicpu/sparse_concat.py +59 -0
  834. mindspore/ops/_op_impl/aicpu/sparse_cross.py +42 -0
  835. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_add.py +58 -0
  836. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_div.py +58 -0
  837. mindspore/ops/_op_impl/aicpu/sparse_dense_cwise_mul.py +58 -0
  838. mindspore/ops/_op_impl/aicpu/sparse_fill_empty_rows.py +63 -0
  839. mindspore/ops/_op_impl/aicpu/sparse_fill_empty_rows_grad.py +45 -0
  840. mindspore/ops/_op_impl/aicpu/sparse_matrix_mat_mul.py +56 -0
  841. mindspore/ops/_op_impl/aicpu/sparse_matrix_nnz.py +81 -0
  842. mindspore/ops/_op_impl/aicpu/sparse_matrix_transpose.py +116 -0
  843. mindspore/ops/_op_impl/aicpu/sparse_reorder.py +56 -0
  844. mindspore/ops/_op_impl/aicpu/sparse_reshape.py +34 -0
  845. mindspore/ops/_op_impl/aicpu/sparse_segment_mean_grad.py +36 -0
  846. mindspore/ops/_op_impl/aicpu/sparse_segment_mean_with_num_segments.py +44 -0
  847. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n.py +43 -0
  848. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n_grad.py +38 -0
  849. mindspore/ops/_op_impl/aicpu/sparse_segment_sqrt_n_with_num_segments.py +44 -0
  850. mindspore/ops/_op_impl/aicpu/sparse_segment_sum.py +49 -0
  851. mindspore/ops/_op_impl/aicpu/sparse_segment_sum_with_num_segments.py +68 -0
  852. mindspore/ops/_op_impl/aicpu/sparse_slice.py +63 -0
  853. mindspore/ops/_op_impl/aicpu/sparse_slice_grad.py +61 -0
  854. mindspore/ops/_op_impl/aicpu/sparse_softmax.py +33 -0
  855. mindspore/ops/_op_impl/aicpu/sparse_softmax_cross_entropy_with_logits_v2.py +35 -0
  856. mindspore/ops/_op_impl/aicpu/sparse_sparse_maximum.py +53 -0
  857. mindspore/ops/_op_impl/aicpu/sparse_sparse_minimum.py +53 -0
  858. mindspore/ops/_op_impl/aicpu/sparse_tensor_dense_add.py +84 -0
  859. mindspore/ops/_op_impl/aicpu/sparse_tensor_dense_mat_mul.py +190 -0
  860. mindspore/ops/_op_impl/aicpu/sparse_tensor_to_csr_sparse_matrix.py +51 -0
  861. mindspore/ops/_op_impl/aicpu/sparse_to_dense_v2.py +73 -0
  862. mindspore/ops/_op_impl/aicpu/split.py +45 -0
  863. mindspore/ops/_op_impl/aicpu/sqrt.py +34 -0
  864. mindspore/ops/_op_impl/aicpu/sqrt_grad.py +35 -0
  865. mindspore/ops/_op_impl/aicpu/square.py +35 -0
  866. mindspore/ops/_op_impl/aicpu/squared_difference.py +37 -0
  867. mindspore/ops/_op_impl/aicpu/squeeze.py +42 -0
  868. mindspore/ops/_op_impl/aicpu/sspaddmm.py +97 -0
  869. mindspore/ops/_op_impl/aicpu/stack.py +45 -0
  870. mindspore/ops/_op_impl/aicpu/stack_push_pop.py +87 -0
  871. mindspore/ops/_op_impl/aicpu/standard_laplace.py +34 -0
  872. mindspore/ops/_op_impl/aicpu/standard_normal.py +34 -0
  873. mindspore/ops/_op_impl/aicpu/stateless_dropout_genmask.py +37 -0
  874. mindspore/ops/_op_impl/aicpu/stft.py +70 -0
  875. mindspore/ops/_op_impl/aicpu/strided_slice.py +43 -0
  876. mindspore/ops/_op_impl/aicpu/strided_slice_grad.py +50 -0
  877. mindspore/ops/_op_impl/aicpu/strided_slice_v2.py +93 -0
  878. mindspore/ops/_op_impl/aicpu/strided_slice_v2_grad.py +66 -0
  879. mindspore/ops/_op_impl/aicpu/sub.py +41 -0
  880. mindspore/ops/_op_impl/aicpu/sub_and_filter.py +36 -0
  881. mindspore/ops/_op_impl/aicpu/tan.py +34 -0
  882. mindspore/ops/_op_impl/aicpu/tanh.py +34 -0
  883. mindspore/ops/_op_impl/aicpu/tanh_grad.py +35 -0
  884. mindspore/ops/_op_impl/aicpu/tensor_scatter_update.py +59 -0
  885. mindspore/ops/_op_impl/aicpu/tile.py +56 -0
  886. mindspore/ops/_op_impl/aicpu/topk.py +34 -0
  887. mindspore/ops/_op_impl/aicpu/trace.py +40 -0
  888. mindspore/ops/_op_impl/aicpu/tracegrad.py +41 -0
  889. mindspore/ops/_op_impl/aicpu/trans_data.py +35 -0
  890. mindspore/ops/_op_impl/aicpu/transpose.py +58 -0
  891. mindspore/ops/_op_impl/aicpu/tridiagonal_matmul.py +42 -0
  892. mindspore/ops/_op_impl/aicpu/tridiagonal_solve.py +35 -0
  893. mindspore/ops/_op_impl/aicpu/tril.py +42 -0
  894. mindspore/ops/_op_impl/aicpu/tril_indices.py +34 -0
  895. mindspore/ops/_op_impl/aicpu/triplet_margin_loss.py +62 -0
  896. mindspore/ops/_op_impl/aicpu/triu.py +43 -0
  897. mindspore/ops/_op_impl/aicpu/triu_indices.py +34 -0
  898. mindspore/ops/_op_impl/aicpu/truncated_normal.py +39 -0
  899. mindspore/ops/_op_impl/aicpu/uniform.py +36 -0
  900. mindspore/ops/_op_impl/aicpu/uniform_candidate_sampler.py +41 -0
  901. mindspore/ops/_op_impl/aicpu/uniform_int.py +36 -0
  902. mindspore/ops/_op_impl/aicpu/uniform_real.py +33 -0
  903. mindspore/ops/_op_impl/aicpu/unique.py +31 -0
  904. mindspore/ops/_op_impl/aicpu/unique_consecutive.py +47 -0
  905. mindspore/ops/_op_impl/aicpu/unique_with_pad.py +32 -0
  906. mindspore/ops/_op_impl/aicpu/unravel_index.py +32 -0
  907. mindspore/ops/_op_impl/aicpu/unsorted_segment_prod.py +53 -0
  908. mindspore/ops/_op_impl/aicpu/unsorted_segment_sum.py +57 -0
  909. mindspore/ops/_op_impl/aicpu/unstack.py +45 -0
  910. mindspore/ops/_op_impl/aicpu/update_cache.py +44 -0
  911. mindspore/ops/_op_impl/aicpu/upper_bound.py +47 -0
  912. mindspore/ops/_op_impl/aicpu/upsample_nearest_3d.py +42 -0
  913. mindspore/ops/_op_impl/aicpu/upsample_nearest_3d_grad.py +49 -0
  914. mindspore/ops/_op_impl/aicpu/upsample_trilinear_3d.py +40 -0
  915. mindspore/ops/_op_impl/aicpu/upsample_trilinear_3d_grad.py +50 -0
  916. mindspore/ops/_op_impl/aicpu/xdivy.py +35 -0
  917. mindspore/ops/_op_impl/aicpu/xlogy.py +33 -0
  918. mindspore/ops/_op_impl/aicpu/zeros_like.py +42 -0
  919. mindspore/ops/_op_impl/aicpu/zeta.py +31 -0
  920. mindspore/ops/_op_impl/akg/__init__.py +19 -0
  921. mindspore/ops/_op_impl/akg/ascend/__init__.py +48 -0
  922. mindspore/ops/_op_impl/akg/ascend/abs.py +35 -0
  923. mindspore/ops/_op_impl/akg/ascend/add.py +42 -0
  924. mindspore/ops/_op_impl/akg/ascend/add_n.py +37 -0
  925. mindspore/ops/_op_impl/akg/ascend/batchmatmul.py +33 -0
  926. mindspore/ops/_op_impl/akg/ascend/cast.py +46 -0
  927. mindspore/ops/_op_impl/akg/ascend/equal.py +35 -0
  928. mindspore/ops/_op_impl/akg/ascend/exp.py +35 -0
  929. mindspore/ops/_op_impl/akg/ascend/expand_dims.py +33 -0
  930. mindspore/ops/_op_impl/akg/ascend/greater.py +34 -0
  931. mindspore/ops/_op_impl/akg/ascend/greater_equal.py +35 -0
  932. mindspore/ops/_op_impl/akg/ascend/less.py +31 -0
  933. mindspore/ops/_op_impl/akg/ascend/less_equal.py +35 -0
  934. mindspore/ops/_op_impl/akg/ascend/load_im2col.py +33 -0
  935. mindspore/ops/_op_impl/akg/ascend/log.py +34 -0
  936. mindspore/ops/_op_impl/akg/ascend/maximum.py +36 -0
  937. mindspore/ops/_op_impl/akg/ascend/minimum.py +39 -0
  938. mindspore/ops/_op_impl/akg/ascend/mul.py +41 -0
  939. mindspore/ops/_op_impl/akg/ascend/neg.py +37 -0
  940. mindspore/ops/_op_impl/akg/ascend/pow.py +35 -0
  941. mindspore/ops/_op_impl/akg/ascend/prod_force_se_a.py +33 -0
  942. mindspore/ops/_op_impl/akg/ascend/real_div.py +36 -0
  943. mindspore/ops/_op_impl/akg/ascend/reciprocal.py +32 -0
  944. mindspore/ops/_op_impl/akg/ascend/reduce_max.py +32 -0
  945. mindspore/ops/_op_impl/akg/ascend/reduce_min.py +32 -0
  946. mindspore/ops/_op_impl/akg/ascend/reduce_sum.py +37 -0
  947. mindspore/ops/_op_impl/akg/ascend/rsqrt.py +35 -0
  948. mindspore/ops/_op_impl/akg/ascend/select.py +37 -0
  949. mindspore/ops/_op_impl/akg/ascend/sqrt.py +35 -0
  950. mindspore/ops/_op_impl/akg/ascend/square.py +35 -0
  951. mindspore/ops/_op_impl/akg/ascend/sub.py +42 -0
  952. mindspore/ops/_op_impl/akg/cpu/__init__.py +23 -0
  953. mindspore/ops/_op_impl/akg/cpu/coo2csr.py +29 -0
  954. mindspore/ops/_op_impl/akg/cpu/csr2coo.py +29 -0
  955. mindspore/ops/_op_impl/akg/cpu/csr_gather.py +33 -0
  956. mindspore/ops/_op_impl/akg/cpu/csr_mm.py +34 -0
  957. mindspore/ops/_op_impl/akg/cpu/csr_mul.py +33 -0
  958. mindspore/ops/_op_impl/akg/cpu/csr_mv.py +33 -0
  959. mindspore/ops/_op_impl/akg/cpu/csr_reduce_sum.py +31 -0
  960. mindspore/ops/_op_impl/akg/gpu/__init__.py +24 -0
  961. mindspore/ops/_op_impl/akg/gpu/coo2csr.py +29 -0
  962. mindspore/ops/_op_impl/akg/gpu/csr2coo.py +29 -0
  963. mindspore/ops/_op_impl/akg/gpu/csr_div.py +36 -0
  964. mindspore/ops/_op_impl/akg/gpu/csr_gather.py +33 -0
  965. mindspore/ops/_op_impl/akg/gpu/csr_mm.py +37 -0
  966. mindspore/ops/_op_impl/akg/gpu/csr_mul.py +36 -0
  967. mindspore/ops/_op_impl/akg/gpu/csr_mv.py +36 -0
  968. mindspore/ops/_op_impl/akg/gpu/csr_reduce_sum.py +33 -0
  969. mindspore/ops/_op_impl/cpu/__init__.py +78 -0
  970. mindspore/ops/_op_impl/cpu/adam.py +49 -0
  971. mindspore/ops/_op_impl/cpu/adam_weight_decay.py +47 -0
  972. mindspore/ops/_op_impl/cpu/arg_max.py +30 -0
  973. mindspore/ops/_op_impl/cpu/arg_max_with_value.py +31 -0
  974. mindspore/ops/_op_impl/cpu/arg_min_with_value.py +31 -0
  975. mindspore/ops/_op_impl/cpu/buffer_append.py +28 -0
  976. mindspore/ops/_op_impl/cpu/buffer_get.py +28 -0
  977. mindspore/ops/_op_impl/cpu/buffer_sample.py +28 -0
  978. mindspore/ops/_op_impl/cpu/cast.py +171 -0
  979. mindspore/ops/_op_impl/cpu/concat_offset.py +38 -0
  980. mindspore/ops/_op_impl/cpu/conv2d.py +30 -0
  981. mindspore/ops/_op_impl/cpu/conv3d.py +30 -0
  982. mindspore/ops/_op_impl/cpu/div.py +32 -0
  983. mindspore/ops/_op_impl/cpu/dropout.py +31 -0
  984. mindspore/ops/_op_impl/cpu/dropout_grad.py +30 -0
  985. mindspore/ops/_op_impl/cpu/dynamic_shape.py +42 -0
  986. mindspore/ops/_op_impl/cpu/dynamic_stitch.py +41 -0
  987. mindspore/ops/_op_impl/cpu/equal_count.py +30 -0
  988. mindspore/ops/_op_impl/cpu/gather_d.py +49 -0
  989. mindspore/ops/_op_impl/cpu/gather_d_grad.py +38 -0
  990. mindspore/ops/_op_impl/cpu/gather_d_grad_v2.py +40 -0
  991. mindspore/ops/_op_impl/cpu/gather_v2.py +40 -0
  992. mindspore/ops/_op_impl/cpu/hsigmoid.py +33 -0
  993. mindspore/ops/_op_impl/cpu/hsigmoid_grad.py +34 -0
  994. mindspore/ops/_op_impl/cpu/hswish.py +32 -0
  995. mindspore/ops/_op_impl/cpu/hswish_grad.py +33 -0
  996. mindspore/ops/_op_impl/cpu/identity_n.py +40 -0
  997. mindspore/ops/_op_impl/cpu/is_finite.py +39 -0
  998. mindspore/ops/_op_impl/cpu/l2loss.py +30 -0
  999. mindspore/ops/_op_impl/cpu/layer_norm.py +36 -0
  1000. mindspore/ops/_op_impl/cpu/layer_norm_grad.py +38 -0
  1001. mindspore/ops/_op_impl/cpu/maximum.py +35 -0
  1002. mindspore/ops/_op_impl/cpu/maximum_grad.py +47 -0
  1003. mindspore/ops/_op_impl/cpu/minimum.py +40 -0
  1004. mindspore/ops/_op_impl/cpu/minimum_grad.py +51 -0
  1005. mindspore/ops/_op_impl/cpu/mirror_pad.py +36 -0
  1006. mindspore/ops/_op_impl/cpu/mirror_pad_grad.py +36 -0
  1007. mindspore/ops/_op_impl/cpu/mul.py +32 -0
  1008. mindspore/ops/_op_impl/cpu/one_hot.py +31 -0
  1009. mindspore/ops/_op_impl/cpu/pad.py +32 -0
  1010. mindspore/ops/_op_impl/cpu/pow.py +32 -0
  1011. mindspore/ops/_op_impl/cpu/priority_replay_buffer.py +42 -0
  1012. mindspore/ops/_op_impl/cpu/pyexecute.py +29 -0
  1013. mindspore/ops/_op_impl/cpu/pyfunc.py +29 -0
  1014. mindspore/ops/_op_impl/cpu/range.py +34 -0
  1015. mindspore/ops/_op_impl/cpu/real_div.py +33 -0
  1016. mindspore/ops/_op_impl/cpu/reduce_all.py +29 -0
  1017. mindspore/ops/_op_impl/cpu/reduce_any.py +29 -0
  1018. mindspore/ops/_op_impl/cpu/reduce_max.py +32 -0
  1019. mindspore/ops/_op_impl/cpu/reduce_mean.py +40 -0
  1020. mindspore/ops/_op_impl/cpu/reduce_min.py +32 -0
  1021. mindspore/ops/_op_impl/cpu/reduce_prod.py +40 -0
  1022. mindspore/ops/_op_impl/cpu/reduce_std.py +31 -0
  1023. mindspore/ops/_op_impl/cpu/reduce_sum.py +41 -0
  1024. mindspore/ops/_op_impl/cpu/space_to_batch_nd.py +38 -0
  1025. mindspore/ops/_op_impl/cpu/sparse_slice.py +62 -0
  1026. mindspore/ops/_op_impl/cpu/sparse_slice_grad.py +60 -0
  1027. mindspore/ops/_op_impl/cpu/split.py +34 -0
  1028. mindspore/ops/_op_impl/cpu/sspaddmm.py +95 -0
  1029. mindspore/ops/_op_impl/cpu/stack.py +38 -0
  1030. mindspore/ops/_op_impl/cpu/sub.py +32 -0
  1031. mindspore/ops/_op_impl/cpu/tensor_copy_slices.py +41 -0
  1032. mindspore/ops/_op_impl/cpu/tile.py +37 -0
  1033. mindspore/ops/_op_impl/cpu/top_k.py +31 -0
  1034. mindspore/ops/_op_impl/cpu/transpose.py +39 -0
  1035. mindspore/ops/_primitive_cache.py +90 -0
  1036. mindspore/ops/_register_for_op.py +73 -0
  1037. mindspore/ops/_utils/__init__.py +20 -0
  1038. mindspore/ops/_utils/utils.py +147 -0
  1039. mindspore/ops/_vmap/__init__.py +25 -0
  1040. mindspore/ops/_vmap/vmap_array_ops.py +2151 -0
  1041. mindspore/ops/_vmap/vmap_base.py +533 -0
  1042. mindspore/ops/_vmap/vmap_convolution_ops.py +441 -0
  1043. mindspore/ops/_vmap/vmap_debug_ops.py +50 -0
  1044. mindspore/ops/_vmap/vmap_grad_math_ops.py +274 -0
  1045. mindspore/ops/_vmap/vmap_grad_nn_ops.py +806 -0
  1046. mindspore/ops/_vmap/vmap_image_ops.py +194 -0
  1047. mindspore/ops/_vmap/vmap_math_ops.py +977 -0
  1048. mindspore/ops/_vmap/vmap_nn_ops.py +2209 -0
  1049. mindspore/ops/_vmap/vmap_other_ops.py +105 -0
  1050. mindspore/ops/_vmap/vmap_random_ops.py +122 -0
  1051. mindspore/ops/_vmap/vmap_sparse_ops.py +89 -0
  1052. mindspore/ops/auto_generate/__init__.py +31 -0
  1053. mindspore/ops/auto_generate/cpp_create_prim_instance_helper.py +231 -0
  1054. mindspore/ops/auto_generate/gen_arg_dtype_cast.py +250 -0
  1055. mindspore/ops/auto_generate/gen_arg_handler.py +197 -0
  1056. mindspore/ops/auto_generate/gen_extend_func.py +980 -0
  1057. mindspore/ops/auto_generate/gen_ops_def.py +6443 -0
  1058. mindspore/ops/auto_generate/gen_ops_prim.py +13167 -0
  1059. mindspore/ops/auto_generate/pyboost_inner_prim.py +429 -0
  1060. mindspore/ops/composite/__init__.py +71 -0
  1061. mindspore/ops/composite/base.py +1281 -0
  1062. mindspore/ops/composite/env_ops.py +41 -0
  1063. mindspore/ops/composite/math_ops.py +125 -0
  1064. mindspore/ops/composite/multitype_ops/__init__.py +77 -0
  1065. mindspore/ops/composite/multitype_ops/_compile_utils.py +1458 -0
  1066. mindspore/ops/composite/multitype_ops/_constexpr_utils.py +897 -0
  1067. mindspore/ops/composite/multitype_ops/add_impl.py +606 -0
  1068. mindspore/ops/composite/multitype_ops/bitwise_and_impl.py +56 -0
  1069. mindspore/ops/composite/multitype_ops/bitwise_or_impl.py +56 -0
  1070. mindspore/ops/composite/multitype_ops/bitwise_xor_impl.py +56 -0
  1071. mindspore/ops/composite/multitype_ops/div_impl.py +189 -0
  1072. mindspore/ops/composite/multitype_ops/equal_impl.py +335 -0
  1073. mindspore/ops/composite/multitype_ops/floordiv_impl.py +88 -0
  1074. mindspore/ops/composite/multitype_ops/getitem_impl.py +400 -0
  1075. mindspore/ops/composite/multitype_ops/greater_equal_impl.py +109 -0
  1076. mindspore/ops/composite/multitype_ops/greater_impl.py +110 -0
  1077. mindspore/ops/composite/multitype_ops/in_impl.py +196 -0
  1078. mindspore/ops/composite/multitype_ops/left_shift_impl.py +37 -0
  1079. mindspore/ops/composite/multitype_ops/less_equal_impl.py +111 -0
  1080. mindspore/ops/composite/multitype_ops/less_impl.py +112 -0
  1081. mindspore/ops/composite/multitype_ops/logic_not_impl.py +113 -0
  1082. mindspore/ops/composite/multitype_ops/logical_and_impl.py +60 -0
  1083. mindspore/ops/composite/multitype_ops/logical_or_impl.py +61 -0
  1084. mindspore/ops/composite/multitype_ops/mod_impl.py +86 -0
  1085. mindspore/ops/composite/multitype_ops/mul_impl.py +294 -0
  1086. mindspore/ops/composite/multitype_ops/negative_impl.py +79 -0
  1087. mindspore/ops/composite/multitype_ops/not_equal_impl.py +290 -0
  1088. mindspore/ops/composite/multitype_ops/not_in_impl.py +196 -0
  1089. mindspore/ops/composite/multitype_ops/ones_like_impl.py +96 -0
  1090. mindspore/ops/composite/multitype_ops/pow_impl.py +87 -0
  1091. mindspore/ops/composite/multitype_ops/right_shift_impl.py +37 -0
  1092. mindspore/ops/composite/multitype_ops/setitem_impl.py +884 -0
  1093. mindspore/ops/composite/multitype_ops/sub_impl.py +116 -0
  1094. mindspore/ops/composite/multitype_ops/uadd_impl.py +29 -0
  1095. mindspore/ops/composite/multitype_ops/zeros_like_impl.py +228 -0
  1096. mindspore/ops/deprecated.py +315 -0
  1097. mindspore/ops/extend/__init__.py +53 -0
  1098. mindspore/ops/extend/array_func.py +218 -0
  1099. mindspore/ops/extend/math_func.py +76 -0
  1100. mindspore/ops/extend/nn_func.py +308 -0
  1101. mindspore/ops/function/__init__.py +760 -0
  1102. mindspore/ops/function/array_func.py +6889 -0
  1103. mindspore/ops/function/clip_func.py +384 -0
  1104. mindspore/ops/function/debug_func.py +69 -0
  1105. mindspore/ops/function/fft_func.py +31 -0
  1106. mindspore/ops/function/grad/__init__.py +34 -0
  1107. mindspore/ops/function/grad/grad_func.py +1424 -0
  1108. mindspore/ops/function/image_func.py +292 -0
  1109. mindspore/ops/function/linalg_func.py +416 -0
  1110. mindspore/ops/function/math_func.py +11877 -0
  1111. mindspore/ops/function/nn_func.py +8175 -0
  1112. mindspore/ops/function/other_func.py +114 -0
  1113. mindspore/ops/function/parameter_func.py +134 -0
  1114. mindspore/ops/function/random_func.py +1539 -0
  1115. mindspore/ops/function/reshard_func.py +102 -0
  1116. mindspore/ops/function/sparse_func.py +884 -0
  1117. mindspore/ops/function/sparse_unary_func.py +2422 -0
  1118. mindspore/ops/function/spectral_func.py +150 -0
  1119. mindspore/ops/function/vmap_func.py +116 -0
  1120. mindspore/ops/functional.py +454 -0
  1121. mindspore/ops/op_info_register.py +1572 -0
  1122. mindspore/ops/operations/__init__.py +717 -0
  1123. mindspore/ops/operations/_csr_ops.py +403 -0
  1124. mindspore/ops/operations/_custom_grad.py +181 -0
  1125. mindspore/ops/operations/_embedding_cache_ops.py +307 -0
  1126. mindspore/ops/operations/_grad_ops.py +3052 -0
  1127. mindspore/ops/operations/_infer_ops.py +19 -0
  1128. mindspore/ops/operations/_inner_ops.py +2567 -0
  1129. mindspore/ops/operations/_map_tensor_ops.py +112 -0
  1130. mindspore/ops/operations/_ms_kernel.py +601 -0
  1131. mindspore/ops/operations/_ocr_ops.py +379 -0
  1132. mindspore/ops/operations/_opaque_predicate_registry.py +41 -0
  1133. mindspore/ops/operations/_pyfunc_registry.py +58 -0
  1134. mindspore/ops/operations/_quant_ops.py +1844 -0
  1135. mindspore/ops/operations/_rl_inner_ops.py +1231 -0
  1136. mindspore/ops/operations/_scalar_ops.py +106 -0
  1137. mindspore/ops/operations/_sequence_ops.py +1155 -0
  1138. mindspore/ops/operations/_sparse_grad_ops.py +56 -0
  1139. mindspore/ops/operations/_tensor_array.py +359 -0
  1140. mindspore/ops/operations/_thor_ops.py +807 -0
  1141. mindspore/ops/operations/array_ops.py +6258 -0
  1142. mindspore/ops/operations/comm_ops.py +1996 -0
  1143. mindspore/ops/operations/control_ops.py +127 -0
  1144. mindspore/ops/operations/custom_ops.py +1065 -0
  1145. mindspore/ops/operations/debug_ops.py +646 -0
  1146. mindspore/ops/operations/image_ops.py +1041 -0
  1147. mindspore/ops/operations/inner_ops.py +697 -0
  1148. mindspore/ops/operations/linalg_ops.py +95 -0
  1149. mindspore/ops/operations/manually_defined/__init__.py +24 -0
  1150. mindspore/ops/operations/manually_defined/_inner.py +61 -0
  1151. mindspore/ops/operations/manually_defined/ops_def.py +2016 -0
  1152. mindspore/ops/operations/math_ops.py +5306 -0
  1153. mindspore/ops/operations/nn_ops.py +9669 -0
  1154. mindspore/ops/operations/other_ops.py +871 -0
  1155. mindspore/ops/operations/random_ops.py +1243 -0
  1156. mindspore/ops/operations/reshard_ops.py +53 -0
  1157. mindspore/ops/operations/rl_ops.py +288 -0
  1158. mindspore/ops/operations/sparse_ops.py +2753 -0
  1159. mindspore/ops/operations/spectral_ops.py +111 -0
  1160. mindspore/ops/primitive.py +1034 -0
  1161. mindspore/ops/signature.py +54 -0
  1162. mindspore/ops/silent_check.py +162 -0
  1163. mindspore/ops/vm_impl_registry.py +91 -0
  1164. mindspore/ops_generate/__init__.py +27 -0
  1165. mindspore/ops_generate/arg_dtype_cast.py +250 -0
  1166. mindspore/ops_generate/arg_handler.py +197 -0
  1167. mindspore/ops_generate/gen_aclnn_implement.py +263 -0
  1168. mindspore/ops_generate/gen_ops.py +1084 -0
  1169. mindspore/ops_generate/gen_ops_inner_prim.py +131 -0
  1170. mindspore/ops_generate/gen_pyboost_func.py +968 -0
  1171. mindspore/ops_generate/gen_utils.py +209 -0
  1172. mindspore/ops_generate/op_proto.py +138 -0
  1173. mindspore/ops_generate/pyboost_utils.py +354 -0
  1174. mindspore/ops_generate/template.py +239 -0
  1175. mindspore/parallel/__init__.py +28 -0
  1176. mindspore/parallel/_auto_parallel_context.py +1466 -0
  1177. mindspore/parallel/_cell_wrapper.py +91 -0
  1178. mindspore/parallel/_cost_model_context.py +700 -0
  1179. mindspore/parallel/_dp_allreduce_fusion.py +159 -0
  1180. mindspore/parallel/_offload_context.py +275 -0
  1181. mindspore/parallel/_parallel_serialization.py +533 -0
  1182. mindspore/parallel/_ps_context.py +242 -0
  1183. mindspore/parallel/_recovery_context.py +110 -0
  1184. mindspore/parallel/_tensor.py +660 -0
  1185. mindspore/parallel/_transformer/__init__.py +35 -0
  1186. mindspore/parallel/_transformer/layers.py +765 -0
  1187. mindspore/parallel/_transformer/loss.py +251 -0
  1188. mindspore/parallel/_transformer/moe.py +693 -0
  1189. mindspore/parallel/_transformer/op_parallel_config.py +222 -0
  1190. mindspore/parallel/_transformer/transformer.py +3119 -0
  1191. mindspore/parallel/_utils.py +600 -0
  1192. mindspore/parallel/algo_parameter_config.py +400 -0
  1193. mindspore/parallel/checkpoint_transform.py +643 -0
  1194. mindspore/parallel/cluster/__init__.py +15 -0
  1195. mindspore/parallel/cluster/process_entity/__init__.py +18 -0
  1196. mindspore/parallel/cluster/process_entity/_api.py +344 -0
  1197. mindspore/parallel/cluster/process_entity/_utils.py +126 -0
  1198. mindspore/parallel/cluster/run.py +136 -0
  1199. mindspore/parallel/mpi/__init__.py +14 -0
  1200. mindspore/parallel/mpi/_mpi_config.py +116 -0
  1201. mindspore/parallel/parameter_broadcast.py +152 -0
  1202. mindspore/parallel/shard.py +350 -0
  1203. mindspore/perf_msvcbuildinsights.dll +0 -0
  1204. mindspore/pgodb140.dll +0 -0
  1205. mindspore/pgort140.dll +0 -0
  1206. mindspore/profiler/__init__.py +27 -0
  1207. mindspore/profiler/common/__init__.py +14 -0
  1208. mindspore/profiler/common/exceptions/__init__.py +14 -0
  1209. mindspore/profiler/common/exceptions/error_code.py +83 -0
  1210. mindspore/profiler/common/exceptions/exceptions.py +286 -0
  1211. mindspore/profiler/common/process_pool.py +41 -0
  1212. mindspore/profiler/common/singleton.py +28 -0
  1213. mindspore/profiler/common/struct_type.py +118 -0
  1214. mindspore/profiler/common/util.py +444 -0
  1215. mindspore/profiler/common/validator/__init__.py +14 -0
  1216. mindspore/profiler/common/validator/validate_path.py +84 -0
  1217. mindspore/profiler/envprofiling.py +256 -0
  1218. mindspore/profiler/parser/__init__.py +14 -0
  1219. mindspore/profiler/parser/aicpu_data_parser.py +272 -0
  1220. mindspore/profiler/parser/ascend_analysis/__init__.py +14 -0
  1221. mindspore/profiler/parser/ascend_analysis/constant.py +53 -0
  1222. mindspore/profiler/parser/ascend_analysis/file_manager.py +159 -0
  1223. mindspore/profiler/parser/ascend_analysis/function_event.py +161 -0
  1224. mindspore/profiler/parser/ascend_analysis/fwk_cann_parser.py +131 -0
  1225. mindspore/profiler/parser/ascend_analysis/fwk_file_parser.py +85 -0
  1226. mindspore/profiler/parser/ascend_analysis/msprof_timeline_parser.py +57 -0
  1227. mindspore/profiler/parser/ascend_analysis/profiler_info_parser.py +116 -0
  1228. mindspore/profiler/parser/ascend_analysis/tlv_decoder.py +86 -0
  1229. mindspore/profiler/parser/ascend_analysis/trace_event_manager.py +68 -0
  1230. mindspore/profiler/parser/ascend_cluster_generator.py +116 -0
  1231. mindspore/profiler/parser/ascend_communicate_generator.py +314 -0
  1232. mindspore/profiler/parser/ascend_flops_generator.py +116 -0
  1233. mindspore/profiler/parser/ascend_fpbp_generator.py +82 -0
  1234. mindspore/profiler/parser/ascend_hccl_generator.py +271 -0
  1235. mindspore/profiler/parser/ascend_integrate_generator.py +42 -0
  1236. mindspore/profiler/parser/ascend_memory_generator.py +185 -0
  1237. mindspore/profiler/parser/ascend_msprof_exporter.py +281 -0
  1238. mindspore/profiler/parser/ascend_msprof_generator.py +187 -0
  1239. mindspore/profiler/parser/ascend_op_generator.py +334 -0
  1240. mindspore/profiler/parser/ascend_steptrace_generator.py +94 -0
  1241. mindspore/profiler/parser/ascend_timeline_generator.py +543 -0
  1242. mindspore/profiler/parser/base_timeline_generator.py +489 -0
  1243. mindspore/profiler/parser/container.py +229 -0
  1244. mindspore/profiler/parser/cpu_gpu_timeline_generator.py +684 -0
  1245. mindspore/profiler/parser/flops_parser.py +531 -0
  1246. mindspore/profiler/parser/framework_enum.py +111 -0
  1247. mindspore/profiler/parser/framework_parser.py +854 -0
  1248. mindspore/profiler/parser/framework_struct.py +61 -0
  1249. mindspore/profiler/parser/hccl_parser.py +573 -0
  1250. mindspore/profiler/parser/hwts_log_parser.py +122 -0
  1251. mindspore/profiler/parser/integrator.py +526 -0
  1252. mindspore/profiler/parser/memory_usage_parser.py +431 -0
  1253. mindspore/profiler/parser/minddata_analyzer.py +800 -0
  1254. mindspore/profiler/parser/minddata_parser.py +186 -0
  1255. mindspore/profiler/parser/minddata_pipeline_parser.py +299 -0
  1256. mindspore/profiler/parser/msadvisor_analyzer.py +82 -0
  1257. mindspore/profiler/parser/msadvisor_parser.py +240 -0
  1258. mindspore/profiler/parser/op_intermediate_parser.py +149 -0
  1259. mindspore/profiler/parser/optime_parser.py +250 -0
  1260. mindspore/profiler/parser/profiler_info.py +141 -0
  1261. mindspore/profiler/parser/step_trace_parser.py +666 -0
  1262. mindspore/profiler/profiling.py +2054 -0
  1263. mindspore/rewrite/__init__.py +29 -0
  1264. mindspore/rewrite/api/__init__.py +17 -0
  1265. mindspore/rewrite/api/node.py +519 -0
  1266. mindspore/rewrite/api/node_type.py +53 -0
  1267. mindspore/rewrite/api/pattern_engine.py +490 -0
  1268. mindspore/rewrite/api/scoped_value.py +181 -0
  1269. mindspore/rewrite/api/symbol_tree.py +497 -0
  1270. mindspore/rewrite/ast_helpers/__init__.py +25 -0
  1271. mindspore/rewrite/ast_helpers/ast_converter.py +143 -0
  1272. mindspore/rewrite/ast_helpers/ast_finder.py +404 -0
  1273. mindspore/rewrite/ast_helpers/ast_flattener.py +268 -0
  1274. mindspore/rewrite/ast_helpers/ast_modifier.py +605 -0
  1275. mindspore/rewrite/ast_helpers/ast_replacer.py +79 -0
  1276. mindspore/rewrite/common/__init__.py +19 -0
  1277. mindspore/rewrite/common/config.py +24 -0
  1278. mindspore/rewrite/common/error_log.py +39 -0
  1279. mindspore/rewrite/common/event.py +28 -0
  1280. mindspore/rewrite/common/namer.py +271 -0
  1281. mindspore/rewrite/common/namespace.py +118 -0
  1282. mindspore/rewrite/common/observable.py +44 -0
  1283. mindspore/rewrite/common/observer.py +54 -0
  1284. mindspore/rewrite/node/__init__.py +22 -0
  1285. mindspore/rewrite/node/call_function.py +95 -0
  1286. mindspore/rewrite/node/cell_container.py +139 -0
  1287. mindspore/rewrite/node/control_flow.py +113 -0
  1288. mindspore/rewrite/node/node.py +1428 -0
  1289. mindspore/rewrite/node/node_manager.py +283 -0
  1290. mindspore/rewrite/node/node_topological_manager.py +223 -0
  1291. mindspore/rewrite/parsers/__init__.py +29 -0
  1292. mindspore/rewrite/parsers/arguments_parser.py +63 -0
  1293. mindspore/rewrite/parsers/assign_parser.py +852 -0
  1294. mindspore/rewrite/parsers/attribute_parser.py +57 -0
  1295. mindspore/rewrite/parsers/class_def_parser.py +289 -0
  1296. mindspore/rewrite/parsers/constant_parser.py +104 -0
  1297. mindspore/rewrite/parsers/container_parser.py +88 -0
  1298. mindspore/rewrite/parsers/expr_parser.py +55 -0
  1299. mindspore/rewrite/parsers/for_parser.py +61 -0
  1300. mindspore/rewrite/parsers/function_def_parser.py +84 -0
  1301. mindspore/rewrite/parsers/if_parser.py +85 -0
  1302. mindspore/rewrite/parsers/module_parser.py +117 -0
  1303. mindspore/rewrite/parsers/parser.py +43 -0
  1304. mindspore/rewrite/parsers/parser_register.py +86 -0
  1305. mindspore/rewrite/parsers/return_parser.py +37 -0
  1306. mindspore/rewrite/parsers/while_parser.py +59 -0
  1307. mindspore/rewrite/sparsify/__init__.py +0 -0
  1308. mindspore/rewrite/sparsify/sparse_transformer.py +457 -0
  1309. mindspore/rewrite/sparsify/sparsify.py +112 -0
  1310. mindspore/rewrite/sparsify/utils.py +179 -0
  1311. mindspore/rewrite/symbol_tree/__init__.py +20 -0
  1312. mindspore/rewrite/symbol_tree/symbol_tree.py +1819 -0
  1313. mindspore/rewrite/symbol_tree/symbol_tree_builder.py +76 -0
  1314. mindspore/rewrite/symbol_tree/symbol_tree_dumper.py +142 -0
  1315. mindspore/run_check/__init__.py +20 -0
  1316. mindspore/run_check/_check_version.py +574 -0
  1317. mindspore/run_check/run_check.py +66 -0
  1318. mindspore/safeguard/__init__.py +18 -0
  1319. mindspore/safeguard/rewrite_obfuscation.py +531 -0
  1320. mindspore/swresample-4.dll +0 -0
  1321. mindspore/swscale-6.dll +0 -0
  1322. mindspore/tbbmalloc.dll +0 -0
  1323. mindspore/tinyxml2.dll +0 -0
  1324. mindspore/train/__init__.py +47 -0
  1325. mindspore/train/_utils.py +439 -0
  1326. mindspore/train/amp.py +817 -0
  1327. mindspore/train/anf_ir_pb2.py +1517 -0
  1328. mindspore/train/callback/__init__.py +44 -0
  1329. mindspore/train/callback/_backup_and_restore.py +117 -0
  1330. mindspore/train/callback/_callback.py +613 -0
  1331. mindspore/train/callback/_checkpoint.py +751 -0
  1332. mindspore/train/callback/_cluster_monitor.py +201 -0
  1333. mindspore/train/callback/_dataset_graph.py +150 -0
  1334. mindspore/train/callback/_early_stop.py +239 -0
  1335. mindspore/train/callback/_flops_collector.py +238 -0
  1336. mindspore/train/callback/_history.py +92 -0
  1337. mindspore/train/callback/_lambda_callback.py +80 -0
  1338. mindspore/train/callback/_landscape.py +1049 -0
  1339. mindspore/train/callback/_loss_monitor.py +107 -0
  1340. mindspore/train/callback/_lr_scheduler_callback.py +76 -0
  1341. mindspore/train/callback/_mindio_ttp.py +443 -0
  1342. mindspore/train/callback/_on_request_exit.py +195 -0
  1343. mindspore/train/callback/_reduce_lr_on_plateau.py +226 -0
  1344. mindspore/train/callback/_summary_collector.py +1184 -0
  1345. mindspore/train/callback/_time_monitor.py +141 -0
  1346. mindspore/train/checkpoint_pb2.py +233 -0
  1347. mindspore/train/data_sink.py +219 -0
  1348. mindspore/train/dataset_helper.py +688 -0
  1349. mindspore/train/lineage_pb2.py +1260 -0
  1350. mindspore/train/loss_scale_manager.py +213 -0
  1351. mindspore/train/memory_profiling_pb2.py +298 -0
  1352. mindspore/train/metrics/__init__.py +175 -0
  1353. mindspore/train/metrics/accuracy.py +133 -0
  1354. mindspore/train/metrics/auc.py +129 -0
  1355. mindspore/train/metrics/bleu_score.py +170 -0
  1356. mindspore/train/metrics/confusion_matrix.py +700 -0
  1357. mindspore/train/metrics/cosine_similarity.py +109 -0
  1358. mindspore/train/metrics/dice.py +116 -0
  1359. mindspore/train/metrics/error.py +175 -0
  1360. mindspore/train/metrics/fbeta.py +167 -0
  1361. mindspore/train/metrics/hausdorff_distance.py +333 -0
  1362. mindspore/train/metrics/loss.py +97 -0
  1363. mindspore/train/metrics/mean_surface_distance.py +189 -0
  1364. mindspore/train/metrics/metric.py +373 -0
  1365. mindspore/train/metrics/occlusion_sensitivity.py +225 -0
  1366. mindspore/train/metrics/perplexity.py +133 -0
  1367. mindspore/train/metrics/precision.py +160 -0
  1368. mindspore/train/metrics/recall.py +159 -0
  1369. mindspore/train/metrics/roc.py +223 -0
  1370. mindspore/train/metrics/root_mean_square_surface_distance.py +191 -0
  1371. mindspore/train/metrics/topk.py +167 -0
  1372. mindspore/train/mind_ir_pb2.py +1903 -0
  1373. mindspore/train/model.py +2176 -0
  1374. mindspore/train/node_strategy_pb2.py +653 -0
  1375. mindspore/train/print_pb2.py +184 -0
  1376. mindspore/train/profiling_parallel_pb2.py +151 -0
  1377. mindspore/train/serialization.py +3101 -0
  1378. mindspore/train/summary/__init__.py +23 -0
  1379. mindspore/train/summary/_lineage_adapter.py +41 -0
  1380. mindspore/train/summary/_summary_adapter.py +496 -0
  1381. mindspore/train/summary/_writer_pool.py +207 -0
  1382. mindspore/train/summary/enums.py +56 -0
  1383. mindspore/train/summary/summary_record.py +581 -0
  1384. mindspore/train/summary/writer.py +167 -0
  1385. mindspore/train/summary_pb2.py +1165 -0
  1386. mindspore/train/train_thor/__init__.py +20 -0
  1387. mindspore/train/train_thor/convert_utils.py +268 -0
  1388. mindspore/train/train_thor/dataset_helper.py +192 -0
  1389. mindspore/train/train_thor/model_thor.py +257 -0
  1390. mindspore/turbojpeg.dll +0 -0
  1391. mindspore/vcmeta.dll +0 -0
  1392. mindspore/vcomp140.dll +0 -0
  1393. mindspore/vcruntime140.dll +0 -0
  1394. mindspore/vcruntime140_1.dll +0 -0
  1395. mindspore/version.py +1 -0
  1396. mindspore-2.3.0.dist-info/METADATA +351 -0
  1397. mindspore-2.3.0.dist-info/RECORD +1400 -0
  1398. mindspore-2.3.0.dist-info/WHEEL +5 -0
  1399. mindspore-2.3.0.dist-info/entry_points.txt +4 -0
  1400. mindspore-2.3.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2846 @@
1
+ # Copyright 2020-2022 Huawei Technologies Co., Ltd
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ # ============================================================================
15
+ """loss"""
16
+ from __future__ import absolute_import, division
17
+ import math
18
+
19
+ import mindspore
20
+ import mindspore.common.dtype as mstype
21
+ import mindspore.ops as ops
22
+ from mindspore import log
23
+ from mindspore.common.tensor import Tensor
24
+ from mindspore.common.parameter import Parameter
25
+ from mindspore.ops import operations as P
26
+ from mindspore.ops.operations import _inner_ops as inner
27
+ from mindspore.ops.operations.nn_ops import MultiMarginLoss as MultiMarginLossOp
28
+ from mindspore.ops.operations.nn_ops import MultilabelMarginLoss as MultilabelMarginLossOp
29
+ from mindspore.ops import functional as F
30
+ from mindspore import nn
31
+ from mindspore.ops.primitive import constexpr, _primexpr
32
+ from mindspore.nn.cell import Cell
33
+ from mindspore.nn.layer.activation import get_activation
34
+ from mindspore import _checkparam as validator
35
+ from mindspore import context
36
+
37
+
38
+ class LossBase(Cell):
39
+ """
40
+ Base class for other losses.
41
+
42
+ Other losses derived from this should implement their own `construct` and use method `self.get_loss`
43
+ to apply reduction to loss values.
44
+
45
+ Args:
46
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
47
+ ``'sum'`` . Default: ``'mean'`` .
48
+
49
+ - ``'none'``: no reduction will be applied.
50
+ - ``'mean'``: compute and return the (weighted) mean of elements in the output.
51
+ - ``'sum'``: the output elements will be summed.
52
+
53
+ Raises:
54
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
55
+
56
+ Supported Platforms:
57
+ ``Ascend`` ``GPU`` ``CPU``
58
+
59
+ Examples:
60
+ >>> import mindspore
61
+ >>> from mindspore import ops, Tensor, nn
62
+ >>> import numpy as np
63
+ >>>
64
+ >>> class Net(nn.LossBase):
65
+ ... def __init__(self, reduction='mean'):
66
+ ... super(Net, self).__init__(reduction)
67
+ ... self.abs = ops.Abs()
68
+ ...
69
+ ... def construct(self, logits, labels):
70
+ ... x = self.abs(logits - labels)
71
+ ... output = self.get_loss(x)
72
+ ... axis = self.get_axis(x)
73
+ ... return output, axis
74
+ >>> net = Net()
75
+ >>> # Case 1: logits.shape = labels.shape = (3,)
76
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
77
+ >>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
78
+ >>> output, axis = net(logits, labels)
79
+ >>> print(output)
80
+ 0.33333334
81
+ >>> print(axis)
82
+ (0,)
83
+ >>> # Case 2: logits.shape = labels.shape = (3, 3)
84
+ >>> logits = Tensor(np.array([[1, 2, 3],[1, 2, 3],[1, 2, 3]]), mindspore.float32)
85
+ >>> labels = Tensor(np.array([[1, 2, 2],[1, 2, 3],[1, 2, 3]]), mindspore.float32)
86
+ >>> output, axis = net(logits, labels)
87
+ >>> print(output)
88
+ 0.11111111
89
+ >>> print(axis)
90
+ (0, 1)
91
+ """
92
+
93
+ def __init__(self, reduction='mean'):
94
+ """Initialize Loss."""
95
+ super(LossBase, self).__init__()
96
+
97
+ if reduction not in ('mean', 'sum', 'none'):
98
+ raise ValueError(f"For '{self.cls_name}', the 'reduction' must be in ['mean', 'sum', 'none'], "
99
+ f"but got {reduction}.")
100
+
101
+ self.average = True
102
+ self.reduce = True
103
+ if reduction == 'sum':
104
+ self.average = False
105
+ if reduction == 'none':
106
+ self.reduce = False
107
+
108
+ self.reduce_mean = P.ReduceMean()
109
+ self.reduce_sum = P.ReduceSum()
110
+ self.mul = P.Mul()
111
+ self.cast = P.Cast()
112
+
113
+ def get_axis(self, x):
114
+ """
115
+ Get a range of axis for input.
116
+
117
+ Args:
118
+ x (Tensor): Tensor of any shape.
119
+ """
120
+ shape = F.shape(x)
121
+ length = F.tuple_len(shape)
122
+ perm = F.make_range(0, length)
123
+ return perm
124
+
125
+ def get_loss(self, x, weights=1.0):
126
+ """
127
+ Computes the weighted loss.
128
+
129
+ Args:
130
+ x (Tensor): Tensor of shape :math:`(N, *)` where :math:`*` means, any number of
131
+ additional dimensions.
132
+ weights (Union[float, Tensor]): Optional `Tensor` whose rank is either 0, or the same rank as inputs,
133
+ and must be broadcastable to inputs (i.e., all dimensions must be either `1`,
134
+ or the same as the corresponding inputs dimension). Default: ``1.0`` .
135
+
136
+ Returns:
137
+ Return the weighted loss.
138
+ """
139
+ input_dtype = x.dtype
140
+ x = self.cast(x, mstype.float32)
141
+ weights = self.cast(weights, mstype.float32)
142
+ x = self.mul(weights, x)
143
+ if self.reduce and self.average:
144
+ x = self.reduce_mean(x, self.get_axis(x))
145
+ if self.reduce and not self.average:
146
+ x = self.reduce_sum(x, self.get_axis(x))
147
+ x = self.cast(x, input_dtype)
148
+ return x
149
+
150
+ def construct(self, logits, labels):
151
+ raise NotImplementedError
152
+
153
+
154
+ class _Loss(LossBase):
155
+ """
156
+ Base class for other losses.
157
+ """
158
+
159
+ def __init__(self, reduction='mean'):
160
+ """Initialize _Loss."""
161
+ log.warning("'_Loss' is deprecated from version 1.3 and "
162
+ "will be removed in a future version, use 'LossBase' instead.")
163
+ super(_Loss, self).__init__(reduction)
164
+
165
+ def construct(self, logits, labels):
166
+ raise NotImplementedError
167
+
168
+
169
+ @constexpr(check=False)
170
+ def _check_is_tensor(param_name, input_data, cls_name):
171
+ """Internal function, used to check whether the input data is Tensor."""
172
+ if input_data is not None and not isinstance(F.typeof(input_data), mstype.TensorType):
173
+ raise TypeError(f"For '{cls_name}', the '{param_name}' must be '{mstype.TensorType}', "
174
+ f"but got '{F.typeof(input_data)}'")
175
+
176
+
177
+ class L1Loss(LossBase):
178
+ r"""
179
+ L1Loss is used to calculate the mean absolute error between the predicted value and the target value.
180
+
181
+ Assuming that the :math:`x` and :math:`y` are 1-D Tensor, length :math:`N`, then calculate the loss of :math:`x` and
182
+ :math:`y` without dimensionality reduction (the reduction parameter is set to "none"). The formula is as follows:
183
+
184
+ .. math::
185
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad \text{with } l_n = \left| x_n - y_n \right|,
186
+
187
+ where :math:`N` is the batch size. If `reduction` is not ``'none'``, then:
188
+
189
+ .. math::
190
+ \ell(x, y) =
191
+ \begin{cases}
192
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
193
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
194
+ \end{cases}
195
+
196
+ Args:
197
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
198
+ ``'sum'`` . Default: ``'mean'`` .
199
+
200
+ - ``'none'``: no reduction will be applied.
201
+ - ``'mean'``: compute and return the mean of elements in the output.
202
+ - ``'sum'``: the output elements will be summed.
203
+
204
+ Inputs:
205
+ - **logits** (Tensor) - Predicted value, Tensor of any dimension.
206
+ - **labels** (Tensor) - Target value, same shape as the `logits` in common cases.
207
+ However, it supports the shape of `logits` is different from the shape of `labels`
208
+ and they should be broadcasted to each other.
209
+
210
+ Outputs:
211
+ Tensor, data type is float.
212
+
213
+ Raises:
214
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
215
+ ValueError: If `logits` and `labels` have different shapes and cannot be broadcasted to each other.
216
+
217
+ Supported Platforms:
218
+ ``Ascend`` ``GPU`` ``CPU``
219
+
220
+ Examples:
221
+ >>> import mindspore
222
+ >>> from mindspore import Tensor, nn
223
+ >>> import numpy as np
224
+ >>> # Case 1: logits.shape = labels.shape = (3,)
225
+ >>> loss = nn.L1Loss()
226
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
227
+ >>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
228
+ >>> output = loss(logits, labels)
229
+ >>> print(output)
230
+ 0.33333334
231
+ >>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
232
+ >>> loss = nn.L1Loss(reduction='none')
233
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
234
+ >>> labels = Tensor(np.array([[1, 1, 1], [1, 2, 2]]), mindspore.float32)
235
+ >>> output = loss(logits, labels)
236
+ >>> print(output)
237
+ [[0. 1. 2.]
238
+ [0. 0. 1.]]
239
+ """
240
+
241
+ def __init__(self, reduction='mean'):
242
+ """Initialize L1Loss."""
243
+ super(L1Loss, self).__init__(reduction)
244
+ self.reduction = reduction
245
+
246
+ def construct(self, logits, labels):
247
+ return F.l1_loss(logits, labels, self.reduction)
248
+
249
+
250
+ class MSELoss(LossBase):
251
+ r"""
252
+ Calculates the mean squared error between the predicted value and the label value.
253
+
254
+ For simplicity, let :math:`x` and :math:`y` be 1-dimensional Tensor with length :math:`N`,
255
+ the unreduced loss (i.e. with argument reduction set to 'none') of :math:`x` and :math:`y` is given as:
256
+
257
+ .. math::
258
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad \text{with} \quad l_n = (x_n - y_n)^2.
259
+
260
+ where :math:`N` is the batch size. If `reduction` is not ``'none'``, then:
261
+
262
+ .. math::
263
+ \ell(x, y) =
264
+ \begin{cases}
265
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
266
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
267
+ \end{cases}
268
+
269
+ Args:
270
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
271
+ ``'sum'`` . Default: ``'mean'`` .
272
+
273
+ - ``'none'``: no reduction will be applied.
274
+ - ``'mean'``: compute and return the mean of elements in the output.
275
+ - ``'sum'``: the output elements will be summed.
276
+
277
+ Inputs:
278
+ - **logits** (Tensor) - The predicted value of the input. Tensor of any dimension.
279
+ - **labels** (Tensor) - The input label. Tensor of any dimension, same shape as the `logits` in common cases.
280
+ However, it supports the shape of `logits` is different from the shape of `labels`
281
+ and they should be broadcasted to each other.
282
+
283
+ Outputs:
284
+ Tensor, loss of type float, the shape is zero if `reduction` is ``'mean'`` or ``'sum'`` ,
285
+ while the shape of output is the broadcasted shape if `reduction` is 'none'.
286
+
287
+ Raises:
288
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'`` or ``'sum'``.
289
+ ValueError: If `logits` and `labels` have different shapes and cannot be broadcasted.
290
+
291
+ Supported Platforms:
292
+ ``Ascend`` ``GPU`` ``CPU``
293
+
294
+ Examples:
295
+ >>> import mindspore
296
+ >>> from mindspore import Tensor, nn
297
+ >>> import numpy as np
298
+ >>> # Case 1: logits.shape = labels.shape = (3,)
299
+ >>> loss = nn.MSELoss()
300
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
301
+ >>> labels = Tensor(np.array([1, 1, 1]), mindspore.float32)
302
+ >>> output = loss(logits, labels)
303
+ >>> print(output)
304
+ 1.6666667
305
+ >>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
306
+ >>> loss = nn.MSELoss(reduction='none')
307
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
308
+ >>> labels = Tensor(np.array([[1, 1, 1], [1, 2, 2]]), mindspore.float32)
309
+ >>> output = loss(logits, labels)
310
+ >>> print(output)
311
+ [[0. 1. 4.]
312
+ [0. 0. 1.]]
313
+ """
314
+
315
+ def construct(self, logits, labels):
316
+ _check_is_tensor('logits', logits, self.cls_name)
317
+ _check_is_tensor('labels', labels, self.cls_name)
318
+ x = F.square(logits - labels)
319
+ return self.get_loss(x)
320
+
321
+
322
+ @constexpr
323
+ def _check_rmseloss_dtype(param_dtype, not_supported_dtype, cls_name):
324
+ """Check RMSELoss not supported data type"""
325
+ if param_dtype in not_supported_dtype:
326
+ raise TypeError(f"For '{cls_name}', the parameters data type must not be in {not_supported_dtype}, "
327
+ f"but got mindspore.{str(param_dtype).lower()}.")
328
+
329
+
330
+ class RMSELoss(LossBase):
331
+ r"""
332
+ RMSELoss creates a criterion to measure the root mean square error between :math:`x` and :math:`y`
333
+ element-wise, where :math:`x` is the input and :math:`y` is the labels.
334
+
335
+ For simplicity, let :math:`x` and :math:`y` be 1-dimensional Tensor with length :math:`N`,
336
+ the loss of :math:`x` and :math:`y` is given as:
337
+
338
+ .. math::
339
+ loss = \sqrt{\frac{1}{N}\sum_{i=1}^{N}{(x_i-y_i)^2}}
340
+
341
+ Inputs:
342
+ - **logits** (Tensor) - Tensor of shape :math:`(N, *)` where :math:`*` means, any number of
343
+ additional dimensions.
344
+ - **labels** (Tensor) - Tensor of shape :math:`(N, *)`, same shape as the `logits` in common cases.
345
+ However, it supports the shape of `logits` is different from the shape of `labels`
346
+ and they should be broadcasted to each other.
347
+
348
+ Outputs:
349
+ Tensor, weighted loss float tensor and its shape is :math:`()`.
350
+
351
+ Supported Platforms:
352
+ ``Ascend`` ``GPU`` ``CPU``
353
+
354
+ Examples:
355
+ >>> import mindspore
356
+ >>> from mindspore import Tensor, nn
357
+ >>> import numpy as np
358
+ >>> # Case 1: logits.shape = labels.shape = (3,)
359
+ >>> loss = nn.RMSELoss()
360
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
361
+ >>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
362
+ >>> output = loss(logits, labels)
363
+ >>> print(output)
364
+ 0.57735026
365
+ >>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
366
+ >>> loss = nn.RMSELoss()
367
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
368
+ >>> labels = Tensor(np.array([[1, 1, 1], [1, 2, 2]]), mindspore.float32)
369
+ >>> output = loss(logits, labels)
370
+ >>> print(output)
371
+ 1.0
372
+ """
373
+
374
+ def __init__(self):
375
+ """Initialize RMSELoss."""
376
+ super(RMSELoss, self).__init__()
377
+ self.dtype = P.DType()
378
+ self.MSELoss = MSELoss()
379
+
380
+ def construct(self, logits, label):
381
+ logits_dtype = self.dtype(logits)
382
+ label_dtype = self.dtype(label)
383
+ not_supported_dtype = [mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64]
384
+ _check_rmseloss_dtype(logits_dtype, not_supported_dtype, 'RMSELoss')
385
+ _check_rmseloss_dtype(label_dtype, not_supported_dtype, "RMSELoss")
386
+
387
+ rmse_loss = F.sqrt(self.MSELoss(logits, label))
388
+
389
+ return rmse_loss
390
+
391
+
392
+ class MAELoss(LossBase):
393
+ r"""
394
+ MAELoss creates a criterion to measure the average absolute error between :math:`x` and :math:`y`
395
+ element-wise, where :math:`x` is the input and :math:`y` is the labels.
396
+
397
+ For simplicity, let :math:`x` and :math:`y` be 1-dimensional Tensor with length :math:`N`,
398
+ the unreduced loss (i.e. with argument reduction set to 'none') of :math:`x` and :math:`y` is given as:
399
+
400
+ .. math::
401
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad \text{with } l_n = \left| x_n - y_n \right|
402
+
403
+ where :math:`N` is the batch size. If `reduction` is not ``'none'``, then:
404
+
405
+ .. math::
406
+ \ell(x, y) =
407
+ \begin{cases}
408
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
409
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
410
+ \end{cases}
411
+
412
+ Args:
413
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
414
+ ``'sum'`` . Default: ``'mean'`` .
415
+
416
+ - ``'none'``: no reduction will be applied.
417
+ - ``'mean'``: compute and return the mean of elements in the output.
418
+ - ``'sum'``: the output elements will be summed.
419
+
420
+ Inputs:
421
+ - **logits** (Tensor) - Tensor of shape :math:`(M, *)` where :math:`*` means, any number of
422
+ additional dimensions.
423
+ - **labels** (Tensor) - Tensor of shape :math:`(N, *)`, same shape as the `logits` in common cases.
424
+ However, it supports the shape of `logits` is different from the shape of `labels`
425
+ and they should be broadcasted to each other.
426
+
427
+ Outputs:
428
+ Tensor, weighted loss float tensor, the shape is zero if `reduction` is ``'mean'`` or ``'sum'`` .,
429
+ while the shape of output is the broadcasted shape if `reduction` is 'none'.
430
+
431
+ Raises:
432
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
433
+
434
+ Supported Platforms:
435
+ ``Ascend`` ``GPU`` ``CPU``
436
+
437
+ Examples:
438
+ >>> import mindspore
439
+ >>> from mindspore import Tensor, nn
440
+ >>> import numpy as np
441
+ >>> # Case 1: logits.shape = labels.shape = (3,)
442
+ >>> loss = nn.MAELoss()
443
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
444
+ >>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
445
+ >>> output = loss(logits, labels)
446
+ >>> print(output)
447
+ 0.33333334
448
+ >>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
449
+ >>> loss = nn.MAELoss(reduction='none')
450
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
451
+ >>> labels = Tensor(np.array([[1, 1, 1], [1, 2, 2]]), mindspore.float32)
452
+ >>> output = loss(logits, labels)
453
+ >>> print(output)
454
+ [[0. 1. 2.]
455
+ [0. 0. 1.]]
456
+ """
457
+
458
+ def __init__(self, reduction='mean'):
459
+ """Initialize MAELoss."""
460
+ super(MAELoss, self).__init__(reduction)
461
+ self.abs = P.Abs()
462
+
463
+ def construct(self, logits, label):
464
+ _check_is_tensor('logits', logits, self.cls_name)
465
+ _check_is_tensor('labels', label, self.cls_name)
466
+ x = self.abs(logits - label)
467
+ return self.get_loss(x)
468
+
469
+
470
+ class MarginRankingLoss(LossBase):
471
+ r"""
472
+ MarginRankingLoss creates a criterion that measures the loss.
473
+
474
+ Given two tensors :math:`input1`, :math:`input2` and a Tensor label :math:`target` with values 1 or -1,
475
+ the operation is as follows:
476
+
477
+ .. math::
478
+ \text{loss}(input1, input2, target) = \max(0, -target * (input1 - input2) + \text{margin})
479
+
480
+ Args:
481
+ margin (float, optional): Specify the adjustment factor of the operation. Default: ``0.0`` .
482
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
483
+ ``'sum'`` . Default: ``'mean'`` .
484
+
485
+ - ``'none'``: no reduction will be applied.
486
+ - ``'mean'``: compute and return the mean of elements in the output.
487
+ - ``'sum'``: the output elements will be summed.
488
+
489
+ Inputs:
490
+ - **input1** (Tensor) - Tensor of shape :math:`(N, *)` where :math:`*` means, any number
491
+ of additional dimensions.
492
+ - **input2** (Tensor) - Tensor of shape :math:`(N, *)`, same shape and dtype as `input1`.
493
+ - **target** (Tensor) - Contains value 1 or -1. Suppose the shape of `input1` is
494
+ :math:`(x_1, x_2, x_3, ..., x_R)`, then the shape of `target` must be :math:`(x_1, x_2, x_3, ..., x_R)`.
495
+
496
+ Outputs:
497
+ Tensor or Scalar. if `reduction` is ``'none'``, its shape is the same as `input1`.
498
+ Otherwise, a scalar value will be returned.
499
+
500
+ Raises:
501
+ TypeError: If `margin` is not a float.
502
+ TypeError: If `input1`, `input2` or `target` is not a Tensor.
503
+ TypeError: If the types of `input1` and `input2` are inconsistent.
504
+ TypeError: If the types of `input1` and `target` are inconsistent.
505
+ ValueError: If the shape of `input1` and `input2` are inconsistent.
506
+ ValueError: If the shape of `input1` and `target` are inconsistent.
507
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'`` , ``'sum'``.
508
+
509
+ Supported Platforms:
510
+ ``Ascend`` ``GPU`` ``CPU``
511
+
512
+ Examples:
513
+ >>> import mindspore as ms
514
+ >>> from mindspore import Tensor, nn, ops
515
+ >>> import numpy as np
516
+ >>> loss1 = nn.MarginRankingLoss(reduction='none')
517
+ >>> loss2 = nn.MarginRankingLoss(reduction='mean')
518
+ >>> loss3 = nn.MarginRankingLoss(reduction='sum')
519
+ >>> sign = ops.Sign()
520
+ >>> input1 = Tensor(np.array([0.3864, -2.4093, -1.4076]), ms.float32)
521
+ >>> input2 = Tensor(np.array([-0.6012, -1.6681, 1.2928]), ms.float32)
522
+ >>> target = sign(Tensor(np.array([-2, -2, 3]), ms.float32))
523
+ >>> output1 = loss1(input1, input2, target)
524
+ >>> print(output1)
525
+ [0.98759997 0. 2.7003999 ]
526
+ >>> output2 = loss2(input1, input2, target)
527
+ >>> print(output2)
528
+ 1.2293333
529
+ >>> output3 = loss3(input1, input2, target)
530
+ >>> print(output3)
531
+ 3.6879997
532
+ """
533
+
534
+ def __init__(self, margin=0.0, reduction='mean'):
535
+ """Initialize MarginRankingLoss."""
536
+ super(MarginRankingLoss, self).__init__(reduction)
537
+ self.reduction = reduction
538
+ self.margin = margin
539
+
540
+ def construct(self, input1, input2, target):
541
+ x = ops.margin_ranking_loss(input1, input2, target, self.margin, self.reduction)
542
+ return x
543
+
544
+
545
+ class SmoothL1Loss(LossBase):
546
+ r"""
547
+ SmoothL1 loss function, if the absolute error element-wise between the predicted value and the target value
548
+ is less than the set threshold `beta`, the square term is used, otherwise the absolute error term is used.
549
+
550
+ Given two input :math:`x,\ y`, the SmoothL1Loss can be described as follows:
551
+
552
+ .. math::
553
+ L_{i} =
554
+ \begin{cases}
555
+ \frac{0.5 (x_i - y_i)^{2}}{\beta}, & \text{if } |x_i - y_i| < {\beta} \\
556
+ |x_i - y_i| - 0.5 {\beta}, & \text{otherwise.}
557
+ \end{cases}
558
+
559
+ Where :math:`{\beta}` represents the threshold `beta`.
560
+
561
+ If `reduction` is not `none`, then:
562
+
563
+ .. math::
564
+ L =
565
+ \begin{cases}
566
+ \operatorname{mean}(L_{i}), & \text{if reduction} = \text{'mean';}\\
567
+ \operatorname{sum}(L_{i}), & \text{if reduction} = \text{'sum'.}
568
+ \end{cases}
569
+
570
+ .. note::
571
+ - SmoothL1Loss can be regarded as modified version of :class:`mindspore.nn.L1Loss`
572
+ or a combination of :class:`mindspore.nn.L1Loss` and :class:`mindspore.ops.L2Loss`.
573
+ - :class:`mindspore.nn.L1Loss` computes the element-wise absolute difference between two input tensor
574
+ while :class:`mindspore.ops.L2Loss` computes the
575
+ - squared difference between two input tensors. :class:`mindspore.ops.L2Loss`
576
+ often leads to faster convergence but it is less
577
+ robust to outliers, and the loss function has better robustness.
578
+
579
+ Args:
580
+ beta (float): The loss function calculates the threshold of the transformation between L1Loss and L2Loss.
581
+ Default: ``1.0`` .
582
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
583
+ ``'sum'`` . Default: ``'none'`` .
584
+
585
+ - ``'none'``: no reduction will be applied.
586
+ - ``'mean'``: compute and return the mean of elements in the output.
587
+ - ``'sum'``: the output elements will be summed.
588
+
589
+ Inputs:
590
+ - **logits** (Tensor) - Predictive value. Tensor of any dimension. Data type must be one of float16 or
591
+ float32.
592
+ - **labels** (Tensor) - Ground truth data, same shape and dtype as the `logits`.
593
+
594
+ Outputs:
595
+ Tensor, if `reduction` is ``'none'``, then output is a tensor with the same shape as `logits`.
596
+ Otherwise the shape of output tensor is :math:`()`.
597
+
598
+ Raises:
599
+ TypeError: If `beta` is not a float.
600
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
601
+ TypeError: If `logits` or `labels` are not Tensor.
602
+ TypeError: If dtype of `logits` or `labels` is neither float16 not float32.
603
+ TypeError: If dtype of `logits` is not the same as `labels`.
604
+ ValueError: If `beta` is less than or equal to 0.
605
+ ValueError: If shape of `logits` is not the same as `labels`.
606
+
607
+ Supported Platforms:
608
+ ``Ascend`` ``GPU`` ``CPU``
609
+
610
+ Examples:
611
+ >>> import mindspore
612
+ >>> from mindspore import Tensor, nn
613
+ >>> import numpy as np
614
+ >>> loss = nn.SmoothL1Loss()
615
+ >>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
616
+ >>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
617
+ >>> output = loss(logits, labels)
618
+ >>> print(output)
619
+ [0. 0. 0.5]
620
+ """
621
+
622
+ def __init__(self, beta=1.0, reduction='none'):
623
+ """Initialize SmoothL1Loss."""
624
+ super(SmoothL1Loss, self).__init__(reduction)
625
+ self.beta = beta
626
+ self.reduction = reduction
627
+ self.smooth_l1_loss = P.SmoothL1Loss(self.beta, self.reduction)
628
+
629
+ def construct(self, logits, labels):
630
+ return self.smooth_l1_loss(logits, labels)
631
+
632
+
633
+ class SoftMarginLoss(LossBase):
634
+ r"""
635
+ A loss class for two-class classification problems.
636
+
637
+ SoftMarginLoss creates a criterion that optimizes a two-class classification
638
+ logistic loss between input tensor :math:`x` and labels tensor :math:`y`
639
+ (containing 1 or -1).
640
+
641
+ .. math::
642
+ \text{loss}(x, y) = \sum_i \frac{\log(1 + \exp(-y[i]*x[i]))}{x.nelement()}
643
+
644
+ :math:`x.nelement()` represents the number of element of `x` .
645
+
646
+ Args:
647
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
648
+ ``'sum'`` . Default: ``'mean'`` .
649
+
650
+ - ``'none'``: no reduction will be applied.
651
+ - ``'mean'``: compute and return the mean of elements in the output.
652
+ - ``'sum'``: the output elements will be summed.
653
+
654
+ Inputs:
655
+ - **logits** (Tensor) - Predict data. Data type must be float16 or float32.
656
+ - **labels** (Tensor) - Ground truth data, with the same type and shape as `logits`.
657
+
658
+ Outputs:
659
+ Tensor or Scalar, if `reduction` is ``"none"``, its shape is the same as `logits`.
660
+ Otherwise, a scalar value will be returned.
661
+
662
+ Raises:
663
+ TypeError: If `logits` or `labels` is not a Tensor.
664
+ TypeError: If dtype of `logits` or `labels` is neither float16 nor float32.
665
+ ValueError: If shape of `logits` is not the same as `labels`.
666
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
667
+
668
+ Supported Platforms:
669
+ ``Ascend`` ``GPU``
670
+
671
+ Examples:
672
+ >>> import mindspore
673
+ >>> from mindspore import Tensor, nn
674
+ >>> import numpy as np
675
+ >>> loss = nn.SoftMarginLoss()
676
+ >>> logits = Tensor(np.array([[0.3, 0.7], [0.5, 0.5]]), mindspore.float32)
677
+ >>> labels = Tensor(np.array([[-1, 1], [1, -1]]), mindspore.float32)
678
+ >>> output = loss(logits, labels)
679
+ >>> print(output)
680
+ 0.6764238
681
+ """
682
+
683
+ def __init__(self, reduction='mean'):
684
+ super(SoftMarginLoss, self).__init__()
685
+ self.soft_margin_loss = P.SoftMarginLoss(reduction)
686
+
687
+ def construct(self, logits, labels):
688
+ return self.soft_margin_loss(logits, labels)
689
+
690
+
691
+ class SoftmaxCrossEntropyWithLogits(LossBase):
692
+ r"""
693
+ Computes softmax cross entropy between logits and labels.
694
+
695
+ Measures the distribution error between the probabilities of the input (computed with softmax function) and the
696
+ labels where the classes are mutually exclusive (only one class is positive) using cross entropy loss.
697
+
698
+ Typical input into this function is unnormalized scores denoted as :math:`x` whose shape is :math:`(N, C)` ,
699
+ and the corresponding targets.
700
+
701
+ Typically, the input to this function is the fractional value of each category and the corresponding target value,
702
+ and the input format is :math:`(N, C)` .
703
+
704
+ For each instance :math:`x_i`, :math:`i` ranges from 0 to N-1, the loss is given as:
705
+
706
+ .. math::
707
+ \ell(x_i, c) = - \log\left(\frac{\exp(x_i[c])}{\sum_j \exp(x_i[j])}\right)
708
+ = -x_i[c] + \log\left(\sum_j \exp(x_i[j])\right)
709
+
710
+ where :math:`x_i` is a 1D score Tensor, :math:`c` is the index of 1 in one-hot.
711
+
712
+ Note:
713
+ While the labels classes are mutually exclusive, i.e., only one class is positive in the labels, the predicted
714
+ probabilities does not need to be exclusive. It is only required that the predicted probability distribution
715
+ of entry is a valid one.
716
+
717
+ Args:
718
+ sparse (bool, optional): Specifies whether labels use sparse format or not. Default: ``False`` .
719
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
720
+ ``'sum'`` . Default: ``'none'`` .
721
+
722
+ - ``'none'``: no reduction will be applied.
723
+ - ``'mean'``: compute and return the mean of elements in the output.
724
+ - ``'sum'``: the output elements will be summed.
725
+
726
+ Inputs:
727
+ - **logits** (Tensor) - Tensor of shape :math:`(N, C)` . Data type must be float16 or float32.
728
+ - **labels** (Tensor) - Tensor of shape :math:`(N, )` . If `sparse` is True, The type of
729
+ `labels` is int32 or int64. Otherwise, the type of `labels` is the same as the type of `logits`.
730
+
731
+ Outputs:
732
+ Tensor, a tensor of the same shape and type as logits with the component-wise logistic losses.
733
+
734
+ Raises:
735
+ TypeError: If `sparse` is not a bool.
736
+ TypeError: If `sparse` is True and dtype of `labels` is neither int32 nor int64.
737
+ TypeError: If `sparse` is False and dtype of `labels` is neither float16 not float32.
738
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
739
+
740
+ Supported Platforms:
741
+ ``Ascend`` ``GPU`` ``CPU``
742
+
743
+ Examples:
744
+ >>> import mindspore
745
+ >>> from mindspore import Tensor, nn
746
+ >>> import numpy as np
747
+ >>> # case 1: sparse=True
748
+ >>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
749
+ >>> logits = Tensor(np.array([[3, 5, 6, 9, 12, 33, 42, 12, 32, 72]]), mindspore.float32)
750
+ >>> labels_np = np.array([1]).astype(np.int32)
751
+ >>> labels = Tensor(labels_np)
752
+ >>> output = loss(logits, labels)
753
+ >>> print(output)
754
+ [67.]
755
+ >>> # case 2: sparse=False
756
+ >>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
757
+ >>> logits = Tensor(np.array([[3, 5, 6, 9, 12, 33, 42, 12, 32, 72]]), mindspore.float32)
758
+ >>> labels_np = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]]).astype(np.float32)
759
+ >>> labels = Tensor(labels_np)
760
+ >>> output = loss(logits, labels)
761
+ >>> print(output)
762
+ [30.]
763
+ """
764
+
765
+ def __init__(self,
766
+ sparse=False,
767
+ reduction='none'):
768
+ """Initialize SoftmaxCrossEntropyWithLogits."""
769
+ super(SoftmaxCrossEntropyWithLogits, self).__init__(reduction)
770
+ self.sparse = validator.check_bool(sparse, "sparse", self.cls_name)
771
+ self.reduction = reduction
772
+ self.softmax_cross_entropy = P.SoftmaxCrossEntropyWithLogits()
773
+ self.one_hot = P.OneHot()
774
+ self.on_value = Tensor(1.0, mstype.float32)
775
+ self.off_value = Tensor(0., mstype.float32)
776
+ self.is_cpugpu = context.get_context('device_target') in ["CPU", "GPU"]
777
+ self.sparse_softmax_cross_entropy = P.SparseSoftmaxCrossEntropyWithLogits()
778
+
779
+ def construct(self, logits, labels):
780
+ _check_is_tensor('logits', logits, self.cls_name)
781
+ _check_is_tensor('labels', labels, self.cls_name)
782
+ if self.sparse:
783
+ if self.reduction == 'mean':
784
+ x = self.sparse_softmax_cross_entropy(logits, labels)
785
+ return x
786
+ labels = self.one_hot(labels, F.shape(logits)[-1], self.on_value, self.off_value)
787
+ x = self.softmax_cross_entropy(logits, labels)[0]
788
+ return self.get_loss(x)
789
+
790
+
791
+ @_primexpr
792
+ def _check_dice_shape(logits_shape, label_shape, prim_name=None):
793
+ """Internal function, check whether the shape of logits and labels meets the requirements."""
794
+ validator.check('logits_shape', logits_shape, 'label_shape', label_shape, prim_name=prim_name)
795
+
796
+
797
+ @constexpr
798
+ def _check_label_dtype(labels_dtype, cls_name):
799
+ """Internal function, used to check whether the data type of labels meets the requirements."""
800
+ validator.check_type_name("labels", labels_dtype, [mstype.int32, mstype.int64], cls_name)
801
+
802
+
803
+ class DiceLoss(LossBase):
804
+ r"""
805
+ The Dice coefficient is a set similarity loss, which is used to calculate the similarity between two samples. The
806
+ value of the Dice coefficient is 1 when the segmentation result is the best and is 0 when the segmentation result
807
+ is the worst. The Dice coefficient indicates the ratio of the area between two objects to the total area.
808
+ The function is shown as follows:
809
+
810
+ .. math::
811
+ dice = 1 - \frac{2 * |pred \bigcap true|}{|pred| + |true| + smooth}
812
+
813
+ :math:`pred` represent `logits`, :math:`true` represent `labels` .
814
+
815
+ Args:
816
+ smooth (float): A term added to the denominator to improve numerical stability. Should be greater than 0.
817
+ Default: ``1e-5`` .
818
+
819
+ Inputs:
820
+ - **logits** (Tensor) - Input predicted value. The data type must be float16 or float32.
821
+ - **labels** (Tensor) - Input target value. Same shape as the `logits`.
822
+ The data type must be float16 or float32.
823
+
824
+ Outputs:
825
+ Tensor, a tensor of shape with the per-example sampled Dice losses.
826
+
827
+ Raises:
828
+ ValueError: If the dimension of `logits` is different from `labels`.
829
+ TypeError: If the type of `logits` or `labels` is not a tensor.
830
+
831
+ Supported Platforms:
832
+ ``Ascend`` ``GPU`` ``CPU``
833
+
834
+ Examples:
835
+ >>> import mindspore
836
+ >>> from mindspore import Tensor, nn
837
+ >>> import numpy as np
838
+ >>> loss = nn.DiceLoss(smooth=1e-5)
839
+ >>> logits = Tensor(np.array([[0.2, 0.5], [0.3, 0.1], [0.9, 0.6]]), mindspore.float32)
840
+ >>> labels = Tensor(np.array([[0, 1], [1, 0], [0, 1]]), mindspore.float32)
841
+ >>> output = loss(logits, labels)
842
+ >>> print(output)
843
+ 0.38596618
844
+ """
845
+
846
+ def __init__(self, smooth=1e-5):
847
+ """Initialize DiceLoss."""
848
+ super(DiceLoss, self).__init__()
849
+ self.smooth = validator.check_positive_float(smooth, "smooth")
850
+ self.reshape = P.Reshape()
851
+
852
+ def construct(self, logits, label):
853
+ _check_is_tensor('logits', logits, self.cls_name)
854
+ _check_is_tensor('labels', label, self.cls_name)
855
+ _check_dice_shape(logits.shape, label.shape, self.cls_name)
856
+ if logits.dtype == mstype.uint8:
857
+ raise TypeError(f"For '{self.cls_name}', the dtype of 'logits' can not be uint8.")
858
+ if label.dtype == mstype.uint8:
859
+ raise TypeError(f"For '{self.cls_name}', the dtype of 'labels' can not be uint8.")
860
+ intersection = self.reduce_sum(self.mul(logits.view(-1), label.view(-1)))
861
+ unionset = self.reduce_sum(self.mul(logits.view(-1), logits.view(-1))) + \
862
+ self.reduce_sum(self.mul(label.view(-1), label.view(-1)))
863
+
864
+ single_dice_coeff = (2 * intersection) / (unionset + self.smooth)
865
+ dice_loss = 1 - single_dice_coeff
866
+
867
+ return dice_loss
868
+
869
+
870
+ @_primexpr
871
+ def _check_shape(logits_shape, label_shape, prim_name=None):
872
+ """Internal function, used to check whether the shape of logits and labels meets the requirements."""
873
+ validator.check('logits_shape', logits_shape, 'label_shape', label_shape, prim_name=prim_name)
874
+
875
+
876
+ @_primexpr
877
+ def _check_ndim_multi(logits_dim, label_dim, prim_name=None):
878
+ """Internal function, used to check whether the dimension of logits and label meets the requirements."""
879
+ msg_prefix = f'For \'{prim_name}\', the' if prim_name else "The"
880
+ if logits_dim < 2:
881
+ raise ValueError(f"{msg_prefix} 'logits' dimension must be greater than 1, but got {logits_dim}.")
882
+ if label_dim < 2:
883
+ raise ValueError(f"{msg_prefix} 'labels' dimension must be greater than 1, but got {label_dim}.")
884
+
885
+
886
+ @_primexpr
887
+ def _check_weights(weight_shape, label_shape, prim_name=None):
888
+ """Internal function, used to check whether the reduced shape meets the requirements."""
889
+ msg_prefix = f'For \'{prim_name}\', the' if prim_name else "The"
890
+ if weight_shape != label_shape:
891
+ raise ValueError(f"{msg_prefix} weight_shape[0] must be equal to label_shape[1], "
892
+ f"but got weight_shape[0]: {weight_shape} and label_shape[1]: {label_shape}.")
893
+
894
+
895
+ class MultiClassDiceLoss(LossBase):
896
+ r"""
897
+ When there are multiple classifications, label is transformed into multiple binary classifications by one hot.
898
+ For each channel section in the channel, it can be regarded as a binary classification problem, so it can be
899
+ obtained through the binary :class:`mindspore.nn.DiceLoss` losses of each category,
900
+ and then the average value of the binary losses.
901
+
902
+ Args:
903
+ weights (Union[Tensor, None]): Tensor of shape :math:`(num\_classes, dim)`. The weight shape[0] should be
904
+ equal to labels shape[1].
905
+ Default: ``None`` .
906
+ ignore_indiex (Union[int, None]): Class index to ignore.
907
+ Default: ``None`` .
908
+ activation (Union[str, Cell]): Activate function applied to the output of the fully connected layer, eg. 'ReLU'.
909
+ Default: ``'softmax'`` . Choose from: [ ``'softmax'`` , ``'logsoftmax'`` , ``'relu'`` , ``'relu6'`` ,
910
+ ``'tanh'`` , ``'Sigmoid'`` ]
911
+
912
+ Inputs:
913
+ - **logits** (Tensor) - Tensor of shape :math:`(N, C, *)` where :math:`*` means, any number of additional
914
+ dimensions. The logits dimension should be greater than 1. The data type must be float16 or float32.
915
+ - **labels** (Tensor) - Tensor of shape :math:`(N, C, *)`, same shape as the `logits`.
916
+ The labels dimension should be greater than 1. The data type must be float16 or float32.
917
+
918
+ Outputs:
919
+ Tensor, a tensor of shape with the per-example sampled MultiClass Dice Losses.
920
+
921
+ Raises:
922
+ ValueError: If the shape of `logits` is different from `labels`.
923
+ TypeError: If the type of `logits` or `labels` is not a tensor.
924
+ ValueError: If the dimension of `logits` or `labels` is less than 2.
925
+ ValueError: If the weights.shape[0] is not equal to labels.shape[1].
926
+ ValueError: If `weights` is a tensor, but its dimension is not 2.
927
+
928
+ Supported Platforms:
929
+ ``Ascend`` ``GPU`` ``CPU``
930
+
931
+ Examples:
932
+ >>> import mindspore
933
+ >>> from mindspore import Tensor, nn
934
+ >>> import numpy as np
935
+ >>> loss = nn.MultiClassDiceLoss(weights=None, ignore_indiex=None, activation="softmax")
936
+ >>> logits = Tensor(np.array([[0.2, 0.5, 0.7], [0.3, 0.1, 0.5], [0.9, 0.6, 0.3]]), mindspore.float32)
937
+ >>> labels = Tensor(np.array([[0, 1, 0], [1, 0, 0], [0, 0, 1]]), mindspore.float32)
938
+ >>> output = loss(logits, labels)
939
+ >>> print(output)
940
+ 0.54958105
941
+ """
942
+
943
+ def __init__(self, weights=None, ignore_indiex=None, activation="softmax"):
944
+ """Initialize MultiClassDiceLoss."""
945
+ super(MultiClassDiceLoss, self).__init__()
946
+ activation_list = ['softmax', 'logsoftmax', 'relu', 'relu6', 'tanh', 'sigmoid']
947
+
948
+ self.binarydiceloss = DiceLoss(smooth=1e-5)
949
+ self.weights = weights if weights is None else validator.check_value_type("weights", weights, [Tensor])
950
+ if isinstance(self.weights, Tensor) and self.weights.ndim != 2:
951
+ raise ValueError(f"For '{self.cls_name}', the dimension of 'weights' must be 2, "
952
+ f"but got {self.weights.ndim}.")
953
+ self.ignore_indiex = ignore_indiex if ignore_indiex is None else validator.check_value_type("ignore_indiex",
954
+ ignore_indiex,
955
+ [int])
956
+ if isinstance(activation, str) and activation not in activation_list:
957
+ raise ValueError(f"For '{self.cls_name}', the 'activation' must be in {activation_list}, "
958
+ f"but got {activation}.")
959
+
960
+ self.activation = get_activation(activation) if isinstance(activation, str) else activation
961
+ if self.activation is not None and not isinstance(self.activation, Cell):
962
+ raise TypeError(f"For '{self.cls_name}', the 'activation' must be str or Cell, "
963
+ f"but got {type(self.activation)}.")
964
+ self.reshape = P.Reshape()
965
+
966
+ def construct(self, logits, label):
967
+ _check_is_tensor('logits', logits, self.cls_name)
968
+ _check_is_tensor('labels', label, self.cls_name)
969
+ _check_shape(logits.shape, label.shape, self.cls_name)
970
+ _check_ndim_multi(logits.ndim, label.ndim, self.cls_name)
971
+ total_loss = 0
972
+
973
+ if self.activation is not None:
974
+ logits = self.activation(logits)
975
+
976
+ for i in range(label.shape[1]):
977
+ if i != self.ignore_indiex:
978
+ dice_loss = self.binarydiceloss(logits[:, i], label[:, i])
979
+ if self.weights is not None:
980
+ _check_weights(self.weights.shape[0], label.shape[1], self.cls_name)
981
+ dice_loss *= self.weights[i]
982
+ total_loss += dice_loss
983
+
984
+ return total_loss / label.shape[1]
985
+
986
+
987
+ class SampledSoftmaxLoss(LossBase):
988
+ r"""
989
+ Computes the sampled softmax training loss. This operator can accelerate the training of the softmax classifier
990
+ over a large number of classes. It is generally an underestimate of the full softmax loss.
991
+
992
+ Args:
993
+ num_sampled (int): The number of classes to randomly sample per batch.
994
+ num_classes (int): The number of possible classes.
995
+ num_true (int): The number of labels classes per training example. Default: ``1`` .
996
+ sampled_values (Union[list, tuple]): List or tuple of (`sampled_candidates`, `true_expected_count`,
997
+ `sampled_expected_count`) returned by a `*CandidateSampler` function.
998
+ Default to None, `UniformCandidateSampler` is applied. Default: ``None`` .
999
+ remove_accidental_hits (bool): Whether to remove "accidental hits"
1000
+ where a sampled class equals to one of the labels classes. Default: ``True`` .
1001
+ seed (int): Random seed for candidate sampling. Default: ``0``.
1002
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1003
+ ``'sum'`` . Default: ``'none'`` .
1004
+
1005
+ - ``'none'``: no reduction will be applied.
1006
+ - ``'mean'``: compute and return the mean of elements in the output.
1007
+ - ``'sum'``: the output elements will be summed.
1008
+
1009
+ Inputs:
1010
+ - **weights** (Tensor) - The weights of input. Tensor of shape :math:`(C, dim)`.
1011
+ - **bias** (Tensor) - Tensor of shape :math:`(C,)`. The class biases.
1012
+ - **labels** (Tensor) - Tensor of shape :math:`(N, num\_true)`, type `int64, int32`. The labels classes.
1013
+ - **logits** (Tensor) - Tensor of shape :math:`(N, dim)`. The forward activations of the input network.
1014
+
1015
+ Outputs:
1016
+ Tensor or Scalar, if `reduction` is ``'none'``, then output is a tensor with shape :math:`(N,)`.
1017
+ Otherwise, the output is a scalar.
1018
+
1019
+ Raises:
1020
+ TypeError: If `sampled_values` is not a list or tuple.
1021
+ TypeError: If dtype of `labels` is neither int32 nor int64.
1022
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1023
+ ValueError: If `num_sampled` or `num_true` is greater than `num_classes`.
1024
+ ValueError: If length of `sampled_values` is not equal to 3.
1025
+
1026
+ Supported Platforms:
1027
+ ``GPU``
1028
+
1029
+ Examples:
1030
+ >>> import mindspore
1031
+ >>> from mindspore import Tensor, nn
1032
+ >>> import numpy as np
1033
+ >>> mindspore.set_seed(1)
1034
+ >>> loss = nn.SampledSoftmaxLoss(num_sampled=4, num_classes=7, num_true=1)
1035
+ >>> weights = Tensor(np.random.randint(0, 9, [7, 10]), mindspore.float32)
1036
+ >>> biases = Tensor(np.random.randint(0, 9, [7]), mindspore.float32)
1037
+ >>> labels = Tensor([0, 1, 2])
1038
+ >>> logits = Tensor(np.random.randint(0, 9, [3, 10]), mindspore.float32)
1039
+ >>> output = loss(weights, biases, labels, logits)
1040
+ >>> print(output)
1041
+ [4.6051701e+01 1.4000047e+01 6.1989022e-06]
1042
+ """
1043
+
1044
+ def __init__(self, num_sampled, num_classes, num_true=1,
1045
+ sampled_values=None, remove_accidental_hits=True, seed=0,
1046
+ reduction='none'):
1047
+ """Initialize SampledSoftmaxLoss."""
1048
+ super(SampledSoftmaxLoss, self).__init__(reduction)
1049
+
1050
+ if num_true < 1:
1051
+ raise ValueError(f"For '{self.cls_name}', the 'num_true' must be greater than or equal to 1, "
1052
+ f"but got {num_true}.")
1053
+ if seed < 0:
1054
+ raise ValueError(f"For '{self.cls_name}', the 'seed' must be greater than or equal to 0, but got {seed}.")
1055
+ if num_sampled > num_classes:
1056
+ raise ValueError(f"For '{self.cls_name}', the 'num_sampled' must be smaller than or "
1057
+ f"equal to 'num_classes', but got 'num_sampled': {num_sampled} "
1058
+ f"and 'num_classes': {num_classes}.")
1059
+ if num_true > num_classes:
1060
+ raise ValueError(f"For '{self.cls_name}', the 'num_true' must be smaller than or equal to 'num_classes', "
1061
+ f"but got 'num_true': {num_true} amd 'num_classes': {num_classes}.")
1062
+ if sampled_values is not None:
1063
+ if not isinstance(sampled_values, (list, tuple)):
1064
+ raise TypeError(f"For '{self.cls_name}', the type of 'sampled_values' must be a list or tuple, "
1065
+ f"but got {type(sampled_values).__name__}.")
1066
+ if len(sampled_values) != 3:
1067
+ raise ValueError(f"For '{self.cls_name}', the length of 'sampled_values' must be equal to 3,"
1068
+ f"but got {len(sampled_values)}.")
1069
+
1070
+ self.num_sampled = num_sampled
1071
+ self.num_classes = num_classes
1072
+ self.num_true = num_true
1073
+ self.sampled_values = sampled_values
1074
+ self.remove_accidental_hits = remove_accidental_hits
1075
+ self.seed = seed
1076
+ self.sampler = P.UniformCandidateSampler(
1077
+ num_true,
1078
+ num_sampled,
1079
+ True,
1080
+ num_classes,
1081
+ seed,
1082
+ remove_accidental_hits)
1083
+ self.cast = P.Cast()
1084
+ self.reshape = P.Reshape()
1085
+ self.shape = P.Shape()
1086
+ self.exp = P.Exp()
1087
+ self.log = P.Log()
1088
+ self.slice_op = P.Slice()
1089
+ self.matmul = P.MatMul(False, True)
1090
+ self.gather_v2 = P.Gather()
1091
+ self.reduce_max_true = P.ReduceMax(True)
1092
+ self.reduce_sum = P.ReduceSum()
1093
+ self.reduce_sum_true = P.ReduceSum(True)
1094
+ self.concat_dim0 = P.Concat(0)
1095
+ self.concat_dim1 = P.Concat(1)
1096
+ self.ones_like = P.OnesLike()
1097
+ self.zeros_like = P.ZerosLike()
1098
+ self.mul = P.Mul()
1099
+ self.expand_dims = P.ExpandDims()
1100
+ self.dtype = P.DType()
1101
+
1102
+ def construct(self, weights, biases, labels, logits):
1103
+ _check_is_tensor('weights', weights, self.cls_name)
1104
+ _check_is_tensor('biases', biases, self.cls_name)
1105
+ _check_is_tensor('labels', labels, self.cls_name)
1106
+ _check_is_tensor('logits', logits, self.cls_name)
1107
+ _check_label_dtype(self.dtype(labels), self.cls_name)
1108
+
1109
+ logits, labels = self._compute_sampled_logits(
1110
+ weights=weights,
1111
+ biases=biases,
1112
+ labels=labels,
1113
+ logits=logits,
1114
+ num_true=self.num_true,
1115
+ sampled_values=self.sampled_values,
1116
+ subtract_log_q=True)
1117
+
1118
+ x = self._softmax_cross_entropy(logits, labels)
1119
+ return x
1120
+
1121
+ def _softmax_cross_entropy(self, logits, targets):
1122
+ stable_exp_logits = self.exp(logits - self.reduce_max_true(logits, 1))
1123
+ pred = stable_exp_logits / self.reduce_sum_true(stable_exp_logits, 1)
1124
+ return -1 * self.reduce_sum(targets * self.log(pred + 1.0e-20), 1)
1125
+
1126
+ def _compute_sampled_logits(self, weights,
1127
+ biases,
1128
+ labels,
1129
+ logits,
1130
+ num_true=1,
1131
+ sampled_values=None,
1132
+ subtract_log_q=True):
1133
+ """Helper function for SampledSoftmaxLoss functions.
1134
+
1135
+ Computes sampled output training logits and labels suitable
1136
+
1137
+ Note: In the case where num_true > 1, we assign to each labels class
1138
+ with the labels probability (1/num_true) so that the labels probabilities
1139
+ sum to 1 per-example.
1140
+
1141
+ Args:
1142
+ weights (Tensor): Tensor of shape `[num_classes, dim]`.
1143
+ biases (Tensor): Tensor of shape `[num_classes]`.
1144
+ labels (Tensor): Tensor of shape `[batch_size, num_true]`. The labels classes.
1145
+ logits (Tensor): Tensor of shape `[batch_size, dim]`. The forward
1146
+ activations of the input network.
1147
+ num_true (int): The number of labels classes per training example.
1148
+ sampled_values: A tuple of (`sampled_candidates`, `true_expected_count`,
1149
+ `sampled_expected_count`) returned by a `UniformCandidateSampler` function.
1150
+ subtract_log_q: A `bool`. whether to subtract the log expected count of
1151
+ the labels in the sample to get the logits of the true labels. Default: ``True`` .
1152
+ Returns:
1153
+ out_logits: `Tensor` object with shape
1154
+ `[batch_size, num_true + num_sampled]`
1155
+ out_labels: A tensor object with the same shape as `out_logits`.
1156
+ """
1157
+
1158
+ if not labels.dtype == mstype.int32:
1159
+ labels = self.cast(labels, mstype.int32)
1160
+ labels = self.reshape(labels, (-1, num_true))
1161
+ labels_flat = self.reshape(labels, (-1,))
1162
+
1163
+ # Sample the negative labels.
1164
+ # sampled shape: [num_sampled] tensor
1165
+ # true_expected_count shape is [batch_size, 1] tensor
1166
+ # sampled_expected_count shape is [num_sampled] tensor
1167
+ if sampled_values is None:
1168
+ sampled_values = self.sampler(labels)
1169
+
1170
+ (sampled, true_expected_count, sampled_expected_count) = sampled_values
1171
+
1172
+ if not sampled.dtype == mstype.int32:
1173
+ sampled = self.cast(sampled, mstype.int32)
1174
+ all_ids = self.concat_dim0((labels_flat, sampled))
1175
+ all_w = self.gather_v2(weights, all_ids, 0)
1176
+
1177
+ n_true = self.shape(labels_flat)[0]
1178
+ n_sampled = self.shape(sampled)[0]
1179
+ n_dim = self.shape(all_w)[1]
1180
+
1181
+ true_w = self.slice_op(all_w, [0, 0], [n_true, n_dim])
1182
+ sampled_w = self.slice_op(all_w, [n_true, 0], [n_sampled, n_dim])
1183
+ sampled_logits = self.matmul(logits, sampled_w)
1184
+
1185
+ all_b = self.gather_v2(biases, all_ids, 0)
1186
+ true_b = self.slice_op(all_b, [0], [n_true])
1187
+ sampled_b = self.slice_op(all_b, [n_true], [n_sampled])
1188
+
1189
+ new_true_w_shape = (-1, num_true, n_dim)
1190
+ row_wise_dots = self.mul(self.expand_dims(logits, 1),
1191
+ self.reshape(true_w, new_true_w_shape))
1192
+
1193
+ # We want the row-wise dot plus biases which yields a
1194
+ # [batch_size, num_true] tensor of true_logits.
1195
+ dots_as_matrix = self.reshape(row_wise_dots, (-1, n_dim))
1196
+ true_logits = self.reshape(self.reduce_sum(dots_as_matrix, 1), (-1, num_true))
1197
+ true_b = self.reshape(true_b, (-1, num_true))
1198
+ true_logits += true_b
1199
+ sampled_logits += sampled_b
1200
+
1201
+ if subtract_log_q:
1202
+ # Subtract log of Q(l), prior probability that l appears in sampled.
1203
+ true_logits -= self.log(true_expected_count)
1204
+ sampled_logits -= self.log(sampled_expected_count)
1205
+
1206
+ # Construct output logits and labels. The true labels/logits start at col 0.
1207
+ out_logits = self.concat_dim1((true_logits, sampled_logits))
1208
+
1209
+ # true_logits is a float tensor, ones_like(true_logits) is a float
1210
+ # tensor of ones. We then divide by num_true to ensure the per-example
1211
+ # labels sum to 1.0, i.e. form a proper probability distribution.
1212
+ out_labels = self.concat_dim1((
1213
+ self.ones_like(true_logits) / num_true,
1214
+ self.zeros_like(sampled_logits)
1215
+ ))
1216
+ return out_logits, out_labels
1217
+
1218
+
1219
+ class TripletMarginWithDistanceLoss(LossBase):
1220
+ r"""
1221
+ TripletMarginWithDistanceLoss operation.
1222
+
1223
+ Creates a criterion that measures the triplet loss given an input
1224
+ tensors :math:`x1`, :math:`x2`, :math:`x3` and a margin with a value greater than :math:`0`.
1225
+ This is used for measuring a relative similarity between samples. A triplet
1226
+ is composed by `a`, `p` and `n` (i.e., `anchor`, `positive examples` and `negative
1227
+ examples` respectively). The shapes of all input tensors should be
1228
+ :math:`(N, D)`.
1229
+
1230
+ The distance swap is described in detail in the paper `Learning shallow
1231
+ convolutional feature descriptors with triplet losses` by
1232
+ V. Balntas, E. Riba et al.
1233
+
1234
+ The loss function for each sample in the mini-batch is:
1235
+
1236
+ .. math::
1237
+ L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}
1238
+
1239
+ where
1240
+
1241
+ .. math::
1242
+ d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p
1243
+
1244
+ Args:
1245
+ distance_function (callable): The distance function needed to calculate the margin loss of a triplet.
1246
+ if no distance metric is specified, the pairwise distance will be used. Default: ``None`` .
1247
+ swap (bool): The distance swap is described in detail in the paper
1248
+ `Learning shallow convolutional feature descriptors with triplet losses` by
1249
+ V. Balntas, E. Riba et al. Default: ``False`` .
1250
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1251
+ ``'sum'`` . Default: ``'mean'`` .
1252
+
1253
+ - ``'none'``: no reduction will be applied.
1254
+ - ``'mean'``: compute and return the mean of elements in the output.
1255
+ - ``'sum'``: the output elements will be summed.
1256
+
1257
+ margin (float): Make a margin between the positive pair and the negative pair. Default: ``1.0`` .
1258
+
1259
+ Inputs:
1260
+ - **x** (Tensor) - A sample randomly selected from the training set. Data type must be BasicType.
1261
+ The shape should be :math:`(N, D)`.
1262
+ - **positive** (Tensor) - A sample belonging to the same category as x,
1263
+ with the same type and shape as `x`.
1264
+ - **negative** (Tensor) - A sample belonging to the different class from x,
1265
+ with the same type and shape as `x`.
1266
+
1267
+ Outputs:
1268
+ Union[Tensor, Scalar], if `reduction` is ``'none'``, its shape is :math:`(N)`.
1269
+ Otherwise, a scalar value will be returned.
1270
+
1271
+ Raises:
1272
+ TypeError: If `x` or `positive` or `negative` is not a Tensor.
1273
+ TypeError: If `swap` is not a bool.
1274
+ ValueError: If dimensions of input `x`, `positive` and `negative` are less than or equal to 1 at the same time.
1275
+ ValueError: If length of shape of `margin` is not 0.
1276
+ ValueError: If shape of `x`, `positive` and `negative` cannot broadcast.
1277
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1278
+
1279
+ Supported Platforms:
1280
+ ``Ascend`` ``GPU`` ``CPU``
1281
+
1282
+ Examples:
1283
+ >>> import mindspore
1284
+ >>> from mindspore import Tensor, nn
1285
+ >>> x = Tensor([[0.3, 0.7], [0.5, 0.5]])
1286
+ >>> positive = Tensor([[0.4, 0.6], [0.4, 0.6]])
1287
+ >>> negative = Tensor([[0.2, 0.9], [0.3, 0.7]])
1288
+ >>> loss = nn.TripletMarginWithDistanceLoss()
1289
+ >>> out = loss(x, positive, negative)
1290
+ >>> print(out.asnumpy())
1291
+ 0.8881968
1292
+ """
1293
+
1294
+ def __init__(self, distance_function=None, swap=False, reduction="mean", margin=1.0):
1295
+ """Initialize TripletMarginWithDistanceLoss."""
1296
+ super(TripletMarginWithDistanceLoss, self).__init__(reduction=reduction)
1297
+ validator.check_is_float(margin, "margin", self.cls_name)
1298
+ validator.check_bool(swap, "swap", self.cls_name)
1299
+ if distance_function is None:
1300
+ def pairwise_distance(x, y):
1301
+ d = (x - y).abs()
1302
+ if d.ndim == 0:
1303
+ raise ValueError(
1304
+ "For 'pairwise_distance' in 'TripletMarginWithDistanceLoss', "
1305
+ "'ndim' of the input must be positive, "
1306
+ f"but got {d.ndim}"
1307
+ )
1308
+ return P.LpNorm(axis=1, p=2)(d)
1309
+
1310
+ self.distance_function = pairwise_distance
1311
+ else:
1312
+ self.distance_function = distance_function
1313
+ self.swap = swap
1314
+ self.reduction = reduction
1315
+ self.margin = margin
1316
+ self.minimum = P.Minimum()
1317
+ self.maximum = P.Maximum()
1318
+
1319
+ def construct(self, x, positive, negative):
1320
+ _check_is_tensor("x", x, self.cls_name)
1321
+ _check_is_tensor("positive", positive, self.cls_name)
1322
+ _check_is_tensor("negative", negative, self.cls_name)
1323
+ d1 = self.distance_function(x, positive)
1324
+ d2 = self.distance_function(x, negative)
1325
+ if self.swap:
1326
+ d2 = self.minimum(d2, self.distance_function(positive, negative))
1327
+ loss = self.maximum(d1 - d2 + self.margin, 0)
1328
+ return self.get_loss(loss)
1329
+
1330
+
1331
+ class PoissonNLLLoss(LossBase):
1332
+ r"""
1333
+ Poisson negative log likelihood loss.
1334
+
1335
+ The loss is:
1336
+
1337
+ .. math::
1338
+ \mathcal{L}_{D} = \sum_{i = 0}^{|D|}\left( x_{i} - y_{i}\ln x_{i} + \ln{y_{i}!} \right)
1339
+
1340
+ where :math:`\mathcal{L}_{D}` is the loss, :math:`y_{i}` is the `target`,
1341
+ :math:`x_{i}` is the `input`.
1342
+
1343
+ If `log_input` is True, use :math:`e^{x_{i}} - y_{i} x_{i}` instead of :math:`x_{i} - y_{i}\ln x_{i}`.
1344
+ When calculating logarithms, the lower bound of `input` is set to `eps` to avoid numerical errors.
1345
+
1346
+ If `full` is False, the last term :math:`\ln{y_{i}!}` will be omitted,
1347
+ otherwise the last term will be approximated using Stirling formula:
1348
+
1349
+ .. math::
1350
+ n! \approx \sqrt{2\pi n}\left( \frac{n}{e} \right)^{n}
1351
+
1352
+ Note:
1353
+ Calculating the logarithm of a negative number or the exponent of a large positive number under Ascend
1354
+ will have a different range of return values and results different from those under GPU and CPU.
1355
+
1356
+ Args:
1357
+ log_input (bool, optional): Whether use log input. Default: ``True`` .
1358
+ full (bool, optional): Whether include the Stirling approximation term in the loss calculation.
1359
+ Default: ``False`` .
1360
+ eps (float, optional): Lower bound of `input` when calculating logarithms. Default: ``1e-08`` .
1361
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1362
+ ``'sum'`` . Default: ``'mean'`` .
1363
+
1364
+ - ``'none'``: no reduction will be applied.
1365
+ - ``'mean'``: compute and return the mean of elements in the output.
1366
+ - ``'sum'``: the output elements will be summed.
1367
+
1368
+ Inputs:
1369
+ - **input** (Tensor) - The input Tensor. The shape can be any number of dimensions.
1370
+ - **target** (Tensor) - The label Tensor which has the same shape as `input`.
1371
+
1372
+ Outputs:
1373
+ Tensor or Scalar, if `reduction` is ``'none'``, then output is a tensor and has the same shape as `input`.
1374
+ Otherwise it is a scalar.
1375
+
1376
+ Raises:
1377
+ TypeError: If `reduction` is not a str.
1378
+ TypeError: If neither `input` nor `target` is a tensor.
1379
+ TypeError: If dtype of `input` or `target` is not currently supported.
1380
+
1381
+ Supported Platforms:
1382
+ ``Ascend`` ``GPU`` ``CPU``
1383
+
1384
+ Examples:
1385
+ >>> import mindspore as ms
1386
+ >>> import mindspore.nn as nn
1387
+ >>> x = ms.Tensor([[0.3, 0.7], [0.5, 0.5]])
1388
+ >>> target = ms.Tensor([[1.0, 2.0], [3.0, 4.0]])
1389
+ >>> loss = nn.PoissonNLLLoss()
1390
+ >>> output = loss(x, target)
1391
+ >>> print(output.asnumpy())
1392
+ 0.3652635
1393
+ """
1394
+
1395
+ def __init__(self, log_input=True, full=False, eps=1e-08, reduction="mean"):
1396
+ """Initialize PoissonNLLLoss."""
1397
+ super(PoissonNLLLoss, self).__init__(reduction=reduction)
1398
+ self.log_input = log_input
1399
+ self.full = full
1400
+ self.eps = eps
1401
+ self.maximum = P.Maximum()
1402
+ self.cast = P.Cast()
1403
+
1404
+ def construct(self, input, target):
1405
+ _check_is_tensor('input', input, self.cls_name)
1406
+ _check_is_tensor('target', target, self.cls_name)
1407
+ target = self.cast(target, input.dtype)
1408
+ if self.log_input:
1409
+ loss = input.exp() - target * input
1410
+ else:
1411
+ loss = input - target * ((input + self.eps).log())
1412
+ if self.full:
1413
+ target = self.maximum(target, self.eps)
1414
+ stirling_term = (target > 1) * ((target + 0.5) * target.log() - target + get_half_ln_2_pi())
1415
+ loss += F.masked_fill(stirling_term, target <= 1, F.cast(0, stirling_term.dtype))
1416
+ out = self.get_loss(loss)
1417
+ return out
1418
+
1419
+
1420
+ @constexpr
1421
+ def get_half_ln_2_pi():
1422
+ return 0.5 * math.log(2 * math.pi)
1423
+
1424
+
1425
+ class MultiLabelSoftMarginLoss(LossBase):
1426
+ r"""
1427
+ Calculates the MultiLabelSoftMarginLoss.
1428
+ The multi-label soft margin loss is a commonly used loss function in multi-label classification tasks
1429
+ where an input sample can belong to multiple classes.
1430
+ Given an input :math:`x` and binary labels :math:`y` of size :math:`(N,C)`, where :math:`N` denotes
1431
+ the number of samples and :math:`C` denotes the number of classes.
1432
+
1433
+ .. math::
1434
+ \mathcal{loss\left( x , y \right)} = - \frac{1}{N}\frac{1}{C}\sum_{i = 1}^{N}
1435
+ \sum_{j = 1}^{C}\left(y_{ij}\log\frac{1}{1 + e^{- x_{ij}}} + \left( 1 - y_{ij}
1436
+ \right)\log\frac{e^{-x_{ij}}}{1 + e^{-x_{ij}}} \right)
1437
+
1438
+ where :math:`x_{ij}` represents the predicted score of sample :math:`i` for class :math:`j`. :math:`y_{ij}`
1439
+ represents the binary label of sample :math:`i` for class :math:`j`, where sample :math:`i` belongs to
1440
+ class :math:`j` if :math:`y_{ij}=1` , and sample :math:`i` does not belong to class :math:`j` if :math:`y_{ij}=0`.
1441
+ For a multi-label classification task, each sample may have multiple labels with a value of 1 in the binary
1442
+ label :math:`y`. `weight` will multiply to the loss of each class if given.
1443
+
1444
+ Args:
1445
+ weight (Union[Tensor, int, float]): The manual rescaling weight given to each class. Default: ``None`` .
1446
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1447
+ ``'sum'`` . Default: ``'mean'`` .
1448
+
1449
+ - ``'none'``: no reduction will be applied.
1450
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
1451
+ - ``'sum'``: the output elements will be summed.
1452
+
1453
+ Inputs:
1454
+ - **x** (Tensor) - A tensor of shape :math:`(N, C)`, where N is batch size and C is number
1455
+ of classes.
1456
+ - **target** (Tensor) - The label target Tensor which has the same shape as `x`.
1457
+
1458
+ Outputs:
1459
+ Tensor, the data type is the same as x, if the reduction is ``'none'``, its shape is (N), otherwise it is zero.
1460
+
1461
+ Raises:
1462
+ ValueError: If the rank of `x` or `target` is not 2.
1463
+
1464
+ Supported Platforms:
1465
+ ``Ascend`` ``GPU`` ``CPU``
1466
+
1467
+ Examples:
1468
+ >>> import mindspore as ms
1469
+ >>> import mindspore.nn as nn
1470
+ >>> x = ms.Tensor([[0.3, 0.6, 0.6], [0.9, 0.4, 0.2]])
1471
+ >>> target = ms.Tensor([[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]])
1472
+ >>> loss = nn.MultiLabelSoftMarginLoss(reduction='mean')
1473
+ >>> out = loss(x, target)
1474
+ >>> print(out.asnumpy())
1475
+ 0.84693956
1476
+ """
1477
+
1478
+ def __init__(self, weight=None, reduction="mean"):
1479
+ """Initialize MultiLabelSoftMarginLoss."""
1480
+ super(MultiLabelSoftMarginLoss, self).__init__(reduction)
1481
+ self.weight = weight
1482
+ self.reduction = reduction
1483
+
1484
+ def construct(self, x, target):
1485
+ return F.multilabel_soft_margin_loss(x, target, self.weight, self.reduction)
1486
+
1487
+
1488
+ class MultiMarginLoss(LossBase):
1489
+ r"""
1490
+ Creates a criterion that optimizes a multi-class classification hinge
1491
+ loss (margin-based loss) between input :math:`x` (a 2D mini-batch `Tensor`) and
1492
+ output :math:`y` (which is a 1D tensor of target class indices,
1493
+ :math:`0 \leq y \leq \text{x.size}(1)-1`):
1494
+
1495
+ For each mini-batch sample, the loss in terms of the 1D input :math:`x` and scalar
1496
+ output :math:`y` is:
1497
+
1498
+ .. math::
1499
+ \text{loss}(x, y) = \frac{\sum_i \max(0, w[y] * (\text{margin} - x[y] + x[i]))^p}{\text{x.size}(0)}
1500
+
1501
+ where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`
1502
+ and :math:`i \neq y`.
1503
+
1504
+ Args:
1505
+ p (int, optional): The norm degree for pairwise distance. Should be 1 or 2. Default: ``1`` .
1506
+ margin (float, optional): A parameter to change pairwise distance. Default: 1.0.
1507
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1508
+ ``'sum'`` . Default: ``'mean'`` .
1509
+
1510
+ - ``'none'``: no reduction will be applied.
1511
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
1512
+ - ``'sum'``: the output elements will be summed.
1513
+
1514
+ weight (Tensor, optional): The rescaling weight to each class with shape :math:`(C,)`. Data type only
1515
+ support float32, float16 or float64. Default: ``None`` , all classes are weighted equally.
1516
+
1517
+ Inputs:
1518
+ - **x** (Tensor) - Input x, with shape :math:`(N, C)`. Data type only supports float32, float16 or float64.
1519
+ x is :math:`x` in the above formula.
1520
+ - **target** (Tensor) - Ground truth labels, with shape :math:`(N,)`. Data type only supports int64. The
1521
+ value of target should be non-negative, less than C. `target` is :math:`y` in the above formula.
1522
+
1523
+ Outputs:
1524
+ Tensor. When `reduction` is ``'none'``, the shape is :math:`(N,)`.
1525
+ Otherwise, it is a scalar. Has the same data type with `x`.
1526
+
1527
+ Raises:
1528
+ TypeError: If dtype of `p` or `target` is not int.
1529
+ TypeError: If dtype of `margin` is not float.
1530
+ TypeError: If dtype of `reduction` is not str.
1531
+ TypeError: If dtype of `x` is not float16, float or float64.
1532
+ TypeError: If dtype of `weight` and `x` is not the same.
1533
+ ValueError: If `p` is not 1 or 2.
1534
+ ValueError: If `reduction` is not one of { ``'none'`` , ``'sum'`` , ``'mean'`` }.
1535
+ ValueError: If shape[0] of `x` is not equal to shape[0] of `target`.
1536
+ ValueError: If shape[1] of `x` is not equal to shape[0] of `weight`.
1537
+ ValueError: IF rank of `weight` is not 1.
1538
+ ValueError: If rank of `x` is not 2 or rank of 'target' is not 1.
1539
+
1540
+ Supported Platforms:
1541
+ ``Ascend`` ``GPU`` ``CPU``
1542
+
1543
+ Examples:
1544
+ >>> import mindspore as ms
1545
+ >>> import mindspore.nn as nn
1546
+ >>> import numpy as np
1547
+ >>> x = ms.Tensor(np.ones(shape=[3, 3]), ms.float32)
1548
+ >>> target = ms.Tensor(np.array([1, 2, 1]), ms.int64)
1549
+ >>> loss = nn.MultiMarginLoss()
1550
+ >>> output = loss(x, target)
1551
+ >>> print(output)
1552
+ 0.6666667
1553
+ """
1554
+
1555
+ def __init__(self, p=1, margin=1.0, reduction='mean', weight=None):
1556
+ """Initialize MultiMarginLoss."""
1557
+ super(MultiMarginLoss, self).__init__()
1558
+ self.multi_margin_loss = MultiMarginLossOp(p=p, margin=margin, reduction=reduction)
1559
+ self.weight = weight
1560
+
1561
+ def construct(self, x, target, weight=None):
1562
+ _check_is_tensor('x', x, self.cls_name)
1563
+ _check_is_tensor('target', target, self.cls_name)
1564
+ if self.weight is not None:
1565
+ weight = self.weight
1566
+ weight_one = weight is None
1567
+ if not weight_one:
1568
+ _check_is_tensor('weight', weight, self.cls_name)
1569
+ else:
1570
+ weight = F.fill(x.dtype, x.astype('float32')[0].shape, 1)
1571
+ loss = self.multi_margin_loss(x, target, weight)
1572
+ return loss
1573
+
1574
+
1575
+ class BCELoss(LossBase):
1576
+ r"""
1577
+ BCELoss creates a criterion to measure the binary cross entropy between the true labels and predicted labels.
1578
+
1579
+ Set the predicted labels as :math:`x`, true labels as :math:`y`, the output loss as :math:`\ell(x, y)`.
1580
+ The formula is as follow:
1581
+
1582
+ .. math::
1583
+ L = \{l_1,\dots,l_N\}^\top, \quad
1584
+ l_n = - w_n \left[ y_n \cdot \log x_n + (1 - y_n) \cdot \log (1 - x_n) \right]
1585
+
1586
+ where N is the batch size. Then,
1587
+
1588
+ .. math::
1589
+ \ell(x, y) = \begin{cases}
1590
+ L, & \text{if reduction} = \text{'none';}\\
1591
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
1592
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
1593
+ \end{cases}
1594
+
1595
+ Note:
1596
+ Note that the predicted labels should always be the output of sigmoid. Because it is a two-class
1597
+ classification, the true labels should be numbers between 0 and 1.
1598
+ And if input is either 0 or 1, one of the log terms would be mathematically undefined in the above loss
1599
+ equation.
1600
+
1601
+ Args:
1602
+ weight (Tensor, optional): A rescaling weight applied to the loss of each batch element.
1603
+ And it must have the same shape and data type as `inputs`. Default: ``None`` .
1604
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1605
+ ``'sum'`` . Default: ``'mean'`` .
1606
+
1607
+ - ``'none'``: no reduction will be applied.
1608
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
1609
+ - ``'sum'``: the output elements will be summed.
1610
+
1611
+ Inputs:
1612
+ - **logits** (Tensor) - The input tensor with shape :math:`(N, *)` where :math:`*` means, any number
1613
+ of additional dimensions. The data type must be float16 or float32.
1614
+ - **labels** (Tensor) - The label tensor with shape :math:`(N, *)` where :math:`*` means, any number
1615
+ of additional dimensions. The same shape and data type as `logits`.
1616
+
1617
+ Outputs:
1618
+ Tensor, has the same dtype as `logits`. if `reduction` is ``'none'``, then it has the same shape as `logits`.
1619
+ Otherwise, it is a scalar Tensor.
1620
+
1621
+ Raises:
1622
+ TypeError: If dtype of `logits`, `labels` or `weight` (if given) is neither float16 not float32.
1623
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1624
+ ValueError: If shape of `logits` is not the same as `labels` or `weight` (if given).
1625
+
1626
+ Supported Platforms:
1627
+ ``Ascend`` ``GPU`` ``CPU``
1628
+
1629
+ Examples:
1630
+ >>> import mindspore as ms
1631
+ >>> import mindspore.nn as nn
1632
+ >>> import numpy as np
1633
+ >>> weight = ms.Tensor(np.array([[1.0, 2.0, 3.0], [4.0, 3.3, 2.2]]), ms.float32)
1634
+ >>> loss = nn.BCELoss(weight=weight, reduction='mean')
1635
+ >>> logits = ms.Tensor(np.array([[0.1, 0.2, 0.3], [0.5, 0.7, 0.9]]), ms.float32)
1636
+ >>> labels = ms.Tensor(np.array([[0, 1, 0], [0, 0, 1]]), ms.float32)
1637
+ >>> output = loss(logits, labels)
1638
+ >>> print(output)
1639
+ 1.8952923
1640
+ """
1641
+
1642
+ def __init__(self, weight=None, reduction='mean'):
1643
+ """Initialize BCELoss."""
1644
+ super(BCELoss, self).__init__(reduction)
1645
+ self.binary_cross_entropy = P.BinaryCrossEntropy(reduction=reduction)
1646
+ self.weight_one = weight is None
1647
+ if not self.weight_one:
1648
+ self.weight = weight
1649
+ else:
1650
+ self.ones = P.OnesLike()
1651
+
1652
+ def construct(self, logits, labels):
1653
+ _check_is_tensor('logits', logits, self.cls_name)
1654
+ _check_is_tensor('labels', labels, self.cls_name)
1655
+ if self.weight_one:
1656
+ weight = self.ones(logits)
1657
+ else:
1658
+ weight = self.weight
1659
+ loss = self.binary_cross_entropy(logits, labels, weight)
1660
+ return loss
1661
+
1662
+
1663
+ class CosineEmbeddingLoss(LossBase):
1664
+ r"""
1665
+ CosineEmbeddingLoss creates a criterion to measure the similarity between two tensors using cosine distance.
1666
+
1667
+ Given two tensors :math:`x1`, :math:`x2`, and a Tensor label :math:`y` with values 1 or -1:
1668
+
1669
+ .. math::
1670
+ loss(x_1, x_2, y) = \begin{cases}
1671
+ 1-cos(x_1, x_2), & \text{if } y = 1\\
1672
+ \max(0, cos(x_1, x_2)-margin), & \text{if } y = -1\\
1673
+ \end{cases}
1674
+
1675
+ Args:
1676
+ margin (float): Should be in [-1.0, 1.0]. Default: ``0.0`` .
1677
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1678
+ ``'sum'`` . Default: ``'mean'`` .
1679
+
1680
+ - ``'none'``: no reduction will be applied.
1681
+ - ``'mean'``: compute and return the mean of elements in the output.
1682
+ - ``'sum'``: the output elements will be summed.
1683
+
1684
+ Inputs:
1685
+ - **logits_x1** (Tensor) - Tensor of shape :math:`(N, *)` where :math:`*` means, any number
1686
+ of additional dimensions.
1687
+ - **logits_x2** (Tensor) - Tensor of shape :math:`(N, *)`, same shape and dtype as `logits_x1`.
1688
+ - **labels** (Tensor) - Contains value 1 or -1. Suppose the shape of `logits_x1` is
1689
+ :math:`(x_1, x_2, x_3, ..., x_R)`, then the shape of `labels` must be :math:`(x_1, x_3, x_4, ..., x_R)`.
1690
+
1691
+ Outputs:
1692
+ Tensor or Scalar, if `reduction` is ``"none"``, its shape is the same as `labels`.
1693
+ Otherwise, a scalar value will be returned.
1694
+
1695
+ Raises:
1696
+ TypeError: If `margin` is not a float.
1697
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1698
+ ValueError: If `margin` is not in range [-1.0, 1.0].
1699
+
1700
+ Supported Platforms:
1701
+ ``Ascend`` ``GPU`` ``CPU``
1702
+
1703
+ Examples:
1704
+ >>> import mindspore as ms
1705
+ >>> import mindspore.nn as nn
1706
+ >>> import numpy as np
1707
+ >>> logits_x1 = ms.Tensor(np.array([[0.3, 0.8], [0.4, 0.3]]), ms.float32)
1708
+ >>> logits_x2 = ms.Tensor(np.array([[0.4, 1.2], [-0.4, -0.9]]), ms.float32)
1709
+ >>> labels = ms.Tensor(np.array([1, -1]), ms.int32)
1710
+ >>> cosine_embedding_loss = nn.CosineEmbeddingLoss()
1711
+ >>> output = cosine_embedding_loss(logits_x1, logits_x2, labels)
1712
+ >>> print(output)
1713
+ 0.0003425479
1714
+ """
1715
+
1716
+ def __init__(self, margin=0.0, reduction="mean"):
1717
+ """Initialize CosineEmbeddingLoss."""
1718
+ super(CosineEmbeddingLoss, self).__init__(reduction)
1719
+ self.reduce_sum = P.ReduceSum()
1720
+ self.maximum = P.Maximum()
1721
+ validator.check_value_type("margin", margin, [float], self.cls_name)
1722
+ self.margin = validator.check_float_range(margin, -1.0, 1.0, validator.INC_BOTH, "margin", self.cls_name)
1723
+
1724
+ def construct(self, logits_x1, logits_x2, labels):
1725
+ _check_is_tensor('logits_x1', logits_x1, self.cls_name)
1726
+ _check_is_tensor('logits_x2', logits_x2, self.cls_name)
1727
+ _check_is_tensor('labels', labels, self.cls_name)
1728
+ inner.same_type_shape_(logits_x1, logits_x2)
1729
+ # if labels > 0, 1-cosine(logits_x1, logits_x2)
1730
+ # else, max(0, cosine(logits_x1, logits_x2)-margin)
1731
+ prod_sum = self.reduce_sum(logits_x1 * logits_x2, (1,))
1732
+ square1 = self.reduce_sum(F.square(logits_x1), (1,))
1733
+ square2 = self.reduce_sum(F.square(logits_x2), (1,))
1734
+ denom = F.sqrt(square1) * F.sqrt(square2)
1735
+ cosine = prod_sum / denom
1736
+
1737
+ pos_value = 1.0 - cosine
1738
+ neg_value = self.maximum(cosine - self.margin, 0.0)
1739
+ zeros = F.zeros_like(cosine)
1740
+ pos_part = F.select(labels == 1, pos_value, zeros)
1741
+ neg_part = F.select(labels == -1, neg_value, zeros)
1742
+ output_unreduced = pos_part + neg_part
1743
+
1744
+ return self.get_loss(output_unreduced)
1745
+
1746
+
1747
+ class MultilabelMarginLoss(LossBase):
1748
+ r"""
1749
+ Creates a loss criterion that minimizes the hinge loss for multi-class
1750
+ classification tasks.
1751
+ It takes a 2D mini-batch Tensor :math:`x` as input and a 2D
1752
+ Tensor :math:`y` containing target class indices as output.
1753
+
1754
+ Each sample in the mini-batch, the loss is computed as follows:
1755
+
1756
+ .. math::
1757
+ \text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)}
1758
+
1759
+ where :math:`x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}`, \
1760
+ :math:`y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}`, \
1761
+ :math:`0 \leq y[j] \leq \text{x.size}(0)-1`, \
1762
+ and for all :math:`i` and :math:`j`, :math:`i` does not equal to :math:`y[j]`.
1763
+
1764
+ Furthermore, both :math:`y` and :math:`x` should have identical sizes.
1765
+
1766
+ Note:
1767
+ For this operator, only a contiguous sequence of non-negative targets that starts at
1768
+ the beginning is taken into consideration, which means that different samples can have different
1769
+ number of target classes.
1770
+
1771
+ Args:
1772
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1773
+ ``'sum'`` . Default: ``'mean'`` .
1774
+
1775
+ - ``'none'``: no reduction will be applied.
1776
+ - ``'mean'``: compute and return the mean of elements in the output.
1777
+ - ``'sum'``: the output elements will be summed.
1778
+
1779
+ Inputs:
1780
+ - **x** (Tensor) - Predict data. Tensor of shape :math:`(C)` or :math:`(N, C)`, where :math:`N`
1781
+ is the batch size and :math:`C` is the number of classes. Data type must be float16 or float32.
1782
+ - **target** (Tensor) - Ground truth data, with the same shape as `x`, data type must be int32 and
1783
+ label targets padded by -1.
1784
+
1785
+ Outputs:
1786
+ - **y** (Union[Tensor, Scalar]) - The loss of MultilabelMarginLoss. If `reduction` is ``"none"``, its shape
1787
+ is :math:`(N)`. Otherwise, a scalar value will be returned.
1788
+
1789
+ Raises:
1790
+ TypeError: If `x` or `target` is not a Tensor.
1791
+ TypeError: If dtype of `x` is neither float16 nor float32.
1792
+ TypeError: If dtype of `target` is not int32.
1793
+ ValueError: If length of shape of `x` is neither 1 nor 2.
1794
+ ValueError: If shape of `x` is not the same as `target`.
1795
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1796
+
1797
+ Supported Platforms:
1798
+ ``Ascend`` ``GPU``
1799
+
1800
+ Examples:
1801
+ >>> import mindspore as ms
1802
+ >>> import mindspore.nn as nn
1803
+ >>> import numpy as np
1804
+ >>> loss = nn.MultilabelMarginLoss()
1805
+ >>> x = ms.Tensor(np.array([[0.1, 0.2, 0.4, 0.8], [0.2, 0.3, 0.5, 0.7]]), ms.float32)
1806
+ >>> target = ms.Tensor(np.array([[1, 2, 0, 3], [2, 3, -1, 1]]), ms.int32)
1807
+ >>> output = loss(x, target)
1808
+ >>> print(output)
1809
+ 0.325
1810
+ """
1811
+
1812
+ def __init__(self, reduction='mean'):
1813
+ super(MultilabelMarginLoss, self).__init__()
1814
+ self.multilabel_margin_loss = MultilabelMarginLossOp(reduction=reduction)
1815
+
1816
+ def construct(self, x, target):
1817
+ loss, _ = self.multilabel_margin_loss(x, target)
1818
+ return loss
1819
+
1820
+
1821
+ class BCEWithLogitsLoss(LossBase):
1822
+ r"""
1823
+ Adds sigmoid activation function to input `input` as logits, and uses the given logits to compute binary cross
1824
+ entropy between the `input` and the `target`.
1825
+
1826
+ Sets input `input` as :math:`X`, input `target` as :math:`Y`, output as :math:`L`. Then,
1827
+
1828
+ .. math::
1829
+ p_{ij} = sigmoid(X_{ij}) = \frac{1}{1 + e^{-X_{ij}}}
1830
+
1831
+ .. math::
1832
+ L_{ij} = -[Y_{ij} \cdot \log(p_{ij}) + (1 - Y_{ij}) \cdot \log(1 - p_{ij})]
1833
+
1834
+ Then,
1835
+
1836
+ .. math::
1837
+ \ell(x, y) = \begin{cases}
1838
+ L, & \text{if reduction} = \text{'none';}\\
1839
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
1840
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
1841
+ \end{cases}
1842
+
1843
+ Args:
1844
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1845
+ ``'sum'`` . Default: ``'mean'`` .
1846
+
1847
+ - ``'none'``: no reduction will be applied.
1848
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
1849
+ - ``'sum'``: the output elements will be summed.
1850
+
1851
+ weight (Tensor, optional): A rescaling weight applied to the loss of each batch element.
1852
+ If not None, it can be broadcast to a tensor with shape of `input`,
1853
+ data type must be float16 or float32. Default: ``None`` .
1854
+ pos_weight (Tensor, optional): A weight of positive examples. Must be a vector with length equal to the
1855
+ number of classes. If not None, it must be broadcast to a tensor with shape of `input`, data type
1856
+ must be float16 or float32. Default: ``None`` .
1857
+
1858
+ Inputs:
1859
+ - **input** (Tensor) - Input `input` with shape :math:`(N, *)` where :math:`*` means, any number
1860
+ of additional dimensions. The data type must be float16 or float32.
1861
+ - **target** (Tensor) - Ground truth label with shape :math:`(N, *)` where :math:`*` means, any number
1862
+ of additional dimensions. The same shape and data type as `input`.
1863
+
1864
+ Outputs:
1865
+ Tensor or Scalar, if `reduction` is ``'none'``, its shape is the same as `input`.
1866
+ Otherwise, a scalar value will be returned.
1867
+
1868
+ Raises:
1869
+ TypeError: If input `input` or `target` is not Tensor.
1870
+ TypeError: If data type of `input` or `target` is neither float16 nor float32.
1871
+ TypeError: If `weight` or `pos_weight` is a parameter.
1872
+ TypeError: If data type of `weight` or `pos_weight` is neither float16 nor float32.
1873
+ TypeError: If data type of `reduction` is not string.
1874
+ ValueError: If `weight` or `pos_weight` can not be broadcast to a tensor with shape of `input`.
1875
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1876
+
1877
+ Supported Platforms:
1878
+ ``Ascend`` ``GPU`` ``CPU``
1879
+
1880
+ Examples:
1881
+ >>> import mindspore as ms
1882
+ >>> import mindspore.nn as nn
1883
+ >>> import numpy as np
1884
+ >>> input = ms.Tensor(np.array([[-0.8, 1.2, 0.7], [-0.1, -0.4, 0.7]]).astype(np.float32))
1885
+ >>> target = ms.Tensor(np.array([[0.3, 0.8, 1.2], [-0.6, 0.1, 2.2]]).astype(np.float32))
1886
+ >>> loss = nn.BCEWithLogitsLoss()
1887
+ >>> output = loss(input, target)
1888
+ >>> print(output)
1889
+ 0.3463612
1890
+ """
1891
+
1892
+ def __init__(self, reduction='mean', weight=None, pos_weight=None):
1893
+ """Initialize BCEWithLogitsLoss."""
1894
+ super(BCEWithLogitsLoss, self).__init__()
1895
+ self.reduction = reduction
1896
+ if isinstance(weight, Parameter):
1897
+ raise TypeError(f"For '{self.cls_name}', the 'weight' can not be a Parameter.")
1898
+ if isinstance(pos_weight, Parameter):
1899
+ raise TypeError(f"For '{self.cls_name}', the 'pos_weight' can not be a Parameter.")
1900
+ self.weight = weight
1901
+ self.pos_weight = pos_weight
1902
+
1903
+ def construct(self, input, target):
1904
+ _check_is_tensor('input', input, self.cls_name)
1905
+ _check_is_tensor('target', target, self.cls_name)
1906
+ loss = ops.binary_cross_entropy_with_logits(input, target, self.weight, self.pos_weight, self.reduction)
1907
+ return loss
1908
+
1909
+
1910
+ @_primexpr
1911
+ def _check_ndim(logits_nidm, labels_ndim, prime_name=None):
1912
+ '''Internal function, used to check whether the dimension of logits and labels meets the requirements.'''
1913
+ msg_prefix = f'For \'{prime_name}\', the' if prime_name else "The"
1914
+ if logits_nidm < 2 or logits_nidm > 4:
1915
+ raise ValueError(f"{msg_prefix} dimensions of 'logits' must be in [2, 4], but got "
1916
+ f"dimension of 'logits' {logits_nidm}.")
1917
+ if labels_ndim < 2 or labels_ndim > 4:
1918
+ raise ValueError(f"{msg_prefix} dimensions of 'labels' must be in [2, 4], but got "
1919
+ f"dimension of 'labels' {labels_ndim}.")
1920
+ if logits_nidm != labels_ndim:
1921
+ raise ValueError(f"{msg_prefix} dimensions of 'logits' and 'labels' must be equal, but got "
1922
+ f"dimension of 'logits' {logits_nidm} and dimension of 'labels' {labels_ndim}.")
1923
+
1924
+
1925
+ @_primexpr
1926
+ def _check_channel_and_shape(logits, labels, prime_name=None):
1927
+ """Internal function, used to check whether the channels or shape of logits and labels meets the requirements."""
1928
+ msg_prefix = f'For \'{prime_name}\', the' if prime_name else "The"
1929
+ if logits == 1:
1930
+ raise ValueError(f"{msg_prefix} 'logits'.shape[1] cannot be one, but got {logits}.")
1931
+ if labels not in (1, logits):
1932
+ raise ValueError(f"{msg_prefix} 'labels'.shape[1] must be one or equal to 'logits'.shape[1]: {logits}, "
1933
+ f"but got {labels}.")
1934
+
1935
+
1936
+ @constexpr
1937
+ def _check_input_dtype(labels_dtype, cls_name):
1938
+ """Internal function, used to check whether the data type of labels meets the requirements."""
1939
+ validator.check_type_name("labels", labels_dtype,
1940
+ [mstype.int32, mstype.int64, mstype.float16, mstype.float32], cls_name)
1941
+
1942
+
1943
+ class FocalLoss(LossBase):
1944
+ r"""
1945
+ It is a loss function to solve the imbalance of categories and the difference of
1946
+ classification difficulty.
1947
+ The loss function proposed by Kaiming team in their paper
1948
+ `Focal Loss for Dense Object Detection <https://arxiv.org/pdf/1708.02002.pdf>`_ improves the
1949
+ effect of image object detection.
1950
+ The function is shown as follows:
1951
+
1952
+ .. math::
1953
+ FL(p_t) = -(1-p_t)^\gamma \log(p_t)
1954
+
1955
+ Args:
1956
+ gamma (float): Gamma is used to adjust the steepness of weight curve in focal loss. Default: ``2.0`` .
1957
+ weight (Union[Tensor, None]): A rescaling weight applied to the loss of each batch element. The dimension of
1958
+ weight should be 1. If None, no weight is applied. Default: ``None`` .
1959
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
1960
+ ``'sum'`` . Default: ``'mean'`` .
1961
+
1962
+ - ``'none'``: no reduction will be applied.
1963
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
1964
+ - ``'sum'``: the output elements will be summed.
1965
+
1966
+ Inputs:
1967
+ - **logits** (Tensor) - Tensor of shape should be :math:`(N, C)` or :math:`(N, C, H)` or :math:`(N, C, H, W)`.
1968
+ Where :math:`C` is the number of classes. Its value is greater than 1. If the shape is :math:`(N, C, H, W)`
1969
+ or :math:`(N, C, H)`, the :math:`H` or product of :math:`H` and :math:`W` should be the same as labels.
1970
+ - **labels** (Tensor) - Tensor of shape should be :math:`(N, C)` or :math:`(N, C, H)` or :math:`(N, C, H, W)`.
1971
+ The value of :math:`C` is 1 or it needs to be the same as predict's :math:`C`. If :math:`C` is not 1,
1972
+ the shape of target should be the same as that of predict, where :math:`C` is the number of classes.
1973
+ If the shape is :math:`(N, C, H, W)` or :math:`(N, C, H)`, the :math:`H` or product of :math:`H`
1974
+ and :math:`W` should be the same as logits. The value of `labels` is should be in the
1975
+ range [-:math:`C`, :math:`C`). Where :math:`C` is the number of classes in logits.
1976
+
1977
+ Outputs:
1978
+ Tensor or Scalar, if `reduction` is ``"none"``, its shape is the same as `logits`.
1979
+ Otherwise, a scalar value will be returned.
1980
+
1981
+ Raises:
1982
+ TypeError: If the data type of `gamma` is not a float.
1983
+ TypeError: If `weight` is not a Tensor.
1984
+ ValueError: If `labels` dim is different from `logits`.
1985
+ ValueError: If `labels` channel is not 1 and `labels` shape is different from `logits`.
1986
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
1987
+
1988
+ Supported Platforms:
1989
+ ``Ascend``
1990
+
1991
+ Examples:
1992
+ >>> import mindspore as ms
1993
+ >>> import mindspore.nn as nn
1994
+ >>> logits = ms.Tensor([[0.8, 1.4], [0.5, 0.9], [1.2, 0.9]], ms.float32)
1995
+ >>> labels = ms.Tensor([[1], [1], [0]], ms.int32)
1996
+ >>> focalloss = nn.FocalLoss(weight=ms.Tensor([1, 2]), gamma=2.0, reduction='mean')
1997
+ >>> output = focalloss(logits, labels)
1998
+ >>> print(output)
1999
+ 0.12516622
2000
+ """
2001
+
2002
+ def __init__(self, weight=None, gamma=2.0, reduction='mean'):
2003
+ """Initialize FocalLoss."""
2004
+ super(FocalLoss, self).__init__(reduction=reduction)
2005
+
2006
+ self.gamma = validator.check_value_type("gamma", gamma, [float])
2007
+ if weight is not None and not isinstance(weight, Tensor):
2008
+ raise TypeError(f"For '{self.cls_name}', the type of 'weight' must be a Tensor, "
2009
+ f"but got {type(weight).__name__}.")
2010
+ if isinstance(weight, Tensor) and weight.ndim != 1:
2011
+ raise ValueError(f"For '{self.cls_name}', the dimension of 'weight' must be 1, but got {weight.ndim}.")
2012
+ self.weight = weight
2013
+ self.expand_dims = P.ExpandDims()
2014
+ self.gather_d = P.GatherD()
2015
+ self.squeeze = P.Squeeze(axis=1)
2016
+ self.tile = P.Tile()
2017
+ self.cast = P.Cast()
2018
+ self.dtype = P.DType()
2019
+ self.logsoftmax = nn.LogSoftmax(1)
2020
+
2021
+ def construct(self, logits, labels):
2022
+ _check_is_tensor('logits', logits, self.cls_name)
2023
+ _check_is_tensor('labels', labels, self.cls_name)
2024
+ labelss = labels
2025
+ _check_ndim(logits.ndim, labelss.ndim, self.cls_name)
2026
+ _check_channel_and_shape(logits.shape[1], labelss.shape[1], self.cls_name)
2027
+ _check_input_dtype(self.dtype(labelss), self.cls_name)
2028
+
2029
+ if logits.ndim > 2:
2030
+ logits = logits.view(logits.shape[0], logits.shape[1], -1)
2031
+ labelss = labelss.view(labelss.shape[0], labelss.shape[1], -1)
2032
+ else:
2033
+ logits = self.expand_dims(logits, 2)
2034
+ labelss = self.expand_dims(labelss, 2)
2035
+
2036
+ log_probability = self.logsoftmax(logits)
2037
+
2038
+ if labels.shape[1] == 1:
2039
+ log_probability = self.gather_d(log_probability, 1, self.cast(labelss, mindspore.int32))
2040
+ log_probability = self.squeeze(log_probability)
2041
+
2042
+ probability = F.exp(log_probability)
2043
+
2044
+ if self.weight is not None:
2045
+ convert_weight = self.weight[None, :, None]
2046
+ convert_weight = self.tile(convert_weight, (labelss.shape[0], 1, labelss.shape[2]))
2047
+ if labels.shape[1] == 1:
2048
+ convert_weight = self.gather_d(convert_weight, 1, self.cast(labelss, mindspore.int32))
2049
+ convert_weight = self.squeeze(convert_weight)
2050
+ log_probability = log_probability * convert_weight
2051
+
2052
+ weight = F.pows(-1 * probability + 1.0, self.gamma)
2053
+ if labels.shape[1] == 1:
2054
+ loss = (-1 * weight * log_probability).mean(axis=1)
2055
+ else:
2056
+ loss = (-1 * weight * labelss * log_probability).mean(axis=-1)
2057
+
2058
+ return self.get_loss(loss)
2059
+
2060
+
2061
+ class HuberLoss(LossBase):
2062
+ r"""
2063
+ HuberLoss calculate the error between the predicted value and the target value.
2064
+ It has the advantages of both L1Loss and MSELoss.
2065
+
2066
+ Assuming that the :math:`x` and :math:`y` are 1-D Tensor, length :math:`N`, then calculate the loss of :math:`x` and
2067
+ :math:`y` without dimensionality reduction (the reduction parameter is set to "none"). The formula is as follows:
2068
+
2069
+ .. math::
2070
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top
2071
+
2072
+ with
2073
+
2074
+ .. math::
2075
+ l_n = \begin{cases}
2076
+ 0.5 * (x_n - y_n)^2, & \text{if } |x_n - y_n| < delta; \\
2077
+ delta * (|x_n - y_n| - 0.5 * delta), & \text{otherwise. }
2078
+ \end{cases}
2079
+
2080
+ where :math:`N` is the batch size. If `reduction` is not ``"none"``, then:
2081
+
2082
+ .. math::
2083
+ \ell(x, y) =
2084
+ \begin{cases}
2085
+ \operatorname{mean}(L), & \text{if reduction} = \text{"mean";}\\
2086
+ \operatorname{sum}(L), & \text{if reduction} = \text{"sum".}
2087
+ \end{cases}
2088
+
2089
+ Args:
2090
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2091
+ ``'sum'`` . Default: ``'mean'`` .
2092
+
2093
+ - ``'none'``: no reduction will be applied.
2094
+ - ``'mean'``: compute and return the mean of elements in the output.
2095
+ - ``'sum'``: the output elements will be summed.
2096
+
2097
+ delta (Union[int, float]): The threshold to change between two type of loss.
2098
+ The value must be positive. Default: ``1.0`` .
2099
+
2100
+ Inputs:
2101
+ - **logits** (Tensor) - Predicted value, Tensor of any dimension. The data type must be float16 or float32.
2102
+ - **labels** (Tensor) - Target value, same dtype and shape as the `logits` in common cases.
2103
+ However, it supports the shape of `logits` is different from the shape of `labels`
2104
+ and they should be broadcasted to each other.
2105
+
2106
+ Outputs:
2107
+ Tensor or Scalar, if `reduction` is ``"none"``, return a Tensor with same shape and dtype as `logits`.
2108
+ Otherwise, a scalar value will be returned.
2109
+
2110
+ Raises:
2111
+ TypeError: If data type of `logits` or `labels` is neither float16 nor float32.
2112
+ TypeError: If data type of `logits` or `labels` are not the same.
2113
+ TypeError: If dtype of `delta` is neither float nor int.
2114
+ ValueError: If `delta` is less than or equal to 0.
2115
+ ValueError: If `reduction` is not one of ``"none"``, ``"mean"``, ``"sum"``.
2116
+ ValueError: If `logits` and `labels` have different shapes and cannot be broadcasted to each other.
2117
+
2118
+ Supported Platforms:
2119
+ ``Ascend`` ``GPU`` ``CPU``
2120
+
2121
+ Examples:
2122
+ >>> import mindspore as ms
2123
+ >>> import mindspore.nn as nn
2124
+ >>> import numpy as np
2125
+ >>> # Case 1: logits.shape = labels.shape = (3,)
2126
+ >>> loss = nn.HuberLoss()
2127
+ >>> logits = ms.Tensor(np.array([1, 2, 3]), ms.float32)
2128
+ >>> labels = ms.Tensor(np.array([1, 2, 2]), ms.float32)
2129
+ >>> output = loss(logits, labels)
2130
+ >>> print(output)
2131
+ 0.16666667
2132
+ >>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
2133
+ >>> loss = nn.HuberLoss(reduction="none")
2134
+ >>> logits = ms.Tensor(np.array([1, 2, 3]), ms.float32)
2135
+ >>> labels = ms.Tensor(np.array([[1, 1, 1], [1, 2, 2]]), ms.float32)
2136
+ >>> output = loss(logits, labels)
2137
+ >>> print(output)
2138
+ [[0. 0.5 1.5]
2139
+ [0. 0. 0.5]]
2140
+ """
2141
+
2142
+ def __init__(self, reduction="mean", delta=1.0):
2143
+ """Initialize HuberLoss."""
2144
+ super(HuberLoss, self).__init__(reduction=reduction)
2145
+ self.reduction = reduction
2146
+ self.delta = delta
2147
+
2148
+ def construct(self, logits, labels):
2149
+ return F.huber_loss(logits, labels, self.reduction, self.delta)
2150
+
2151
+
2152
+ class TripletMarginLoss(LossBase):
2153
+ r"""
2154
+ TripletMarginLoss operation.
2155
+
2156
+ Triple loss is used to measure the relative similarity between samples,
2157
+ which is measured by a triplet and a :math:`margin` with a value greater than :math:`0` .
2158
+ The triplet is composed by :math:`a`, :math:`p`, :math:`n` in the following formula.
2159
+
2160
+ The shapes of all input tensors should be :math:`(N, *)` , where :math:`N` is batch size
2161
+ and :math:`*` means any number of additional dimensions.
2162
+
2163
+ The distance swap is described in detail in the paper
2164
+ `Learning local feature descriptors with triplets and shallow convolutional neural
2165
+ networks <http://158.109.8.37/files/BRP2016.pdf>`_
2166
+ by V. Balntas, E. Riba et al.
2167
+
2168
+ The loss function for each sample in the mini-batch is:
2169
+
2170
+ .. math::
2171
+ L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}
2172
+
2173
+ where
2174
+
2175
+ .. math::
2176
+ d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p
2177
+
2178
+ Args:
2179
+ p (int, optional): The degree of norm for pairwise distance. Default: ``2`` .
2180
+ eps (float, optional): Add small value to avoid division by zero. Default: ``1e-06`` .
2181
+ swap (bool, optional): The distance swap change the negative distance to the distance between positive
2182
+ sample and negative sample. Default: ``False`` .
2183
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2184
+ ``'sum'`` . Default: ``'mean'`` .
2185
+
2186
+ - ``'none'``: no reduction will be applied.
2187
+ - ``'mean'``: compute and return the mean of elements in the output.
2188
+ - ``'sum'``: the output elements will be summed.
2189
+
2190
+ margin (Union[Tensor, float]): Make a margin between the positive pair and the negative pair.
2191
+ Default: ``1.0`` .
2192
+
2193
+ Inputs:
2194
+ - **x** (Tensor) - A sample randomly selected from the training set. Data type must be BasicType.
2195
+ :math:`a` in the above formula.
2196
+ - **positive** (Tensor) - A sample belonging to the same category as `x`, with the same type and
2197
+ shape as `x`. :math:`p` in the above formula.
2198
+ - **negative** (Tensor) - A sample belonging to the different class from `x`, with the same type and shape
2199
+ as `x`. :math:`n` in the above formula.
2200
+ - **margin** (Union[Tensor, float]) - Make a margin between the positive pair and the negative pair.
2201
+ Default: ``1.0`` .
2202
+
2203
+ Outputs:
2204
+ Tensor. If `reduction` is ``"none"``, its shape is :math:`(N)`. Otherwise, a scalar value will be returned.
2205
+
2206
+ Raises:
2207
+ TypeError: If `x` or `positive` or 'negative' is not a Tensor.
2208
+ TypeError: If dtype of `x`, `positive` and `negative` is not the same.
2209
+ TypeError: If `p` is not an int.
2210
+ TypeError: If `eps` is not a float.
2211
+ TypeError: If `swap` is not a bool.
2212
+ ValueError: If dimensions of input `x`, `positive` and `negative` are less than or equal to 1 at the same time.
2213
+ ValueError: If the dimension of input `x` or `positive` or `negative` is bigger than or equal to 8.
2214
+ ValueError: If length of shape of `margin` is not 0.
2215
+ ValueError: If shape of `x`, `positive` and `negative` cannot broadcast.
2216
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
2217
+
2218
+ Supported Platforms:
2219
+ ``GPU``
2220
+
2221
+ Examples:
2222
+ >>> import mindspore as ms
2223
+ >>> import mindspore.nn as nn
2224
+ >>> import numpy as np
2225
+ >>> loss = nn.TripletMarginLoss()
2226
+ >>> x = ms.Tensor(np.array([[0.3, 0.7], [0.5, 0.5]]), ms.float32)
2227
+ >>> positive = ms.Tensor(np.array([[0.4, 0.6], [0.4, 0.6]]), ms.float32)
2228
+ >>> negative = ms.Tensor(np.array([[0.2, 0.9], [0.3, 0.7]]), ms.float32)
2229
+ >>> output = loss(x, positive, negative)
2230
+ >>> print(output)
2231
+ 0.8881968
2232
+ """
2233
+
2234
+ def __init__(self, p=2, swap=False, eps=1e-06, reduction="mean", margin=1.):
2235
+ super(TripletMarginLoss, self).__init__()
2236
+ self.p = p
2237
+ self.swap = swap
2238
+ self.eps = eps
2239
+ self.reduction = reduction
2240
+ self.margin = margin
2241
+
2242
+ def construct(self, x, positive, negative, margin=1.):
2243
+ if self.margin != 1.0:
2244
+ margin = self.margin
2245
+ return F.triplet_margin_loss(x, positive, negative, margin=margin, p=self.p,
2246
+ eps=self.eps, swap=self.swap, reduction=self.reduction)
2247
+
2248
+
2249
+ class NLLLoss(LossBase):
2250
+ r"""
2251
+ Gets the negative log likelihood loss between logits and labels.
2252
+
2253
+ The nll loss with :math:`reduction = none` can be described as:
2254
+
2255
+ .. math::
2256
+ \ell(x, t)=L=\left\{l_{1}, \ldots, l_{N}\right\}^{\top},
2257
+ \quad l_{n}=-w_{t_{n}} x_{n, t_{n}},
2258
+ \quad w_{c}=\text { weight }[c] \cdot \mathbb{1}\{c \not= \text{ignore_index}\}
2259
+
2260
+ where :math:`x` is the logits, :math:`t` is the labels, :math:`w` is the weight,
2261
+ :math:`N` is the batch size, :math:`c` belonging to :math:`[0, C-1]` is class index,
2262
+ where :math:`C` is the number of classes.
2263
+
2264
+ If :math:`reduction \neq none` (default ``'mean'`` ), then
2265
+
2266
+ .. math::
2267
+
2268
+ \ell(x, t)=\left\{\begin{array}{ll}
2269
+ \sum_{n=1}^{N} \frac{1}{\sum_{n=1}^{N} w_{t n}} l_{n}, & \text { if reduction }=\text { 'mean', } \\
2270
+ \sum_{n=1}^{N} l_{n}, & \text { if reduction }=\text { 'sum' }
2271
+ \end{array}\right.
2272
+
2273
+ Args:
2274
+ weight (Tensor): The rescaling weight to each class. If the value is not None, the shape is :math:`(C,)`.
2275
+ The data type only supports float32 or float16. Default: ``None`` .
2276
+ ignore_index (int): Specifies a target value that is ignored (typically for padding value)
2277
+ and does not contribute to the gradient. Default: ``-100`` .
2278
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2279
+ ``'sum'`` . Default: ``'mean'`` .
2280
+
2281
+ - ``'none'``: no reduction will be applied.
2282
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
2283
+ - ``'sum'``: the output elements will be summed.
2284
+
2285
+ Inputs:
2286
+ - **logits** (Tensor) - Tensor of shape :math:`(N, C)`
2287
+ or :math:`(N, C, d_1, d_2, ..., d_K)` for :math:`K`-dimensional data, where `C = number of classes`.
2288
+ Data type must be float16 or float32. `inputs` needs to be logarithmic probability.
2289
+ - **labels** (Tensor) -:math:`(N)` or :math:`(N, d_1, d_2, ..., d_K)` for :math:`K`-dimensional data.
2290
+ Data type must be int32.
2291
+
2292
+ Returns:
2293
+ Tensor, the computed negative log likelihood loss value.
2294
+
2295
+ Raises:
2296
+ TypeError: If `weight` is not a Tensor.
2297
+ TypeError: If `ignore_index` is not an int.
2298
+ TypeError: If the data type of `weight` is not float16 or float32.
2299
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
2300
+ TypeError: If `logits` is not a Tensor.
2301
+ TypeError: If `labels` is not a Tensor.
2302
+
2303
+ Supported Platforms:
2304
+ ``Ascend`` ``GPU`` ``CPU``
2305
+
2306
+ Examples:
2307
+ >>> import mindspore as ms
2308
+ >>> import mindspore.nn as nn
2309
+ >>> import numpy as np
2310
+ >>> logits = ms.Tensor(np.random.randn(3, 5), ms.float32)
2311
+ >>> labels = ms.Tensor(np.array([1, 0, 4]), ms.int32)
2312
+ >>> loss = nn.NLLLoss()
2313
+ >>> output = loss(logits, labels)
2314
+ """
2315
+
2316
+ def __init__(self, weight=None, ignore_index=-100, reduction='mean'):
2317
+ super().__init__(reduction)
2318
+ validator.check_value_type('ignore_index', ignore_index, int, self.cls_name)
2319
+ if weight is not None:
2320
+ validator.check_value_type("weight", weight, [Tensor], self.cls_name)
2321
+ validator.check_type_name('weight', weight.dtype, [mstype.float16, mstype.float32], self.cls_name)
2322
+
2323
+ self.weight = weight
2324
+ self.ignore_index = ignore_index
2325
+ self.reduction = reduction
2326
+
2327
+ def construct(self, logits, labels):
2328
+ return F.nll_loss(logits, labels, self.weight, self.ignore_index, self.reduction)
2329
+
2330
+
2331
+ @constexpr
2332
+ def _check_cross_entropy_inputs(logits_shape, label_shape,
2333
+ logits_rank, label_rank,
2334
+ logits_dtype, label_dtype,
2335
+ prim_name=None):
2336
+ """Internal function, used to check whether the shape of logits and labels meets the requirements."""
2337
+ validator.check_type_name('logits', logits_dtype, [mstype.float16, mstype.float32], prim_name)
2338
+
2339
+ msg_prefix = f'For \'{prim_name}\', the' if prim_name else "The"
2340
+ if logits_rank == label_rank:
2341
+ validator.check_type_name('labels', label_dtype, [mstype.float16, mstype.float32], prim_name)
2342
+ if logits_shape != label_shape:
2343
+ raise ValueError(f"{msg_prefix} shape of 'logits' should be (N, C, d_0, d_1, ...), "
2344
+ f"and the shape of 'labels' should be (N, C, d_0, d_1, ...), "
2345
+ f"but get 'logits' shape: {logits_shape} and 'labels' shape: {label_shape}.")
2346
+ elif label_rank == logits_rank - 1:
2347
+ validator.check_type_name('labels', label_dtype, [mstype.int32], prim_name)
2348
+ if logits_rank != 1:
2349
+ logits_shape_new = (logits_shape[0], *logits_shape[2:])
2350
+ if logits_shape_new != label_shape:
2351
+ raise ValueError(f"{msg_prefix} shape of 'logits' should be (N, C, d_0, d_1, ...), "
2352
+ f"and the shape of 'labels' should be (N, d_0, d_1, ...), "
2353
+ f"but get 'logits' shape: {logits_shape} and 'labels' shape: {label_shape}.")
2354
+ else:
2355
+ raise ValueError(f"{msg_prefix} rank of 'logits' and 'labels' should be:\n"
2356
+ f"1. 'logits.ndim == labels.ndim' for probabilities, \n"
2357
+ f"2. 'logits.ndim - 1 == labels.ndim' for class indices, \n"
2358
+ f"but get 'logits' rank: {logits_rank} and 'labels' rank: {label_rank}.")
2359
+
2360
+
2361
+ class CrossEntropyLoss(LossBase):
2362
+ r"""
2363
+ The cross entropy loss between input and target.
2364
+
2365
+ The CrossEntropyLoss support two kind of targets:
2366
+
2367
+ - Class indices (int) in the range :math:`[0, C)` where :math:`C` is the number of classes,
2368
+ when reduction is ``none``, the loss can be described as:
2369
+
2370
+ .. math::
2371
+
2372
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
2373
+ l_n = - w_{y_n} \log \frac{\exp(x_{n,y_n})}{\sum_{c=1}^C \exp(x_{n,c})}
2374
+ \cdot \mathbb{1}\{y_n \not= \text{ignore_index}\}
2375
+
2376
+ where :math:`x` is the inputs, :math:`t` is the target, :math:`w` is the weight,
2377
+ N is the batch size, :math:`c` belonging to [0, C-1] is class index, where :math:`C` is the number of classes.
2378
+
2379
+ If reduction is not ``'none'`` (default 'mean'), then
2380
+
2381
+ .. math::
2382
+
2383
+ \ell(x, y) = \begin{cases}
2384
+ \sum_{n=1}^N \frac{1}{\sum_{n=1}^N w_{y_n} \cdot \mathbb{1}\{y_n \not= \text{ignore_index}\}} l_n, &
2385
+ \text{if reduction} = \text{'mean',}\\
2386
+ \sum_{n=1}^N l_n, &
2387
+ \text{if reduction} = \text{'sum'.}
2388
+ \end{cases}
2389
+
2390
+ - Probabilities (float) for each class, useful when labels beyond a single class per minibatch item
2391
+ are required, the loss with reduction=none can be described as:
2392
+
2393
+ .. math::
2394
+
2395
+ \ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
2396
+ l_n = - \sum_{c=1}^C w_c \log \frac{\exp(x_{n,c})}{\sum_{i=1}^C \exp(x_{n,i})} y_{n,c}
2397
+
2398
+ where :math:`x` is the inputs, :math:`t` is the target, :math:`w` is the weight,
2399
+ N is the batch size, :math:`c` belonging to [0, C-1] is class index, where :math:`C` is the number of classes.
2400
+
2401
+ If reduction is not ``'none'`` (default 'mean'), then
2402
+
2403
+ .. math::
2404
+
2405
+ \ell(x, y) = \begin{cases}
2406
+ \frac{\sum_{n=1}^N l_n}{N}, &
2407
+ \text{if reduction} = \text{'mean',}\\
2408
+ \sum_{n=1}^N l_n, &
2409
+ \text{if reduction} = \text{'sum'.}
2410
+ \end{cases}
2411
+
2412
+ Args:
2413
+ weight (Tensor): The rescaling weight to each class. If the value is not None, the shape is :math:`(C,)`.
2414
+ The data type only supports float32 or float16. Default: ``None`` .
2415
+ ignore_index (int): Specifies a target value that is ignored (typically for padding value)
2416
+ and does not contribute to the gradient. Default: ``-100`` .
2417
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2418
+ ``'sum'`` . Default: ``'mean'`` .
2419
+
2420
+ - ``'none'``: no reduction will be applied.
2421
+ - ``'mean'``: compute and return the weighted mean of elements in the output.
2422
+ - ``'sum'``: the output elements will be summed.
2423
+
2424
+ label_smoothing (float): Label smoothing values, a regularization tool used to prevent the model
2425
+ from overfitting when calculating Loss. The value range is [0.0, 1.0]. Default value: ``0.0`` .
2426
+
2427
+ Inputs:
2428
+ - **logits** (Tensor) - Tensor of shape :math:`(C,)` :math:`(N, C)` or :math:`(N, C, d_1, d_2, ..., d_K)`,
2429
+ where `C = number of classes`. Data type must be float16 or float32.
2430
+ - **labels** (Tensor) - For class indices, tensor of shape :math:`()`, :math:`(N)` or
2431
+ :math:`(N, d_1, d_2, ..., d_K)` , data type must be int32.
2432
+ For probabilities, tensor of shape :math:`(C,)` :math:`(N, C)` or :math:`(N, C, d_1, d_2, ..., d_K)` ,
2433
+ data type must be float16 or float32.
2434
+
2435
+ Returns:
2436
+ Tensor, the computed cross entropy loss value.
2437
+
2438
+ Raises:
2439
+ TypeError: If `weight` is not a Tensor.
2440
+ TypeError: If `ignore_index` is not an int.
2441
+ TypeError: If the data type of `weight` is not float16 or float32.
2442
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
2443
+ TypeError: If `label_smoothing` is not a float.
2444
+ TypeError: If `logits` is not a Tensor.
2445
+ TypeError: If `labels` is not a Tensor.
2446
+
2447
+ Supported Platforms:
2448
+ ``Ascend`` ``GPU`` ``CPU``
2449
+
2450
+ Examples:
2451
+ >>> import mindspore as ms
2452
+ >>> import mindspore.nn as nn
2453
+ >>> import numpy as np
2454
+ >>> # Case 1: Indices labels
2455
+ >>> inputs = ms.Tensor(np.random.randn(3, 5), ms.float32)
2456
+ >>> target = ms.Tensor(np.array([1, 0, 4]), ms.int32)
2457
+ >>> loss = nn.CrossEntropyLoss()
2458
+ >>> output = loss(inputs, target)
2459
+ >>> # Case 2: Probability labels
2460
+ >>> inputs = ms.Tensor(np.random.randn(3, 5), ms.float32)
2461
+ >>> target = ms.Tensor(np.random.randn(3, 5), ms.float32)
2462
+ >>> loss = nn.CrossEntropyLoss()
2463
+ >>> output = loss(inputs, target)
2464
+ """
2465
+
2466
+ def __init__(self, weight=None, ignore_index=-100, reduction='mean',
2467
+ label_smoothing=0.0):
2468
+ super().__init__(reduction)
2469
+ validator.check_value_type('ignore_index', ignore_index, int, self.cls_name)
2470
+ validator.check_value_type('label_smoothing', label_smoothing, float, self.cls_name)
2471
+ validator.check_float_range(label_smoothing, 0.0, 1.0, validator.INC_BOTH, 'label_smoothing', self.cls_name)
2472
+
2473
+ if weight is not None:
2474
+ validator.check_value_type("weight", weight, [Tensor], self.cls_name)
2475
+ validator.check_type_name('weight', weight.dtype, [mstype.float16, mstype.float32], self.cls_name)
2476
+
2477
+ self.weight = weight
2478
+ self.ignore_index = ignore_index
2479
+ self.reduction = reduction
2480
+ self.label_smoothing = label_smoothing
2481
+
2482
+ def construct(self, logits, labels):
2483
+ _check_is_tensor('logits', logits, self.cls_name)
2484
+ _check_is_tensor('labels', labels, self.cls_name)
2485
+ _check_cross_entropy_inputs(logits.shape, labels.shape,
2486
+ logits.ndim, labels.ndim,
2487
+ logits.dtype, labels.dtype,
2488
+ self.cls_name)
2489
+
2490
+ return F.cross_entropy(logits, labels, self.weight, self.ignore_index, self.reduction, self.label_smoothing)
2491
+
2492
+
2493
+ class KLDivLoss(LossBase):
2494
+ r"""
2495
+ Computes the Kullback-Leibler divergence between the `logits` and the `labels`.
2496
+
2497
+ For tensors of the same shape :math:`x` and :math:`target`,
2498
+ the updating formulas of KLDivLoss algorithm are as follows,
2499
+
2500
+ .. math::
2501
+ L(x, target) = target \cdot (\log target - x)
2502
+
2503
+ Then,
2504
+
2505
+ .. math::
2506
+ \ell(x, target) = \begin{cases}
2507
+ L(x, target), & \text{if reduction} = \text{'none';}\\
2508
+ \operatorname{mean}(L(x, target)), & \text{if reduction} = \text{'mean';}\\
2509
+ \operatorname{sum}(L(x, target)) / x.\operatorname{shape}[0], & \text{if reduction} = \text{'batchmean';}\\
2510
+ \operatorname{sum}(L(x, target)), & \text{if reduction} = \text{'sum'.}
2511
+ \end{cases}
2512
+
2513
+ where :math:`x` represents `logits`,
2514
+ :math:`target` represents `labels`, and
2515
+ :math:`\ell(x, target)` represents `output`.
2516
+
2517
+ Note:
2518
+ - Currently it does not support float64 input on `Ascend`.
2519
+ - The output aligns with the mathematical definition of Kullback-Leibler divergence
2520
+ only when `reduction` is set to 'batchmean'.
2521
+
2522
+ Args:
2523
+ reduction (str): Specifies the reduction to be applied to the output. Default: ``'mean'`` .
2524
+
2525
+ - On Ascend, the value of `reduction` must be one of ``'batchmean'`` , ``'none'`` or ``'sum'`` .
2526
+ - On GPU, the value of `reduction` must be one of ``'mean'`` , ``'none'`` or ``'sum'`` .
2527
+ - On CPU, the value of `reduction` must be one of ``'mean'`` , ``'batchmean'`` , ``'none'`` or ``'sum'`` .
2528
+
2529
+ Inputs:
2530
+ - **logits** (Tensor) - The input Tensor. The data type must be float16, float32 or float64.
2531
+ - **labels** (Tensor) - The label Tensor which has the same shape and data type as `logits`.
2532
+
2533
+ Outputs:
2534
+ Tensor or Scalar, if `reduction` is ``'none'``, then output is a tensor and has the same shape as `logits`.
2535
+ Otherwise, it is a scalar.
2536
+
2537
+ Raises:
2538
+ TypeError: If `reduction` is not a str.
2539
+ TypeError: If neither `logits` nor `labels` is a Tensor.
2540
+ TypeError: If dtype of `logits` or `labels` is not currently supported.
2541
+ ValueError: If shape of `logits` is not the same as `labels`.
2542
+ RuntimeError: If `logits` or `labels` is a scalar when `reduction` is 'batchmean'.
2543
+
2544
+ Supported Platforms:
2545
+ ``Ascend`` ``GPU`` ``CPU``
2546
+
2547
+ Examples:
2548
+ >>> import mindspore as ms
2549
+ >>> import mindspore.nn as nn
2550
+ >>> import numpy as np
2551
+ >>> logits = ms.Tensor(np.array([0.2, 0.7, 0.1]), ms.float32)
2552
+ >>> labels = ms.Tensor(np.array([0., 1., 0.]), ms.float32)
2553
+ >>> loss = nn.KLDivLoss(reduction='mean')
2554
+ >>> output = loss(logits, labels)
2555
+ >>> print(output)
2556
+ -0.23333333
2557
+ """
2558
+
2559
+ def __init__(self, reduction='mean'):
2560
+ super().__init__()
2561
+ self.reduction = reduction
2562
+
2563
+ def construct(self, logits, labels):
2564
+ _check_is_tensor('logits', logits, self.cls_name)
2565
+ _check_is_tensor('labels', labels, self.cls_name)
2566
+ return F.kl_div(logits, labels, self.reduction)
2567
+
2568
+
2569
+ @_primexpr
2570
+ def _check_ctcloss_targets_shape(targets):
2571
+ """Internal function, used to check whether the shape of CTC targets meets the requirements."""
2572
+ if targets.ndim > 2:
2573
+ raise ValueError(f"For CTCLoss, when the shape of log_probs is (T, C), the dimension of targets should"
2574
+ f"be 1 or 2, but got {targets.ndim}.")
2575
+ if targets.ndim == 2 and targets.shape[0] != 1:
2576
+ raise ValueError(f"For CTCLoss, the first dimension of 2-D targets should be 1,"
2577
+ f"but got {targets.shape[0]}.")
2578
+
2579
+
2580
+ class CTCLoss(LossBase):
2581
+ """
2582
+ Calculates the CTC (Connectionist Temporal Classification) loss. It's mainly used to calculate the loss between
2583
+ the continuous, unsegemented time series and the target series.
2584
+
2585
+ For the CTC algorithm, refer to `Connectionist Temporal Classification: Labeling Unsegmented Sequence Data with
2586
+ Recurrent Neural Networks <http://www.cs.toronto.edu/~graves/icml_2006.pdf>`_ .
2587
+
2588
+ Args:
2589
+ blank (int, optional): The blank label. Default: ``0`` .
2590
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2591
+ ``'sum'`` . Default: ``'mean'`` .
2592
+
2593
+ - ``'none'``: no reduction will be applied.
2594
+ - ``'mean'``: compute and return the mean of elements in the output.
2595
+ - ``'sum'``: the output elements will be summed.
2596
+
2597
+ zero_infinity (bool, optional): If loss is infinite, this parameter determines whether to set that loss
2598
+ and its correlated gradient to zero. Default: ``False`` .
2599
+
2600
+ Inputs:
2601
+ - **log_probs** (Tensor) - A tensor of shape :math:`(T, N, C)` or :math:`(T, C)`, where T is length of input,
2602
+ N is size of the batch and C is the number of classes. T, N and C are positive integers.
2603
+ - **targets** (Tensor) - A tensor of shape :math:`(N, S)` or (sum( `target_lengths` )),
2604
+ where S is max target length, means the target sequences.
2605
+ - **input_lengths** (Union[tuple, Tensor]) - A tuple or Tensor of shape :math:`(N)`.
2606
+ It means the lengths of the input.
2607
+ - **target_lengths** (Union[tuple, Tensor]) - A tuple or Tensor of shape :math:`(N)`.
2608
+ It means the lengths of the target.
2609
+
2610
+ Outputs:
2611
+ - **neg_log_likelihood** (Tensor) - A loss value which is differentiable with respect to each input node.
2612
+
2613
+ Raises:
2614
+ TypeError: If `log_probs` or `targets` is not a Tensor.
2615
+ TypeError: If `zero_infinity` is not a bool, `reduction` is not string.
2616
+ TypeError: If the dtype of `log_probs` is not float or double.
2617
+ TypeError: If the dtype of `targets`, `input_lengths` or `target_lengths` is not int32 or int64.
2618
+ ValueError: If `reduction` is not ``"none"``, ``"mean"`` or ``"sum"``.
2619
+ ValueError: If the value of `blank` is not in range [0, C). C is number of classes of `log_probs` .
2620
+ ValueError: If the shape of `log_probs` is :math:`(T, C)`, the dimension of `targets` is not 1 or 2.
2621
+ ValueError: If the shape of `log_probs` is :math:`(T, C)`, the first dimension of 2-D `target` is not 1.
2622
+ RuntimeError: If any value of `input_lengths` is larger than T. T is length of `log_probs` .
2623
+ RuntimeError: If any target_lengths[i] is not in range [0, input_length[i]].
2624
+
2625
+ Supported Platforms:
2626
+ ``Ascend`` ``GPU`` ``CPU``
2627
+
2628
+ Examples:
2629
+ >>> import mindspore as ms
2630
+ >>> import mindspore.nn as nn
2631
+ >>> import numpy as np
2632
+ >>> T = 5 # Input sequence length
2633
+ >>> C = 2 # Number of classes
2634
+ >>> N = 2 # Batch size
2635
+ >>> S = 3 # Target sequence length of longest target in batch (padding length)
2636
+ >>> S_min = 2 # Minimum target length, for demonstration purposes
2637
+ >>> arr = np.arange(T*N*C).reshape((T, N, C))
2638
+ >>> ms_input = ms.Tensor(arr, dtype=ms.float32)
2639
+ >>> input_lengths = np.full(shape=(N), fill_value=T)
2640
+ >>> input_lengths = ms.Tensor(input_lengths, dtype=ms.int32)
2641
+ >>> target_lengths = np.full(shape=(N), fill_value=S_min)
2642
+ >>> target_lengths = ms.Tensor(target_lengths, dtype=ms.int32)
2643
+ >>> target = np.random.randint(1, C, size=(N, S))
2644
+ >>> target = ms.Tensor(target, dtype=ms.int32)
2645
+ >>> ctc_loss = nn.CTCLoss(blank=0, reduction='none', zero_infinity=False)
2646
+ >>> loss = ctc_loss(ms_input, target, input_lengths, target_lengths)
2647
+ >>> print(loss)
2648
+ [-45.79497 -55.794968]
2649
+ >>> arr = np.arange(T*C).reshape((T, C))
2650
+ >>> ms_input = ms.Tensor(arr, dtype=ms.float32)
2651
+ >>> input_lengths = ms.Tensor([T], dtype=ms.int32)
2652
+ >>> target_lengths = ms.Tensor([S_min], dtype=ms.int32)
2653
+ >>> target = np.random.randint(1, C, size=(S_min,))
2654
+ >>> target = ms.Tensor(target, dtype=ms.int32)
2655
+ >>> ctc_loss = nn.CTCLoss(blank=0, reduction='none', zero_infinity=False)
2656
+ >>> loss = ctc_loss(ms_input, target, input_lengths, target_lengths)
2657
+ >>> print(loss)
2658
+ -25.794968
2659
+ """
2660
+
2661
+ def __init__(self, blank=0, reduction='mean', zero_infinity=False):
2662
+ super().__init__()
2663
+ self.blank = blank
2664
+ self.reduction = reduction
2665
+ self.zero_infinity = zero_infinity
2666
+
2667
+ def construct(self, log_probs, targets, input_lengths, target_lengths):
2668
+ _check_is_tensor('log_probs', log_probs, self.cls_name)
2669
+ _check_is_tensor('targets', targets, self.cls_name)
2670
+ if log_probs.ndim == 2:
2671
+ _check_ctcloss_targets_shape(targets)
2672
+ if targets.ndim == 1:
2673
+ targets = targets.expand_dims(0)
2674
+ log_probs = log_probs.expand_dims(-2)
2675
+ neg_log_hood, _ = F.ctc_loss(log_probs, targets, input_lengths, target_lengths, self.blank, self.reduction,
2676
+ self.zero_infinity)
2677
+ return neg_log_hood.squeeze(axis=0)
2678
+ neg_log_hood, _ = F.ctc_loss(log_probs, targets, input_lengths, target_lengths, self.blank, self.reduction,
2679
+ self.zero_infinity)
2680
+ return neg_log_hood
2681
+
2682
+
2683
+ class GaussianNLLLoss(LossBase):
2684
+ r"""
2685
+ Gaussian negative log likelihood loss.
2686
+
2687
+ The target values are considered to be samples from a Gaussian distribution, where the expectation and variance are
2688
+ predicted by a neural network. For `labels` modeled on a Gaussian distribution, `logits` to record expectations,
2689
+ and the variance `var` (elements are all positive), the calculated loss is:
2690
+
2691
+ .. math::
2692
+ \text{loss} = \frac{1}{2}\left(\log\left(\text{max}\left(\text{var},
2693
+ \ \text{eps}\right)\right) + \frac{\left(\text{logits} - \text{labels}\right)^2}
2694
+ {\text{max}\left(\text{var}, \ \text{eps}\right)}\right) + \text{const.}
2695
+
2696
+ where :math:`eps` is used for stability of :math:`log`. When :math:`full=True`, a constant will be added to
2697
+ the loss. If the shape of :math:`var` and :math:`logits` are not the same (due to a homoscedastic assumption),
2698
+ their shapes must allow correct broadcasting.
2699
+
2700
+ Keyword Args:
2701
+ full (bool, optional): Whether include the constant term in the loss calculation. When :math:`full=True`,
2702
+ the constant term `const.` will be :math:`0.5 * log(2\pi)`. Default: ``False`` .
2703
+ eps (float, optional): Used to improve the stability of log function. Default: ``1e-6`` .
2704
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2705
+ ``'sum'`` . Default: ``'mean'`` .
2706
+
2707
+ - ``'none'``: no reduction will be applied.
2708
+ - ``'mean'``: compute and return the mean of elements in the output.
2709
+ - ``'sum'``: the output elements will be summed.
2710
+
2711
+ Inputs:
2712
+ - **logits** (Tensor) - Tensor of shape :math:`(N, *)` or :math:`(*)` where :math:`*` means any number of
2713
+ additional dimensions.
2714
+ - **labels** (Tensor) - Tensor of shape :math:`(N, *)` or :math:`(*)`, same shape as the logits, or same shape
2715
+ as the logits but with one dimension equal to 1 (to allow for broadcasting).
2716
+ - **var** - Tensor of shape :math:`(N, *)` or :math:`(*)`, same shape as logits, or same shape as the logits
2717
+ but with one dimension equal to 1, or same shape as the logits but with one fewer dimension
2718
+ (to allow for broadcasting).
2719
+
2720
+ Returns:
2721
+ Tensor or Tensor scalar, the computed loss depending on :math:`reduction`.
2722
+
2723
+ Raises:
2724
+ TypeError: If `logits` is not a Tensor.
2725
+ TypeError: If `labels` is not a Tensor.
2726
+ TypeError: If `full` is not a bool.
2727
+ TypeError: If `eps` is not a float.
2728
+ ValueError: If `eps` is not a float within (0, inf).
2729
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
2730
+
2731
+ Supported Platforms:
2732
+ ``Ascend`` ``GPU`` ``CPU``
2733
+
2734
+ Examples:
2735
+ >>> import mindspore as ms
2736
+ >>> import mindspore.nn as nn
2737
+ >>> import numpy as np
2738
+ >>> arr1 = np.arange(8).reshape((4, 2))
2739
+ >>> arr2 = np.array([2, 3, 1, 4, 6, 4, 4, 9]).reshape((4, 2))
2740
+ >>> logits = ms.Tensor(arr1, ms.float32)
2741
+ >>> labels = ms.Tensor(arr2, ms.float32)
2742
+ >>> loss = nn.GaussianNLLLoss(reduction='mean')
2743
+ >>> var = ms.Tensor(np.ones((4, 1)), ms.float32)
2744
+ >>> output = loss(logits, labels, var)
2745
+ >>> print(output)
2746
+ 1.4374993
2747
+
2748
+ Reference:
2749
+ Nix, D. A. and Weigend, A. S., "Estimating the mean and variance of the
2750
+ target probability distribution", Proceedings of 1994 IEEE International
2751
+ Conference on Neural Networks (ICNN'94), Orlando, FL, USA, 1994, pp. 55-60
2752
+ vol.1, doi: 10.1109/ICNN.1994.374138.
2753
+ """
2754
+
2755
+ def __init__(self, *, full=False, eps=1e-6, reduction='mean'):
2756
+ super(GaussianNLLLoss, self).__init__()
2757
+ validator.check_float_range(eps, 0, float('inf'), validator.INC_NEITHER, "eps", self.cls_name)
2758
+ validator.check_value_type('full', full, [bool], self.cls_name)
2759
+ validator.check_string(reduction, ['none', 'mean', 'sum'], 'reduction', 'gaussian_nll_loss')
2760
+ self.full = full
2761
+ self.eps = eps
2762
+ self.reduction = reduction
2763
+
2764
+ def construct(self, logits, labels, var):
2765
+ _check_is_tensor('logits', logits, self.cls_name)
2766
+ _check_is_tensor('labels', labels, self.cls_name)
2767
+ _check_is_tensor('var', var, self.cls_name)
2768
+ return ops.gaussian_nll_loss(logits, labels, var, self.full, self.eps, self.reduction)
2769
+
2770
+
2771
+ class HingeEmbeddingLoss(LossBase):
2772
+ r"""
2773
+ Calculate the Hinge Embedding Loss value based on the input 'logits' and' labels' (only including 1 or -1).
2774
+ Usually used to measure the similarity between two inputs.
2775
+
2776
+ The loss function for :math:`n`-th sample in the mini-batch is
2777
+
2778
+ .. math::
2779
+ l_n = \begin{cases}
2780
+ x_n, & \text{if}\; y_n = 1,\\
2781
+ \max \{0, \Delta - x_n\}, & \text{if}\; y_n = -1,
2782
+ \end{cases}
2783
+
2784
+ and the total loss functions is
2785
+
2786
+ .. math::
2787
+ \ell(x, y) = \begin{cases}
2788
+ \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\
2789
+ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.}
2790
+ \end{cases}
2791
+
2792
+ where :math:`L = \{l_1,\dots,l_N\}^\top`.
2793
+
2794
+ Args:
2795
+ margin (float, int): Threshold defined by Hinge Embedding Loss :math:`margin`.
2796
+ Represented as :math:`\Delta` in the formula. Default: ``1.0`` .
2797
+ reduction (str, optional): Apply specific reduction method to the output: ``'none'`` , ``'mean'`` ,
2798
+ ``'sum'`` . Default: ``'mean'`` .
2799
+
2800
+ - ``'none'``: no reduction will be applied.
2801
+ - ``'mean'``: compute and return the mean of elements in the output.
2802
+ - ``'sum'``: the output elements will be summed.
2803
+
2804
+ Inputs:
2805
+ - **logits** (Tensor) - The predicted value, expressed as :math:`x` in the equation.
2806
+ Tensor of shape :math:`(*)` where :math:`*` means any number of dimensions.
2807
+ - **labels** (Tensor) - Label value, represented as :math:`y` in the equation.
2808
+ Same shape as the logits, contains -1 or 1.
2809
+
2810
+ Returns:
2811
+ Tensor or Tensor scalar, the computed loss depending on :math:`reduction`.
2812
+
2813
+ Raises:
2814
+ TypeError: If `logits` is not a Tensor.
2815
+ TypeError: If `labels` is not a Tensor.
2816
+ TypeError: If `margin` is not a float or int.
2817
+ ValueError: If `labels` does not have the same shape as `logits` or they could not broadcast to each other.
2818
+ ValueError: If `reduction` is not one of ``'none'``, ``'mean'``, ``'sum'``.
2819
+
2820
+ Supported Platforms:
2821
+ ``Ascend`` ``GPU`` ``CPU``
2822
+
2823
+ Examples:
2824
+ >>> import mindspore as ms
2825
+ >>> import mindspore.nn as nn
2826
+ >>> import numpy as np
2827
+ >>> arr1 = np.array([0.9, -1.2, 2, 0.8, 3.9, 2, 1, 0, -1]).reshape((3, 3))
2828
+ >>> arr2 = np.array([1, 1, -1, 1, -1, 1, -1, 1, 1]).reshape((3, 3))
2829
+ >>> logits = ms.Tensor(arr1, ms.float32)
2830
+ >>> labels = ms.Tensor(arr2, ms.float32)
2831
+ >>> loss = nn.HingeEmbeddingLoss(reduction='mean')
2832
+ >>> output = loss(logits, labels)
2833
+ >>> print(output)
2834
+ 0.16666667
2835
+ """
2836
+
2837
+ def __init__(self, margin=1.0, reduction='mean'):
2838
+ super(HingeEmbeddingLoss, self).__init__()
2839
+ validator.check_value_type('margin', margin, [float, int], self.cls_name)
2840
+ validator.check_string(reduction, ['none', 'sum', 'mean'], 'reduction', self.cls_name)
2841
+ self.margin = margin
2842
+ self.reduction = reduction
2843
+
2844
+ def construct(self, logits, labels):
2845
+ loss = ops.hinge_embedding_loss(logits, labels, self.margin, self.reduction)
2846
+ return loss