Compare commits

...
367 Commits
Author SHA1 Message Date
i-robot f88a00a21a !2470 [Feature] Add testcase for custom operator npu_multi_head_attention
Merge pull request !2470 from rui_everAfter/mha
2023-03-08 06:19:57 +00:00
i-robot 56f3bb219b !2465 [Feature] Add testcase for custom operator npu_lstm
Merge pull request !2465 from rui_everAfter/analysis-0228
2023-03-08 06:19:06 +00:00
i-robot a538497f59 !2484 [Feature] Add NpuFusedAdamW and fused clip_grad_norm()
Merge pull request !2484 from 郭鹏/feature/v1.11.0-fusedoptim
2023-03-08 06:15:54 +00:00
i-robot 19cd190e3f !2468 Add seq id in CallStack.
Merge pull request !2468 from 裘凯达/master
2023-03-07 01:36:10 +00:00
i-robot 0b2ab39356 !2512 [Fix] modify onnx export of npu_dropout_with_add_softmax op.
Merge pull request !2512 from Zhang Yingxin/up_master
2023-03-06 13:32:16 +00:00
i-robot 603afe6766 !2500 [fix] fix datadump bugs
Merge pull request !2500 from xudaohong/master
2023-03-06 12:23:27 +00:00
zhang-aurora ae8127baa1 modify onnx export of npu_dropout_with_add_softmax op 2023-03-04 14:53:04 +08:00
x00430237 4ecb83fbce [fix] fix datadump bugs 2023-03-04 14:42:52 +08:00
gp513 512ee2b65b supports fused optimizer AdamW and fused clip_grad_norm
bugfix
2023-03-04 10:33:02 +08:00
i-robot f5e0cc1f07 !2505 [Feature] Add onnx export of npu_gru
Merge pull request !2505 from Zhang Yingxin/add_ops
2023-03-03 09:51:15 +00:00
zhang-aurora e926388805 Add onnx export of npu_gru 2023-03-03 16:55:05 +08:00
王铭锐 2d4d1e5a1b Add testcase for custom operator npu_lstm 2023-03-03 11:25:08 +08:00
i-robot 4fde9fa1b9 !2499 [Feature] part2: add custom ops wrapper to export onnx
Merge pull request !2499 from Zhang Yingxin/add_ops
2023-03-03 03:15:29 +00:00
i-robot 3cec1c1cfe !2451 [Refactor]remove BUILD_LIBTORCH compiler options from the header file of libtorch_npu.
Merge pull request !2451 from huangyunlong/feature_libtorch
2023-03-03 03:02:41 +00:00
王铭锐 f532c9b752 Add testcase for custom operator npu_multi_head_attention 2023-03-03 11:02:22 +08:00
zhang-aurora 906726d910 add custom ops wrapper to export onnx 2023-03-03 10:16:36 +08:00
i-robot d36d0ec290 !2489 Don't split oversize cached blocks in memory management.
Merge pull request !2489 from 闫鹏全/master
2023-03-02 12:41:50 +00:00
i-robot 77b6fb806e !2485 [Feature] Combined onnx ops export and testcases
Merge pull request !2485 from Zhang Yingxin/local_master
2023-03-02 12:16:25 +00:00
i-robot cb1d8a2c28 !2493 Optimize the performance of the pow operator.
Merge pull request !2493 from 郑亚金/master_zyj_pow_mul_0302
2023-03-02 12:13:40 +00:00
闫鹏全 42af859b44 Don't split oversize cached blocks. 2023-03-02 18:47:26 +08:00
zhang-aurora 38a0e62a3e Combined onnx ops export and testcases 2023-03-02 17:13:13 +08:00
郑亚金 ddee779f77 When the operand of the pow operator is of the scalar is two, call the mul operator. 2023-03-02 14:27:30 +08:00
i-robot 756dbca545 !2480 [BugFix]Full operation fill with dtype inferred from fill_value.
Merge pull request !2480 from 邵非凡/full-1.11
2023-03-02 03:27:26 +00:00
i-robot d4626a9fa0 !2467 [Feature] Allow user to specify a fraction of the NPU memory.
Merge pull request !2467 from 闫鹏全/redo_fraction
2023-03-02 03:23:37 +00:00
cudi 28a1634b9a Add seq number in CallStack. 2023-03-02 10:24:35 +08:00
i-robot 46667a35f1 !2475 [BugFix]e2e profiling compatible with old lite-profiling
Merge pull request !2475 from 王恒/master-local-3
2023-03-01 11:09:35 +00:00
邵非凡 31a1abcedd Full operation fill with dtype inferred from fill_value. 2023-03-01 16:19:44 +08:00
i-robot 4e10b42dcb !2479 Add allgather_base function
Merge pull request !2479 from hanjun/master
2023-03-01 07:27:46 +00:00
wang--heng 68935fd96f e2e profiling compatible with old lite-profiling 2023-03-01 12:18:46 +08:00
尤安升 79131f0ed7 update OWNERS. 2023-03-01 03:50:44 +00:00
h00558267 195973bfaa Add allgather_base
Add allgather_base
2023-03-01 09:27:28 +08:00
i-robot 7e42915d22 !2453 [Fix] optimize error message in hccl.
Merge pull request !2453 from 施博/fix_hccl
2023-03-01 01:17:38 +00:00
i-robot 6fb2529e7b !2438 [Feature] Export ONNX for combined ops
Merge pull request !2438 from Zhang Yingxin/local_master
2023-02-28 13:06:54 +00:00
i-robot 026318d011 !2463 Add per-device allocator object.
Merge pull request !2463 from 闫鹏全/master
2023-02-28 12:35:58 +00:00
i-robot 0c84bc5ac1 !2448 Supports torch.distributed._reduce_scatter_base() on NPU
Merge pull request !2448 from 郭鹏/feature/_reduce_scatter_base
2023-02-28 12:30:31 +00:00
i-robot 170b08e0d2 !2424 [Feature] Add switch allowinternalformat to enable internal format or ND format
Merge pull request !2424 from 王强/master
2023-02-28 12:23:46 +00:00
闫鹏全 0fb902e015 Add memory fraction function for NPU memory management. 2023-02-28 17:18:41 +08:00
i-robot 06b60acb9e !2403 [Feature] Add tests for npu_grid_assign_positive and npu_convolution_transpose.
Merge pull request !2403 from 叶灵煜/custom_op_0222
2023-02-28 09:03:20 +00:00
i-robot 0f17858241 !2406 [Feature] Add base support for fused optimizer and add fused SGD
Merge pull request !2406 from lj_new/master
2023-02-28 07:24:02 +00:00
zhang-aurora 24bb368bcc Export ONNX for combined ops 2023-02-28 15:07:07 +08:00
闫鹏全 95ae807b6d Add per-device allocator object. 2023-02-28 14:56:10 +08:00
shibo19 f118eb1083 optimize error message in hccl 2023-02-28 14:43:35 +08:00
gp513 7e09a22788 supports torch.distributed._reduce_scatter_base()
bugfix
2023-02-28 14:38:37 +08:00
lijing 144bc77742 Add base support for fused optimizer, add fused sgd
Use raise error method instead of abstractmethod

Use enumerate instead of range

Move fused optimizer to torch_npu

Rename fused optimizer to npu fused optimizer

Rename fused sgd to npu fused sgd

Remove unused arguments
2023-02-28 14:33:23 +08:00
i-robot 5122896b91 !2423 [BugFix] API get_device_properties compatibility is maintained with CUDA
Merge pull request !2423 from yangxiaorun/bugfix_get_device_properties
2023-02-28 06:21:51 +00:00
i-robot 32d70b4038 !2434 Add testcase for npu_pad, npu_ptiou and sign_bits_umpack.
Merge pull request !2434 from shaoyf/onnx_testcase_1
2023-02-28 06:11:39 +00:00
huangyunlong 5663059394 [Refactor]remove BUILD_LIBTORCH compiler options from the header file of libtorch. 2023-02-28 11:02:32 +08:00
i-robot 96b8b009a2 !2454 use correct param when calling assert_never in get_kernel
Merge pull request !2454 from dilililiwhy/master
2023-02-28 01:44:51 +00:00
i-robot 6900aae386 !2450 Update the configuration information of BiShengCPP.
Merge pull request !2450 from shaoyf/bishengcpp_test_1
2023-02-27 13:01:18 +00:00
i-robot 6523535ba9 !2457 [BugFix] restore old e2e profiling
Merge pull request !2457 from 王恒/master-local-2
2023-02-27 12:18:15 +00:00
wang--heng 9f68ec2cbb restore old e2e profiling 2023-02-27 19:22:08 +08:00
dilililiWhy 8eddb4b6a3 use correct param when calling assert_never in get_kernel 2023-02-27 18:07:49 +08:00
叶灵煜 d338cd358c Add testcases for custom torch_npu ops.
Signed-off-by: 叶灵煜 <yelingyu@huawei.com>
2023-02-27 16:37:27 +08:00
i-robot 938fb1f720 !2331 [Feature] Add test for npu_conv2d, npu_conv3d and npu_conv_transpose2d.
Merge pull request !2331 from 杜金航/master
2023-02-27 08:11:30 +00:00
i-robot 7bef164a6d !2446 Refactor codegen & make sure clean of setup succeed.
Merge pull request !2446 from 尤安升/master
2023-02-27 07:35:39 +00:00
尤安升 df2f34de5b Refactor codegen & make sure clean of setup succeed. 2023-02-27 14:35:49 +08:00
shaoyf fb8e4aaf13 Update the configuration information of BiShengCPP. 2023-02-27 11:25:58 +08:00
wq160 416303682f [Feature] Add switch allow_internal_format to enable internal format or ND format 2023-02-27 10:36:17 +08:00
i-robot 2383422b68 !2397 [BugFix] Fix embedding_bag in 0D scenario.
Merge pull request !2397 from 戢芳/embedding1.11
2023-02-27 01:24:36 +00:00
i-robot c779c72c50 !2327 Relax the interception condition of Index operator.
Merge pull request !2327 from 刘哲续/master
2023-02-26 08:18:34 +00:00
尤安升 750ff7fe4f Remove unused code. 2023-02-25 16:38:18 +08:00
i-robot 81d672880e !2443 Relocate c10d headers according to origin pytorch.
Merge pull request !2443 from 尤安升/master
2023-02-25 07:10:02 +00:00
尤安升 4afddfcb8f Relocate c10d headers according to origin pytorch. 2023-02-25 14:10:03 +08:00
i-robot 0e515a7f2a !2432 [Fix] fix libtorch build bug
Merge pull request !2432 from 施博/up_master_build
2023-02-24 03:59:16 +00:00
shaoyf 219738354c Add testcase for npu_pad, npu_ptiou and sign_bits_umpack. 2023-02-24 11:40:50 +08:00
shibo19 185b7b4e0a fix libtorch build bug 2023-02-24 10:32:40 +08:00
yangxiaorun 0a0b9bb852 fix: [BugFix] API compatibility is maintained with CUDA 2023-02-24 09:46:28 +08:00
i-robot c007ee1cbe !2360 [Fix] Update version 3.0.0 ReleaseNote .
Merge pull request !2360 from 彭子荣/master
2023-02-23 12:37:33 +00:00
i-robot f7357be81e !2318 [Feature] Upgrade replication_pad2d&reflection_pad2d to support 3D input.
Merge pull request !2318 from 戢芳/pad1.11
2023-02-23 12:28:30 +00:00
i-robot f3735572a7 !2417 [bugfix] Fix uniform kernel error.
Merge pull request !2417 from will-devil/bfmdev
2023-02-23 12:19:38 +00:00
i-robot adc1109bd6 !2396 [Fix]index_put supports the tensors of the input for different devices
Merge pull request !2396 from 王夏夏/master
2023-02-23 12:14:35 +00:00
i-robot a138577098 !2412 [Bugfix] Add “enable_overflow_npu” api for V2 interface of overflow detection.
Merge pull request !2412 from 谭親林/master
2023-02-23 09:22:40 +00:00
wangyicheng d8bdf54268 Fix uniform kernel error. 2023-02-23 17:00:04 +08:00
i-robot 8e08b7fb4c !2410 e2e profiling performance optimization
Merge pull request !2410 from 王恒/master-local
2023-02-23 08:18:55 +00:00
i-robot 7f787ff8d2 !2390 [Feature] Add tests for npu_fused_attention_layernorm_qkv_fwd, npu_convolution, fast_gelu, and npu_format_cast.
Merge pull request !2390 from 叶灵煜/custom_op_0221
2023-02-23 07:35:25 +00:00
i-robot dd8769799b !2401 [Fix]Improve test cases for npu_strided_copy.
Merge pull request !2401 from huangyunlong/feature_hyl
2023-02-23 07:33:42 +00:00
i-robot a27540b719 !2407 [Feature] Add test for npu_scatter.
Merge pull request !2407 from will-devil/scatterdev
2023-02-23 07:27:15 +00:00
i-robot af5e0f5dd9 !2387 [Feature] Add test for npu_layer_norm_eval.
Merge pull request !2387 from will-devil/layerdev
2023-02-23 07:26:50 +00:00
xiaxia3 68f90c1b80 [Fix]index_put supports the tensors of the input for different devices 2023-02-23 15:15:35 +08:00
tanqinlin 12068adce8 [Fix] add interface for overflow enable switch. 2023-02-23 14:40:28 +08:00
i-robot 0413b53608 !2354 ApplyAdamW adaptation
Merge pull request !2354 from 郑亚金/master_zyj_applyadamw_adaptation
2023-02-23 06:09:52 +00:00
wang--heng 1d6fc4fdcc e2e profiling optimization 2023-02-23 10:52:23 +08:00
i-robot fa1a698e7d !2352 [Fix] fix build shell bug on ubuntu with dash
Merge pull request !2352 from 施博/fix_build_shell
2023-02-23 02:02:43 +00:00
shibo19 eb13e4af2b fix build shell bug in ubuntu with dash 2023-02-23 09:52:37 +08:00
郑亚金 569eacd08c ApplyAdamW adaptation. 2023-02-23 09:43:20 +08:00
i-robot 64d507f32c !2404 [Bugfix] Check aclrtSetOpWaitTimeout interface.
Merge pull request !2404 from darin123/master
2023-02-23 01:34:26 +00:00
i-robot fd87b7f678 !2411 [Revert] Revert npu memory management.
Merge pull request !2411 from 闫鹏全/master
2023-02-22 12:30:22 +00:00
闫鹏全 ef47a4d8e3 Revert npu memory management. 2023-02-22 19:14:18 +08:00
i-robot 59bf37805f !2378 [Feature] Add test for npu_anchor_response_flags, npu_roi_align and npu_nms_rotated.
Merge pull request !2378 from huangyunlong/1.11npu
2023-02-22 07:51:45 +00:00
i-robot 6577976e8d !2348 [Feature] Add tests for npu_confusion_transpose, npu_ps_roi_pooling, and npu_softmax_cross_entropy_with_logits.
Merge pull request !2348 from 叶灵煜/custom_op_0216
2023-02-22 07:40:37 +00:00
i-robot 8ce20fe213 !2351 [Feature] Add testcases for npu_broadcast, npu_transpos, one_ and npu_one_hot
Merge pull request !2351 from Zhang Yingxin/local_master
2023-02-22 07:37:11 +00:00
wangyicheng ae965f2075 Add test for npu_scatter. 2023-02-22 15:29:25 +08:00
anping 11fc2307fb [Bugfix] Check aclrtSetOpWaitTimeout interface. 2023-02-22 14:10:44 +08:00
huangyunlong 3e5d81d509 [Fix]Improve test cases for npu_strided_copy. 2023-02-22 11:15:32 +08:00
pipihugh 7d4457922b Fix embedding_bag in 0D scenario. 2023-02-22 11:13:45 +08:00
wangyicheng bdae65f5b1 Add test for npu_layer_norm_eval 2023-02-22 09:59:12 +08:00
叶灵煜 181eec7fbc Add testcases for custom torch_npu ops. 2023-02-22 09:23:18 +08:00
i-robot 4dc80c4a96 !2381 [Feature] Allow user to specify a fraction of the NPU memory.
Merge pull request !2381 from 闫鹏全/fraction
2023-02-21 11:44:24 +00:00
i-robot 1ce31cec98 !2283 Upgrade syncbn_forward.
Merge pull request !2283 from 王夏夏/master
2023-02-21 08:39:13 +00:00
i-robot 47285663c7 !2286 [Fix]Index supports the tensors of the input for different devices.
Merge pull request !2286 from 王夏夏/master
2023-02-21 08:39:00 +00:00
i-robot ff1a542a04 !2305 [Feature] Add test for npu_stride_copy and npu_sort_v2.
Merge pull request !2305 from huangyunlong/feature_hyl
2023-02-21 08:38:30 +00:00
huangyunlong 5078ed052f [Feature] Add test for npu_anchor_response_flags, npu_roi_align and npu_nms_rotated 2023-02-21 16:19:07 +08:00
i-robot c4965940ae !2367 [Fix] Optimize Taskqueue
Merge pull request !2367 from 詹昊/taskqueue
2023-02-21 07:09:34 +00:00
zhanhao dffec8246c Optimize taskqueue. 2023-02-21 14:44:08 +08:00
i-robot e0c1ae859c !2385 [Feature] Register CPU backend.
Merge pull request !2385 from will-devil/cpudev2
2023-02-21 03:17:12 +00:00
闫鹏全 41814ccec9 Add memory fraction function for NPU memory management. 2023-02-21 10:55:09 +08:00
i-robot 517633ddab !2365 [Fix] Warning once when cast dtype to double.
Merge pull request !2365 from 刘嘉巍/ops
2023-02-21 02:04:29 +00:00
i-robot 88d08ed069 !2374 Report CANN opName to MsProfiler with TASK_QUEUE_ENABLE=1
Merge pull request !2374 from 裘凯达/master
2023-02-21 01:56:18 +00:00
i-robot 805722b01a !2353 Add per-device allocator object.
Merge pull request !2353 from 闫鹏全/master
2023-02-21 01:55:46 +00:00
wangyicheng e14cc14023 Register CPU backend. 2023-02-20 11:08:48 +08:00
cudi a5ac48d964 Report CANN opName to MsProfiler with TASK_ENABLE_ENABLE=1. 2023-02-20 10:37:20 +08:00
pipihugh 223f14ac04 Upgrade replication_pad2d&reflection_pad2d to support 3D input. 2023-02-20 10:25:13 +08:00
i-robot cb5e7854c5 !2133 [Refactor] Gen default value for C++ API and Correct backend from yaml.
Merge pull request !2133 from will-devil/defaultdev
2023-02-20 01:35:30 +00:00
叶灵煜 ecb82ae3f0 Add testcases for custom torch_npu ops.
Signed-off-by: 叶灵煜 <yelingyu@huawei.com>
2023-02-19 18:35:02 +08:00
闫鹏全 adf91cf9cc Add per-device allocator object. 2023-02-18 17:11:53 +08:00
刘嘉巍 050a42f571 warn_once when cast double dtype 2023-02-18 11:44:17 +08:00
i-robot ccd25e5ceb !2333 [Feature] Add test for npu bounding box encode and decode.
Merge pull request !2333 from 刘嘉巍/ops
2023-02-17 09:09:04 +00:00
i-robot 2bc784b27d !2292 Fix input device for get_rng_state and set_rng_state.
Merge pull request !2292 from shaoyf/fix/get_rng_state
2023-02-17 09:06:30 +00:00
pengzirong 30ea9fc4e3 更新3.0.0版本RELEASENOT 2023-02-17 16:59:57 +08:00
huangyunlong 58416fc03b [Feature] Add test for npu_strided_copy and npu_sort_v2. 2023-02-17 11:42:09 +08:00
wangyicheng 4356839fd9 Gen default value for C++ API and Correct backend from yaml. 2023-02-17 10:29:12 +08:00
i-robot 4618bf1eec !2308 [Feature] Add test for npu_ifmr, npu_max.dim, npu_max.names_dim, npu_bmmV2 and npu_dtype_cast.
Merge pull request !2308 from 叶灵煜/custom_op_0215
2023-02-16 13:03:57 +00:00
i-robot 86773348c6 !2344 [FIX] Torch_npu is compatible for rts feature err.
Merge pull request !2344 from darin123/master
2023-02-16 12:36:08 +00:00
dujinhang fb86cd4adb [Feature] add test for npu_conv2d, npu_conv3d and npu_conv_transpose2d. 2023-02-16 19:13:39 +08:00
i-robot 71ec59af34 !2325 Test npu_slice, npu_indexing and npu_stride_add.
Merge pull request !2325 from Leon/master
2023-02-16 09:27:45 +00:00
i-robot e2cdd05214 !2316 [bugfix] Fix uniform kernel forward error.
Merge pull request !2316 from will-devil/uniformdev
2023-02-16 09:24:12 +00:00
i-robot 33274e2f7f !2312 [Fix] Fix the deadlock in taskqueue
Merge pull request !2312 from 詹昊/master
2023-02-16 08:51:46 +00:00
anping c98e57cf82 [FIX] Torch_npu is compatible for rts feature err. 2023-02-16 16:21:19 +08:00
叶灵煜 1c3af9d9d7 Add testcases for custom torch_npu ops.
Signed-off-by: 叶灵煜 <yelingyu@huawei.com>
2023-02-16 14:33:53 +08:00
刘嘉巍 4cb2bd9c14 Test npu bounding box encode & decode 2023-02-16 13:23:17 +08:00
i-robot 85efdd3570 !2287 [Feature] Add combine tensor related APIs used for NpuFusedOptimizers
Merge pull request !2287 from 郭鹏/feature/v1.11.0-combine
2023-02-16 03:39:28 +00:00
刘哲续 f49a5963f5 Relax interception conditions. 2023-02-16 10:33:05 +08:00
liangyunfan 6d4beb57d4 Test npu_indexing, npu_slice and npu_stride_add. 2023-02-15 17:53:33 +08:00
zhanhao 3eabfefbda Fix the deadlock in taskqueue 2023-02-15 15:36:43 +08:00
i-robot 4eba282bf6 !2290 Optimize im2col to support 3D input.
Merge pull request !2290 from 戢芳/im2col1.11
2023-02-15 07:35:35 +00:00
gp513 bd1768767c add npu_combine_tensors() for NpuFusedOptimizer
rename combine as combine_tensors and moved to torch_npu/utils

fix init in torch_npu/npu
2023-02-15 14:39:02 +08:00
wangyicheng a0f5177f80 Fix uniform kernel forward error. 2023-02-15 14:18:38 +08:00
i-robot 4f9dad9047 !2297 [Feature] Libtorch: add shell to build libtorch_npu without python.
Merge pull request !2297 from 施博/libtorch_up_master
2023-02-15 03:56:32 +00:00
i-robot d10347340e !2273 [stream feat] add stream failure mode.
Merge pull request !2273 from darin123/master
2023-02-14 02:51:42 +00:00
i-robot b09d3b94d6 !2080 [Fix]Fix the input tensor src_stride under aicore mode.
Merge pull request !2080 from 於欣洁/master_vc0107
2023-02-14 02:03:36 +00:00
pipihugh 98638b44ec Optimize im2col to support 3D input. 2023-02-14 09:49:33 +08:00
i-robot 775e0998fa !2288 [Feature] Add test for npu_reshape and npu_iou.
Merge pull request !2288 from 刘嘉巍/ops
2023-02-13 14:16:33 +00:00
i-robot ec8f8d9baf !2298 Modify function name of Call Stack.
Merge pull request !2298 from 裘凯达/aic_def_master
2023-02-13 14:15:59 +00:00
shibo19 aad94342bf add shell for building libtorch_npu without python 2023-02-13 20:57:03 +08:00
cudi 2c5467d884 Modify name For Call Stack. 2023-02-13 19:53:04 +08:00
00817228 9af82239b1 Fix the input tensor src_stride under aicore mode. 2023-02-13 19:45:51 +08:00
anping 0d99ec1c95 [Stream feat] Add stream failure mode. 2023-02-13 17:24:22 +08:00
i-robot 553fee0239 !2280 [Fix] Fix no attribute python_exit_status.
Merge pull request !2280 from 龚俊强/master
2023-02-13 08:25:58 +00:00
刘嘉巍 fee91ebf65 Test npu_reshape & npu_iou 2023-02-13 16:21:25 +08:00
xiaxia3 cc3103a295 Index supports the tensors of the input for different devices. 2023-02-13 15:54:48 +08:00
shaoyf 3b45846a51 Fix input device for get_rng_state and set_rng_state. 2023-02-13 15:10:16 +08:00
i-robot 318c393bce !2192 Fix output shape of lstm_backward.
Merge pull request !2192 from 郑亚金/master_zyj_11_lstm
2023-02-11 09:10:25 +00:00
郑亚金 2d4d9718bd Fix output shape of lstm_backward. 2023-02-11 15:57:25 +08:00
junqiang521 39b204a6e6 Master version upgrade, update _shutdown_workers 2023-02-11 12:26:12 +08:00
xiaxia3 f4c6b6094e Upgrade syncbn_forward. 2023-02-11 09:57:05 +08:00
i-robot 430c5c2f94 !2276 [Fix] fix isinstance bug in transfer_to_npu tools
Merge pull request !2276 from 施博/master_instance
2023-02-10 10:33:39 +00:00
shibo19 418b3a3984 fix isinstance bug in transfer_to_npu tools 2023-02-10 17:24:44 +08:00
i-robot 9ed6e41198 !2271 [Fix] fix device constructor bug
Merge pull request !2271 from 施博/device_master
2023-02-10 09:17:15 +00:00
shibo19 97264f66ec fix device ctor bug 2023-02-10 14:40:23 +08:00
i-robot fd1a22a26c !2252 Change the default value of AiCore Metrics with ACL_AICORE_PIPE_UTILIZATION.
Merge pull request !2252 from 裘凯达/aic_def_master
2023-02-10 02:32:43 +00:00
cudi 604e8415a4 Modify the default value of AICore Metrics with ACL_AICORE_PIPE_UTILIZATION. 2023-02-09 20:47:37 +08:00
i-robot a312794efe !2248 [Fix] parameter parsing error when 'device=None'.
Merge pull request !2248 from 杜金航/master
2023-02-09 12:37:19 +00:00
i-robot ebc77698bd !2240 Report CallStack to MsProfiler.
Merge pull request !2240 from 裘凯达/master_pt
2023-02-09 10:59:33 +00:00
i-robot f2fffab19a !2174 Torch.load supports npu tensor load to cpu.
Merge pull request !2174 from 闫鹏全/master
2023-02-08 06:54:43 +00:00
dujinhang 53fbed4d35 [Fix] parameter parsing error when 'device=None'. 2023-02-08 14:32:17 +08:00
i-robot 85bca4946f !2235 Add Attr of Swish.
Merge pull request !2235 from 戢芳/swish1.11
2023-02-08 03:37:30 +00:00
i-robot 920d88ac28 !2225 Fix clamp in int64 scenario.
Merge pull request !2225 from 戢芳/clamp1.11
2023-02-08 03:17:14 +00:00
i-robot 85728a332d !2245 [Fix] Fix device class bug
Merge pull request !2245 from 施博/device_master
2023-02-07 13:55:49 +00:00
施博 7275a94942 Merge branch 'master' of gitee.com:ascend/pytorch into device_master
Signed-off-by: 施博 <shibo19@huawei.com>
2023-02-07 12:17:27 +00:00
shibo19 e57a52fe9c fix device class bug 2023-02-07 20:14:25 +08:00
i-robot 0ff9946e9d !2156 IndexPut support 1D broadcast case.
Merge pull request !2156 from 王晓歆/master
2023-02-07 12:11:47 +00:00
i-robot 6ae13a31b0 !2237 Strengthen index operator verification.
Merge pull request !2237 from 刘哲续/master
2023-02-07 12:04:20 +00:00
刘哲续 b5d7ba5d1a Strengthen index operator verification. 2023-02-07 17:24:23 +08:00
闫鹏全 bbcd9ef109 Torch.load supports npu tensor load to cpu. 2023-02-07 17:12:36 +08:00
i-robot 0bc66c1b6c !2232 [Fix] Fix instance assert bug for torch_npu._C.device
Merge pull request !2232 from 施博/master_device
2023-02-07 08:44:32 +00:00
i-robot ce16d822bb !2207 [Fix] Fix bug in storage_resize_npu.
Merge pull request !2207 from 刘嘉巍/master
2023-02-07 08:42:56 +00:00
i-robot 66e7cb5350 !2132 Add BiShengExtension for compile ops writed by BiShengCPP.
Merge pull request !2132 from lotus/master
2023-02-07 07:19:12 +00:00
cudi 8917a72c3a Report call stack to MsProfiler. 2023-02-07 14:23:28 +08:00
pipihugh 4497ba11d4 Add Attr of Swish. 2023-02-07 13:45:11 +08:00
shibo19 6603a558a1 fix assert for torch_npu._C.device 2023-02-07 11:03:48 +08:00
i-robot 90cbf43488 !2168 [Feature] Add allgather_togather op only used for syncbn.
Merge pull request !2168 from 施博/upmaster_allgather
2023-02-07 01:44:37 +00:00
i-robot 28e1d943b9 !2215 Add aminmax.out operator and update the operator support list.
Merge pull request !2215 from Leon/master
2023-02-07 01:15:35 +00:00
i-robot ab58ce6967 !2228 FusedColorjitter Moving the position of the import pillow avoids the problem of dependencies when importing torch_npu
Merge pull request !2228 from 王姜奔/master
2023-02-06 13:37:29 +00:00
王姜奔 4988421705 Moving the position of the import pillow avoids the problem of dependencies when importing torch_npu
Signed-off-by: 王姜奔 <wangjiangben@huawei.com>
2023-02-06 11:46:49 +00:00
pipihugh e46b4eafeb Fix clamp in int64 scenario. 2023-02-06 17:07:55 +08:00
i-robot b920df19a5 !2180 Correct the output dtype of add and sub in the mix dtype scenario.
Merge pull request !2180 from 戢芳/add&sub1.11
2023-02-06 01:11:52 +00:00
i-robot 1acb807f7f !2181 Restore the adaptation of fill_.
Merge pull request !2181 from 戢芳/fill1.11
2023-02-06 01:10:39 +00:00
i-robot 43398f6f8c !2216 Report CANN op name to MsProfiler.
Merge pull request !2216 from 裘凯达/master_pt
2023-02-06 01:08:10 +00:00
i-robot 612682fa6d !2220 [Fix] Add class "Device" for torch_npu
Merge pull request !2220 from 施博/device_master
2023-02-04 09:32:53 +00:00
shibo19 761c973adf Add class Device for torch_npu 2023-02-04 11:34:43 +08:00
i-robot 0325389d2b !2219 回退 'Pull Request !2189 : [Fix] Add class "Device" for torch_npu'
Merge pull request !2219 from weili10/revert-merge-2189-master
2023-02-03 11:41:30 +00:00
weili10 00e313fd85 回退 'Pull Request !2189 : [Fix] Add class "Device" for torch_npu' 2023-02-03 11:30:36 +00:00
lotusdeng2010 9c840a2ed9 Add BiShengExtension for compile ops writed by BiShengCPP 2023-02-03 17:30:08 +08:00
i-robot 2ea2d86e55 !2188 [Fix] Taskqueue add memory barrier.
Merge pull request !2188 from 詹昊/master
2023-02-03 08:04:51 +00:00
i-robot 2297e73ff8 !2189 [Fix] Add class "Device" for torch_npu
Merge pull request !2189 from 施博/device_master
2023-02-03 08:02:28 +00:00
liangyunfan e034df7a08 Add aminmax.out operator and update the operator support list. 2023-02-03 11:57:46 +08:00
i-robot a858d2119e !2177 [fix] fix datadump enque input is cpu tensor
Merge pull request !2177 from xudaohong/master
2023-02-03 01:34:16 +00:00
刘嘉巍 329b39a5a9 Fix bug in storage_resize_npu. 2023-02-02 20:34:49 +08:00
pipihugh ac22be1ed3 Correct the output dtype of add and sub in the mix dtype scenario. 2023-02-02 16:57:45 +08:00
shibo19 59f16c912b Add class Device for torch_npu 2023-02-02 16:53:48 +08:00
zhanhao 06c19d2e52 Taskqueue add memory barrier 2023-02-02 16:43:33 +08:00
pipihugh fc10134eb9 Restore the adaptation of fill_. 2023-02-02 16:32:55 +08:00
cudi 6ba29b2227 Report CANN op to MsProfiler. 2023-02-02 15:38:46 +08:00
i-robot 64093abaf5 !2166 Correct the output dtype of pow.
Merge pull request !2166 from 郑亚金/master_zyj_pow_20230130
2023-02-02 01:32:25 +00:00
i-robot b6052cb85c !2179 Add onnx export operators and test cases
Merge pull request !2179 from Zhang Yingxin/master
2023-02-01 07:38:02 +00:00
i-robot 69b059e791 !2161 [Refactor] Add new op UT to CI.
Merge pull request !2161 from will-devil/cidev
2023-02-01 06:29:21 +00:00
i-robot d570dbb582 !2120 Modify the torch_device_guard function and removed some device patches.
Merge pull request !2120 from 杜金航/master
2023-02-01 06:23:34 +00:00
i-robot 2e5ec43567 !2160 [Fix] Fix invalid output shape allocation of dropout mask in op FusedAttentionScore
Merge pull request !2160 from lj_new/master
2023-02-01 06:18:05 +00:00
zhang-aurora 00368d6dd7 Add onnx export operators and test cases 2023-02-01 11:57:52 +08:00
i-robot 951e379132 !2141 Add alltoall_base op.
Merge pull request !2141 from 邵非凡/ddpUpdate
2023-02-01 02:38:15 +00:00
i-robot 3a8ee9a901 !2139 [Refactor] Remove the DeviceStats data structure and update BlockPool data structure.
Merge pull request !2139 from 闫鹏全/npucaching
2023-02-01 02:24:23 +00:00
i-robot 7ede7dc326 !2135 Add BiShengCPP ops.
Merge pull request !2135 from lotus/master
2023-02-01 01:27:30 +00:00
i-robot 712ce80a78 !2114 Fix upsample_nearest1d to support dynamic scenes.
Merge pull request !2114 from 戢芳/resize1.11
2023-02-01 01:08:37 +00:00
i-robot 67cd14794d !2172 [cherry-pick]: sync commits in 1.8,[1]:refactor(func: convert_to_acl_data_type); [2]:[Style]:reformat the func in calcuopUitl.*
Merge pull request !2172 from 宇世康/master
2023-02-01 01:08:04 +00:00
i-robot 392279649d !2002 [Feature] Add onnx export operators file and test cases
Merge pull request !2002 from Zhang Yingxin/master
2023-01-31 13:50:19 +00:00
shibo19 98745abe88 Add allgather_togather op only used for syncbn. 2023-01-31 21:03:15 +08:00
lotusdeng2010 b0aafbd4e8 Add BiShengCPP ops 2023-01-31 19:52:34 +08:00
x00430237 244c83b81e [fix] fix datadump enque input is cpu tensor 2023-01-31 17:20:37 +08:00
i-robot a3160d129f !2171 [Feature] graph mode support HCCL ops (allreduce, allgather).
Merge pull request !2171 from 王强/master
2023-01-31 07:49:26 +00:00
dujinhang 5cf7c55de9 Modify the torch_device_guard function and removed some device patches. 2023-01-31 15:23:11 +08:00
i-robot ff81f207ee !2159 [Feature] ReplayGraph support only forward case by setting requires_grad to False
Merge pull request !2159 from 王强/master
2023-01-31 07:15:30 +00:00
yskhhh 3e74e3328c fix(CalcuOpUtil.*): Scalartype QUInt2x4 has been added into pytorch1.11,so kATenScalarTypeToAclDataTypeTable must be updated 2023-01-31 11:35:25 +08:00
yskhhh 75d4714f72 style(CalcuOpUtil.*): reformat some func and remove some unused func 2023-01-31 11:17:00 +08:00
wq160 ab148143cb [Feature] graph mode support HCCL ops (allreduce, allgather). 2023-01-31 11:15:43 +08:00
yskhhh 68cdd57237 refactor(func: convert_to_acl_data_type): use array instead of map to implement func convert_to_acl_data_type 2023-01-31 11:01:56 +08:00
wangyicheng 706ce76ea4 Add new op_ut to ci. 2023-01-31 09:26:22 +08:00
weili10 81435460ae update cann version.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-01-30 13:18:04 +00:00
i-robot 5ef9627a0e !2170 [Fix] Fix format bug of resize.
Merge pull request !2170 from 王强/master
2023-01-30 11:42:05 +00:00
wq160 d281876507 [Fix] Fix format bug of resize 2023-01-30 18:20:24 +08:00
i-robot 4201aebfda !2138 [Refactor] Refactor fast gelu forward function.
Merge pull request !2138 from 刘嘉巍/ops
2023-01-30 08:00:08 +00:00
邵非凡 71265b10eb Add alltoall_base op. 2023-01-30 15:44:31 +08:00
Zhang Yingxin e043d6e451 Add onnx export operators file and test cases 2023-01-30 15:33:31 +08:00
hxf12345677 2ae40194f5 Correct the output dtype of pow. 2023-01-30 14:45:53 +08:00
i-robot bd2df86313 !2151 Update Index Adaption.
Merge pull request !2151 from 刘哲续/master
2023-01-30 02:04:39 +00:00
wangxiaoxin_sherie 77a9c27900 IndexPut shrink the number of indicators. 2023-01-30 10:04:26 +08:00
lijing d7b5bd636a Fix invalid output shape allocation of mask 2023-01-30 09:36:40 +08:00
i-robot ec3c015fe1 !2131 [Fix] Remove functions that do not need autograd from custom_autograd.
Merge pull request !2131 from 刘嘉巍/master
2023-01-30 01:26:53 +00:00
wq160 ab22ff657e [Feature] ReplayGraph support only forward case by setting requires_grad to False. 2023-01-29 20:59:10 +08:00
i-robot 9554cf77e6 !2152 [Fix] Fix the bug of empty_strided, when resize occurs.
Merge pull request !2152 from 王强/master
2023-01-29 12:19:10 +00:00
i-robot 908b3e8694 !2145 Delete the transpose operation in the framework of GIoU.
Merge pull request !2145 from 於欣洁/master_giou0107
2023-01-29 11:36:09 +00:00
i-robot 13b0dce9bd !2148 [fix] fix datadump problem caused by torch v1.11.0 code merge
Merge pull request !2148 from xudaohong/master
2023-01-29 08:38:05 +00:00
00817228 0c8e6d4213 Delete the transpose operation in the framework of GIoU. 2023-01-29 15:19:46 +08:00
刘哲续 2393293c81 Update Index Adaption. 2023-01-29 14:52:20 +08:00
wq160 748a00159f [Fix] fix the bug of empty_strided, when resize occurs. 2023-01-29 10:38:12 +08:00
x00430237 34c9f17eba [fix] fix datadump problem caused by torch v1.11.0 code merge 2023-01-28 15:30:22 +08:00
闫鹏全 f6ee0d33ef Update some data structures and function in npu memory management. 2023-01-20 09:26:52 +08:00
weili10 354f47aca6 update README.zh.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-01-19 08:13:46 +00:00
weili10 0c4aa35681 update README.zh.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-01-18 09:26:36 +00:00
刘嘉巍 d4b45042c0 Refactor fast gelu forward function 2023-01-18 15:20:15 +08:00
闫鹏全 43708a8bf6 Remove the DeviceStats data structure. 2023-01-18 15:12:24 +08:00
i-robot 4b94310443 !2134 [Refactor] Clean up some uncall functions related to npu memory management.
Merge pull request !2134 from 闫鹏全/npucaching
2023-01-18 06:55:58 +00:00
pipihugh 3356f3701f Fix upsample_nearest1d to support dynamic scenes. 2023-01-17 17:06:13 +08:00
闫鹏全 a7e7320808 Clean up some uncall functions related to npu memory management. 2023-01-17 11:03:15 +08:00
i-robot 1c327d96a6 !2122 [Refactor] Clean up an uncalled function.
Merge pull request !2122 from 闫鹏全/npucaching
2023-01-16 02:57:12 +00:00
刘嘉巍 16d27b43ae remove functions that do not need autograd from custom_autograd 2023-01-15 13:55:29 +08:00
尤安升 14ce47a51d 新建 examples 2023-01-14 07:04:06 +00:00
闫鹏全 795e527ed7 Clean up an uncalled function. 2023-01-13 16:52:31 +08:00
weili10 b010233bd0 update README.zh.md.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-01-13 08:25:40 +00:00
i-robot 08f17a4dde !2106 Update unit test files.
Merge pull request !2106 from 闫鹏全/ut
2023-01-13 01:27:31 +00:00
i-robot 7b5d2421eb !2112 [Fix] Fixed bugs caused by npu device.
Merge pull request !2112 from 杜金航/master
2023-01-12 14:11:53 +00:00
dujinhang 56d1f2db3d [Fix] Fixed npu device not torch.device type issue. 2023-01-12 22:00:19 +08:00
i-robot 171bd21ad8 !2102 [Refactor] Delete Allocator files that have not been called.
Merge pull request !2102 from 闫鹏全/memory
2023-01-12 13:23:44 +00:00
i-robot 54d1f16da8 !2110 [Fix]Modifying the map_location parameter processing flow in torch.load.
Merge pull request !2110 from 闫鹏全/master
2023-01-12 12:19:20 +00:00
i-robot be0630c160 !2108 Add three npu native func: format_contiguous, check_match, check_memory_over_laps.
Merge pull request !2108 from lotus/master
2023-01-12 12:18:38 +00:00
lotus 8a819be35e Add three npu native func: format_contiguous, check_match, check_memory_over_laps 2023-01-12 16:18:17 +08:00
闫鹏全 d056930764 Update unit test to 1.11.0. 2023-01-12 11:44:50 +08:00
闫鹏全 c833b916c2 Fixed the map_location parameter processing in torch.load. 2023-01-12 11:39:58 +08:00
i-robot 4df3b3f678 !2090 [Feature] Add overflow check func for 1971 soc version.
Merge pull request !2090 from 施博/overflow_1971_master
2023-01-11 09:01:14 +00:00
shibo19 afb69ac33e Add overflow check func for 1971 soc version. 2023-01-11 16:36:19 +08:00
闫鹏全 0538236b1e Delete Allocator files that have not been called. 2023-01-11 09:35:55 +08:00
i-robot 1a069561fc !2097 [Refactor] Remove unsupported ops from yaml.
Merge pull request !2097 from will-devil/yamldev
2023-01-10 08:42:22 +00:00
wangyicheng e377dc0283 Remove unsupported ops from yaml 2023-01-10 14:29:57 +08:00
i-robot 54b0f7126b !2092 [Fix]Fix silu inplace backward.
Merge pull request !2092 from 王晓/silu_1.11
2023-01-09 12:45:35 +00:00
i-robot 72e41b8e47 !2081 Update readme file.
Merge pull request !2081 from 邵非凡/readme
2023-01-09 12:27:32 +00:00
i-robot 58cb4bedea !2091 [Cleancode] Clean code for all.
Merge pull request !2091 from huangyunlong/feature_hyl
2023-01-09 12:21:15 +00:00
i-robot 5287176deb !2084 [Fix] Add attr of GatherV2.
Merge pull request !2084 from 戢芳/gather1.11
2023-01-09 12:17:47 +00:00
wangxiao ccb2200a1b Fix silu inplace backward. 2023-01-09 19:28:02 +08:00
huangyunlong bf754d7bc0 [Cleancode] Clean code for all. 2023-01-09 16:50:57 +08:00
邵非凡 5340ee6f6c Update readme file. 2023-01-09 15:04:24 +08:00
pipihugh f5b6d26c23 Add attr of GatherV2. 2023-01-09 13:37:11 +08:00
i-robot e536e35617 !2077 Synchronize 1.11.0 branch to the master branch.
Merge pull request !2077 from 邵非凡/update1.11
2023-01-07 07:43:45 +00:00
i-robot dab155b170 !2066 [Fix] Update op list for AOE dump.
Merge pull request !2066 from 施博/up_master
2023-01-07 03:25:14 +00:00
i-robot db24b9a054 !2076 [Fix] Fix the problem of cnt can not be 0.
Merge pull request !2076 from 詹昊/master
2023-01-07 03:21:28 +00:00
邵非凡 b53ec7fec9 Synchronize 1.11.0 branch to the master branch. 2023-01-07 11:16:28 +08:00
i-robot baa99a0507 !2067 [Fix] The inverse computation of depth separable convolution is supported.
Merge pull request !2067 from 王夏夏/master
2023-01-07 02:13:08 +00:00
i-robot 73c2db15cd !2069 [Fix] Fix the fp16 precision problem of scatter.
Merge pull request !2069 from 王夏夏/master
2023-01-07 02:12:43 +00:00
zhanhao 81cd832b5e Fix the problem of cnt can not be 0. 2023-01-06 21:54:11 +08:00
xiaxia3 a86b5f46ec The inverse computation of depth separable convolution is supported. 2023-01-06 17:29:12 +08:00
xiaxia3 b595c7afdc Fix the fp16 precision problem of scatter. 2023-01-06 16:21:59 +08:00
shibo19 9f6f8220b6 Update op list for AOE dump. 2023-01-06 15:27:20 +08:00
i-robot 7cdc9414b3 !2062 Fix the compilation errors.
Merge pull request !2062 from 闫鹏全/bugfix
2023-01-06 07:23:34 +00:00
尤安升 9f1067bc35 !2059 Upgrade the master branch from version 1.8.1 to 1.11.0.
Merge pull request !2059 from 闫鹏全/v1.11.0-diff
2023-01-06 06:50:06 +00:00
闫鹏全 4a314b171f Fix the compilation errors. 2023-01-06 14:34:34 +08:00
i-robot 6bc8c786a8 !2050 [Feature] Add adapters of tril_indices and triu_indices.
Merge pull request !2050 from 戢芳/triu_indices1.8
2023-01-06 03:45:53 +00:00
尤安升 ef0c0f4c84 !2026 Update data structures and types to 1.11.0.
Merge pull request !2026 from 闫鹏全/v1.11.0-diff-data
2023-01-06 03:26:34 +00:00
尤安升 a42e50c0f9 !2015 The operator interface is synchronized to official 1.11.0.
Merge pull request !2015 from 闫鹏全/v1.11.0-diff-opsinterface
2023-01-06 03:26:02 +00:00
邵非凡 f3fbe062e4 The operator interface is synchronized to official 1.11.0. 2023-01-06 09:32:11 +08:00
i-robot fe17155b17 !1988 Add affinity interface for bert big kernel
Merge pull request !1988 from lj_new/master
2023-01-06 01:26:28 +00:00
i-robot e019e2c0ea !2054 [Cleancode] Clean code for all.
Merge pull request !2054 from shaoyf/cleancode/master
2023-01-06 01:17:35 +00:00
i-robot b5f0714ebc !2049 IndexPut support 1D broadcast case
Merge pull request !2049 from 王晓歆/master
2023-01-05 13:48:09 +00:00
闫鹏全 8da378d72f Update data structures and types to 1.11.0. 2023-01-05 21:38:53 +08:00
i-robot 1ca96c3887 !2045 Reduce Transpose calls of npu_deformable_conv2d.
Merge pull request !2045 from 王晓/nhwc_fix_1
2023-01-05 13:37:38 +00:00
i-robot cf93f428f7 !2046 [bugfix] Modify InferShapeofNHWC.
Merge pull request !2046 from will-devil/shapedev
2023-01-05 13:31:27 +00:00
i-robot efcb27cfe3 !2036 [Fix] Adjust the Index adaptation logic.
Merge pull request !2036 from 刘哲续/master
2023-01-05 13:30:21 +00:00
i-robot 0ec39852ae !1967 Upgrade Input to support IntArrayRef and set descName.
Merge pull request !1967 from 戢芳/input1.8
2023-01-05 12:29:22 +00:00
刘哲续 153490f0ed Adjust the Index adaptation logic. 2023-01-05 20:08:10 +08:00
wangyicheng 4789b3c28e Modify InferShapeofNHWC. 2023-01-05 19:51:54 +08:00
尤安升 3fc05d486d !2007 Update amp related code implementation to 1.11.0.
Merge pull request !2007 from 闫鹏全/v1.11.0-diff-amp
2023-01-05 11:49:23 +00:00
尤安升 cbd0cc73c8 !2011 Update test framework related code implementation to 1.11.0.
Merge pull request !2011 from 闫鹏全/v1.11.0-diff-test
2023-01-05 11:48:51 +00:00
尤安升 d0e35c02a9 !2009 Update ddp related code implementation to 1.11.0.
Merge pull request !2009 from 闫鹏全/v1.11.0-diff-ddp
2023-01-05 11:48:20 +00:00
尤安升 80cd4b4a37 !2018 Update codegen related code implementation to 1.11.0.
Merge pull request !2018 from 闫鹏全/v1.11.0-diff-codegen
2023-01-05 11:47:43 +00:00
尤安升 a83dec1111 !2013 Updated the python side interface implementation to 1.11.0.
Merge pull request !2013 from 闫鹏全/v1.11.0-diff-part
2023-01-05 11:47:16 +00:00
尤安升 3caec95134 !2027 Update some of the operator interfaces and their implementations to 1.11.0.
Merge pull request !2027 from 闫鹏全/v1.11.0-diff-ops
2023-01-05 11:46:44 +00:00
尤安升 6d5791e967 !2019 Update fx related code implementation to 1.11.0.
Merge pull request !2019 from 闫鹏全/v1.11.0-diff-fx
2023-01-05 11:46:17 +00:00
尤安升 a901d5a9b9 !2028 Update the operator input to add a constraint on const references.
Merge pull request !2028 from 闫鹏全/v1.11.0-diff-const
2023-01-05 11:45:24 +00:00
i-robot fcf28becb2 !2039 Fix hardsigmoid_ and add corresponding cases.
Merge pull request !2039 from 戢芳/hardsigmoid1.8
2023-01-05 11:22:25 +00:00
闫鹏全 08acf60c3c Update codegen related code implementation to 1.11.0. 2023-01-05 19:12:04 +08:00
i-robot 4088f0b895 !2004 [Fix] Reduce unnecessary item when the Tensor is on device
Merge pull request !2004 from 王强/master
2023-01-05 09:57:27 +00:00
闫鹏全 b73b4054ae Update some of the operator interfaces and their implementations to 1.11.0. 2023-01-05 16:59:04 +08:00
wangxiaoxin_sherie 51c61ec9cb indexput support 1D broadcast case 2023-01-05 15:07:56 +08:00
li_jing_hw 19740f7a75 Add 2 affinity interface for bert big kernel
clean code

modify judgement of bool

修复大kernel无法import的问题

Signed-off-by: lj_new <lijing202@huawei.com>

bert大kernel clean code(line too long)

add license for bert big kernel

clean code

clean code

cleancode
2023-01-05 14:29:44 +08:00
pipihugh 6a98a54278 Add adapters of tril_indices and triu_indices. 2023-01-05 13:58:41 +08:00
shaoyf 40b90290a2 Clean code for all. 2023-01-05 13:36:22 +08:00
i-robot 4fedd8df68 !2031 [Fix]Add flag in read and write queue.
Merge pull request !2031 from 詹昊/master
2023-01-05 02:25:49 +00:00
wangxiao 30db38ddca Reduce Transpose calls of npu_deformable_conv2d. 2023-01-05 10:20:40 +08:00
闫鹏全 01554314d1 Master version upgrade, update partial interface. 2023-01-05 10:16:25 +08:00
i-robot 3299eceb18 !2035 [Fix] Fix new_zeros and new_empty without args.
Merge pull request !2035 from shaoyf/bugfix/new_zeros
2023-01-04 12:29:51 +00:00
zhanhao 81a665e09e Add flag in read and write queue. 2023-01-04 20:20:40 +08:00
i-robot 3c268615ce !2037 [Fix]IndexPut unsupport bool incomplete axis
Merge pull request !2037 from 王晓歆/master
2023-01-04 10:57:30 +00:00
pipihugh 500b50ff95 Fix hardsigmoid_ and add corresponding cases. 2023-01-04 16:19:48 +08:00
wangxiaoxin_sherie 8491713a91 Intercept bool non full axis case. 2023-01-04 15:52:22 +08:00
pipihugh cdafc4de0e Upgrade Input to support IntArrayRef and set descName. 2023-01-04 13:49:41 +08:00
shaoyf ac8caded56 Fix new_zeros and new_empty without args. 2023-01-04 11:25:34 +08:00
闫鹏全 6e4e84ac76 Update ddp related code implementation to 1.11.0.
fix
2023-01-04 10:58:00 +08:00
i-robot 7439ae5cce !1995 [feat] add step control and async datadump hook in acc_cmp_tool
Merge pull request !1995 from xudaohong/master
2023-01-04 01:52:34 +00:00
尤安升 2577dcf72e !2005 Update profiler related code implementation to 1.11.0.
Merge pull request !2005 from 闫鹏全/v1.11.0-diff
2023-01-03 11:54:52 +00:00
尤安升 8ffaadd68a !2006 Update Graph mode related code implementation to 1.11.0.
Merge pull request !2006 from 闫鹏全/v1.11.0-diff-graph
2023-01-03 11:53:54 +00:00
i-robot bfa4a58efc !2021 Adjust the Index adaptation logic.
Merge pull request !2021 from 刘哲续/master
2023-01-03 11:49:58 +00:00
邵非凡 1f1765f4b3 Update the operator input to add a constraint on const references. 2023-01-03 19:38:08 +08:00
闫鹏全 8e01258655 Update fx related code implementation to 1.11.0. 2023-01-03 19:11:54 +08:00
x00430237 e672675d13 [feat] add step control and async datadump hook in acc_cmp_tool 2023-01-03 18:45:31 +08:00
刘哲续 218ea4a965 Adjust the Index adaptation logic. 2023-01-03 18:32:27 +08:00
闫鹏全 694e7ed93b Master version upgrade, update test framework related code implementation. 2022-12-30 17:23:16 +08:00
闫鹏全 6311d0d748 Master version upgrade, update amp related code implementation. 2022-12-30 15:40:44 +08:00
闫鹏全 3c637ec022 Master version upgrade, update Graph mode related code implementation. 2022-12-30 14:36:29 +08:00
i-robot c602fd97cb !1946 [Fix] Syncbn support input shape (N,C,+)
Merge pull request !1946 from huangxinliang/master
2022-12-30 06:16:14 +00:00
闫鹏全 ea7b131819 Master version upgrade, update profiler related code implementation. 2022-12-30 14:11:53 +08:00
xinlianglalala 019e7cb16e Do reshape to support ND format 2022-12-30 12:11:46 +08:00
wq160 4a079401b5 [fix] Reduce unnecessary item when the Tensor is on device 2022-12-30 11:43:20 +08:00
i-robot 863ca112de !1968 Call Transpose explicitly in adapter of deformable_conv2d.
Merge pull request !1968 from 王晓/deformable_conv_nhwc2
2022-12-29 13:23:14 +00:00
i-robot 083d8b1db2 !1996 Fix layer_norm shape error.
Merge pull request !1996 from 王晓/ln_resize
2022-12-29 09:05:21 +00:00
wangxiao 69c4092660 Fix layer_norm shape error. 2022-12-29 13:33:59 +08:00
i-robot 32d69d12a9 !1978 [fix] bugfix of supported data types by hccl ops
Merge pull request !1978 from 王强/master
2022-12-27 14:00:52 +00:00
i-robot 91c840476d !1989 Fix compilation errors when the version.py file exists.
Merge pull request !1989 from 闫鹏全/master
2022-12-27 13:51:21 +00:00
i-robot 9d7a6e248e !1982 [feat] merge device stream during datadump, modify tdtchannel capacity
Merge pull request !1982 from xudaohong/master
2022-12-27 13:23:55 +00:00
i-robot 0620f02bfb !1979 [BugFix] Correct the output shape of lstm_backward.
Merge pull request !1979 from 戢芳/lstm1.8
2022-12-27 10:18:32 +00:00
i-robot fb396531f4 !1965 Update the code format of DivKernelNpu.cpp, which is the same as version 1.11.0.
Merge pull request !1965 from 邵非凡/updateFormat
2022-12-27 07:17:50 +00:00
wq160 0fa9e7353f [fix] hccl op supported data type check bug fix 2022-12-27 11:37:44 +08:00
闫鹏全 bffaedbbac Fix compilation errors when the version.py file exists. 2022-12-27 11:34:01 +08:00
x00430237 ad167affff [feat] merge op stream during datadump, modify tdtchannel capacity 2022-12-27 10:42:16 +08:00
i-robot 1871cb1934 !1976 [Fix] Only warning once when running unsupported kernel.
Merge pull request !1976 from 刘嘉巍/dev
2022-12-26 12:47:43 +00:00
liu-jiaweikf 769ff87a21 Warning only once 2022-12-26 17:47:42 +08:00
pipihugh 31beaac68e Correct the output shape of lstm_backward. 2022-12-26 13:35:44 +08:00
i-robot 9da3639213 !1970 Index/IndexPut aicore operator adaptation.
Merge pull request !1970 from 王晓歆/master
2022-12-25 12:15:27 +00:00
wangxiaoxin_sherie 668e45e5d4 Add Index/IndexPut aicore adpater. 2022-12-25 11:22:08 +08:00
Author 邵非凡 7457160ace Update the code format, which is the same as version 1.11.0. 2022-12-24 09:13:07 +08:00
wangxiao 22b276758e Call Transpose explicitly in adapter of deformable_conv2d. 2022-12-23 17:46:00 +08:00
547 changed files with 28702 additions and 12056 deletions
+61 -33
View File
@@ -1,13 +1,7 @@
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
cmake_minimum_required(VERSION 3.12 FATAL_ERROR)
project(TORCHNPU CXX C)
option(USE_GRAPH_MODE "enable graph mode" OFF)
if(USE_GRAPH_MODE)
add_definitions(-DUSE_GRAPH_MODE=1)
endif()
set(LINUX TRUE)
set(CMAKE_INSTALL_MESSAGE NEVER)
# set(CMAKE_VERBOSE_MAKEFILE ON)
@@ -141,16 +135,26 @@ else()
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-s,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
endif()
if (DEFINED BUILD_LIBTORCH)
add_compile_definitions(BUILD_LIBTORCH)
endif()
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/torch_npu/csrc/aten)
include_directories(${PROJECT_SOURCE_DIR}/third_party/hccl/inc)
include_directories(${PROJECT_SOURCE_DIR}/third_party/acl/inc)
if (NOT DEFINED BUILD_LIBTORCH)
include_directories(${PROJECT_SOURCE_DIR}/patch/include)
include_directories(${PROJECT_SOURCE_DIR}/patch/include/torch/csrc/distributed)
endif()
# Set installed PyTorch dir
if(DEFINED PYTORCH_INSTALL_DIR)
include_directories(${PYTORCH_INSTALL_DIR}/include)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include/)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include)
else()
message(FATAL_ERROR, "Cannot find installed PyTorch directory")
endif()
@@ -165,23 +169,33 @@ endif()
# sources
set(ATEN_SRCS)
set(CORE_SRCS)
set(DIST_SRCS)
set(FRAMEWORK_SRCS)
set(NPU_SRCS)
set(PROF_SRCS)
set(UTILS_SRCS)
if (NOT DEFINED BUILD_LIBTORCH)
set(DIST_SRCS)
set(NPU_SRCS)
set(PROF_SRCS)
set(UTILS_SRCS)
endif()
add_subdirectory(${TORCHNPU_ROOT}/aten)
add_subdirectory(${TORCHNPU_ROOT}/core)
add_subdirectory(${TORCHNPU_ROOT}/distributed)
add_subdirectory(${TORCHNPU_ROOT}/framework)
add_subdirectory(${TORCHNPU_ROOT}/npu)
add_subdirectory(${TORCHNPU_ROOT}/profiler)
add_subdirectory(${TORCHNPU_ROOT}/utils)
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/distributed)
add_subdirectory(${TORCHNPU_ROOT}/npu)
add_subdirectory(${TORCHNPU_ROOT}/profiler)
add_subdirectory(${TORCHNPU_ROOT}/utils)
endif()
if (DEFINED BUILD_LIBTORCH)
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS})
else()
# Compile code with pybind11
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
endif()
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
@@ -189,7 +203,10 @@ link_directories(${PYTORCH_INSTALL_DIR}/lib)
link_directories(${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libhccl.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
if (NOT DEFINED BUILD_LIBTORCH)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
endif()
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libascendcl.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_op_compiler.so)
@@ -197,20 +214,31 @@ target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/lib
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libgraph.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_tdt_channel.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10 python3.7m)
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
if ("${ATEN_THREADING}" STREQUAL "OMP")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
if (DEFINED BUILD_LIBTORCH)
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10)
else()
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10 python3.7m)
endif()
include(GNUInstallDirs)
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
if(DEFINED ENV{BSCPP_OPS_ENABLE})
message(STATUS "env BSCPP_OPS_ENABLE exists")
target_link_libraries(${PLUGIN_NAME} PUBLIC bscpp_ops)
endif()
if (NOT DEFINED BUILD_LIBTORCH)
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
if ("${ATEN_THREADING}" STREQUAL "OMP")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
else()
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
endif()
include(GNUInstallDirs)
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
-1
View File
@@ -1,5 +1,4 @@
approvers:
- blian
- nalinaly
- weili10
- you-ansheng
+21 -21
View File
@@ -14,13 +14,13 @@ This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
yum install -y gcc==7.3.0 cmake==3.12.0
yum install -y gcc==7.5.0 cmake==3.12.0
## Ubuntu
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
apt-get install -y gcc==7.3.0 cmake==3.12.0
apt-get install -y gcc==7.5.0 cmake==3.12.0
>![](figures/icon-note.gif) **NOTE:**
>If an error occurs during the installation of the GCC and CMake dependency commands, use the source code for installation. For details, see the FAQ.
@@ -52,7 +52,7 @@ Install the official torch package, and then compile and install the plugin.
```sh
#x86_64
pip3 install torch==1.8.1+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
pip3 install torch==1.11.0+cpu # If an error is reported when you run the pip command to install PyTorch of the CPU version, manually download the .whl package from https://download.pytorch.org/whl/torch.
#AArch64
#The community does not provide the CPU installation package of the ARM architecture. For details, see the first FAQ to compile and install PyTorch using the source code.
@@ -62,7 +62,7 @@ Compile and generate the binary installation package of the PyTorch plugin.
Download code of the corresponding branch and go to the root directory of the plugin.
```
#
git clone -b v1.8.1-3.0.rc2 https://gitee.com/ascend/pytorch.git
git clone -b master https://gitee.com/ascend/pytorch.git
cd pytorch
# Specify the Python version packaging mode:
bash ci/build.sh --python=3.7
@@ -75,11 +75,11 @@ bash ci/build.sh --python=3.9
Install the **torch_npu** package generated in the **pytorch/dist** directory. *{arch}* indicates the architecture name.
```
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
pip3 install --upgrade dist/torch_npu-1.11.0-cp37-cp37m-linux_{arch}.whl
```
Download TorchVision.
```
pip3 install torchvision==0.9.1
pip3 install torchvision==0.12.0
```
@@ -137,7 +137,7 @@ python3 test_div.py
# (Optional) Installing the Mixed Precision Module
AscendPyTorch 1.8.1 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
AscendPyTorch 1.11.0 integrates the AMP module and can be used for training with mixed precision. The differences between the AMP module and the Apex module are as follows. You can select a desired module. For details about how to compile and install the Apex module, see the related [**README.en**](https://gitee.com/ascend/apex) file.
- AMP
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
@@ -184,23 +184,23 @@ The version branches of AscendPyTorch have the following maintenance phases:
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated |
# FAQs
## When the CPU architecture is ARM, PyTorch 1.8.1 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.8.1.
## When the CPU architecture is ARM, PyTorch 1.11.0 cannot be installed using the PIP3 command because the community does not provide the torch package for the ARM CPU architecture. In this case, use the source code to compile and install PyTorch 1.11.0.
Download the PyTorch 1.8.1 source package.
Download the PyTorch 1.11.0 source package.
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
```
Access the source package to obtain the passive dependency code.
```
cd pytorch_v1.8.1
cd pytorch_v1.11.0
git submodule sync
git submodule update --init --recursive
```
Compile and install PyTorch 1.8.1.
Compile and install PyTorch 1.11.0.
```
python3 setup.py install
@@ -316,7 +316,7 @@ When downloading GCC from some sources, you may be prompted by an error message
Perform the following steps as the **root** user.
1. Download **gcc-7.3.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz).
1. Download **gcc-7.5.0.tar.gz** from [https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz).
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
@@ -340,20 +340,20 @@ Perform the following steps as the **root** user.
4. Compile and install GCC.
1. Go to the directory where the source package **gcc-7.3.0.tar.gz** is located and run the following command to decompress it:
1. Go to the directory where the source package **gcc-7.5.0.tar.gz** is located and run the following command to decompress it:
```
tar -zxvf gcc-7.3.0.tar.gz
tar -zxvf gcc-7.5.0.tar.gz
```
2. Go to the extracted directory and download the GCC dependency packages:
```
cd gcc-7.3.0
cd gcc-7.5.0
./contrib/download_prerequisites
```
If an error is reported during the command execution, run the following commands in the **gcc-7.3.0/** directory to download the dependency packages:
If an error is reported during the command execution, run the following commands in the **gcc-7.5.0/** directory to download the dependency packages:
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
@@ -373,13 +373,13 @@ Perform the following steps as the **root** user.
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>Run the configuration, compilation, and installation commands.
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.5.0
make -j15 # Check the number of CPUs by running **grep -w processor /proc/cpuinfo|wc -l**. In this example, the number is 15. You can set the parameters as required.
make install
```
>![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/docs/en/PyTorch%20Network%20Model%20Porting%20and%20Training%20Guide/public_sys-resources/icon-notice.gif) **NOTICE:**
>The **--prefix** option is used to specify the **linux\_gcc7.3.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.3.0**.
>The **--prefix** option is used to specify the **linux\_gcc7.5.0** installation path, which is configurable. Do not set it to **/usr/local** or **/usr,** which is the default installation path for the GCC installed by using the software source. Otherwise, a conflict occurs and the original GCC compilation environment of the system is damaged. In this example, the installation path is set to **/usr/local/linux\_gcc7.5.0**.
4. Change the soft links.
```
@@ -398,14 +398,14 @@ Perform the following steps as the **root** user.
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
**${install_path}** indicates the GCC 7.3.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/gcc7.3.0/**.
**${install_path}** indicates the GCC 7.5.0 installation path configured in [3](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310). In this example, the GCC 7.5.0 installation path is **/usr/local/gcc7.5.0/**.
>![](figures/icon-note.gif) **NOTE:**
>Skip this step if you do not need to use the compilation environment with GCC upgraded.
If the PyTorch compilation fails, check whether the soft link library is correct.
libstdc++->libstdc++.so.6.0.24(7.3.0)
libstdc++->libstdc++.so.6.0.24(7.5.0)
## libblas.so cannot be found.
+34 -28
View File
@@ -14,13 +14,13 @@
yum install -y patch zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas git dos2unix
yum install -y gcc==7.3.0 cmake==3.12.0
yum install -y gcc==7.5.0 cmake==3.12.0
## Ubuntu
apt-get install -y patch g++ make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev m4 dos2unix libopenblas-dev git dos2unix
apt-get install -y gcc==7.3.0 cmake==3.12.0
apt-get install -y gcc==7.5.0 cmake==3.12.0
@@ -41,7 +41,10 @@ apt-get install -y gcc==7.3.0 cmake==3.12.0
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 | 22.0.RC2-1.8.1 |
| 3.0.rc3 | CANN 6.0.RC1 | 1.5.0.post7 | v1.5.0-3.0.rc3 | \ |
| 3.0.rc3 | CANN 6.0.RC1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 | 22.0.RC3-1.8.1 |
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1 | v1.11.0-3.0.rc3 | \ |
| 3.0.rc3 | CANN 6.0.RC1 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 | \ |
| 3.0.0 | CANN 6.0.1 | 1.5.0.post8 | v1.5.0-3.0.0 | \ |
| 3.0.0 | CANN 6.0.1 | 1.8.1 | v1.8.1-3.0.0 | \ |
| 3.0.0 | CANN 6.0.1 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 | \ |
# 安装方式
@@ -60,12 +63,14 @@ pip3 install wheel
```sh
#x86_64
pip3 install torch==1.8.1+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
pip3 install torch==1.11.0+cpu #若使用pip命令安装cpu版本PyTorch报错,请手动下载whl包安装,下载地址:(https://download.pytorch.org/whl/torch)
#aarch64(推荐使用镜像)
可在docker中使用AscendHub镜像仓库提供的基于PyTorch版本制作的基础镜像,包含训练、转换和推理等功能。
1.可在docker中使用AscendHub镜像仓库提供的基于PyTorch版本制作的基础镜像,包含训练、转换和推理等功能。
#镜像仓库地址:(https://ascendhub.huawei.com/#/detail/pytorch-modelzoo)
#社区未提供arm架构cpu安装包,如需尝试编译安装PyTorch框架,可参见FAQ第一条,使用源码编译安装pytorch。
2.鲲鹏arm服务器可在鲲鹏开源软件文件共享中心获取编译好的PyTorch二进制安装包。
#鲲鹏文件共享中心地址:(https://mirrors.huaweicloud.com/kunpeng/archive/Ascend/PyTorch/)
3.社区未提供的arm架构cpu安装包,可参见FAQ第一条,使用源码编译安装pytorch。
```
编译生成pytorch插件的二进制安装包。
@@ -85,12 +90,12 @@ bash ci/build.sh --python=3.9
然后安装pytorch/dist下生成的插件torch_npu包,{arch}为架构名称。
```
pip3 install --upgrade dist/torch_npu-1.8.1rc2-cp37-cp37m-linux_{arch}.whl
pip3 install --upgrade dist/torch_npu-1.11.0-cp37-cp37m-linux_{arch}.whl
```
下载torchvision。
```
pip3 install torchvision==0.9.1
pip3 install torchvision==0.12.0
```
# 运行
@@ -146,7 +151,7 @@ python3 test_div.py
# 安装混合精度模块(可选)
AscendPyTorch1.8.1集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
AscendPyTorch1.11.0集成了AMP模块,也可用于混合精度训练等应用场景,与Apex模块的区别如下,请用户根据功能需要选择使用,若需安装Apex模块请参考相关[README文档](https://gitee.com/ascend/apex)进行编译安装Apex模块。
- AMP
- 动态loss scale:动态计算loss scale的值并判断是否溢出。
@@ -186,27 +191,28 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
| **分支名** | **当前状态** | **上线时间** | **后续状态** | **EOL 日期**|
|------------|--------------|----------------------|----------------------------------------|------------|
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
| **v2.0.4** | Maintained | 2022-01-15 | Unmaintained <br> 2023-01-15 estimated | |
| **v2.0.2** | EOL | 2021-07-29 | N/A | |
| **v2.0.3** | EOL | 2021-10-15 | N/A | |
| **v2.0.4** | Unmaintained | 2022-01-15 | EOL <br> 2023-04-15 estimated | |
| **v3.0.rc1** | Maintained | 2022-04-10 | Unmaintained <br> 2023-04-10 estimated | |
| **v3.0.rc2** | Maintained | 2022-07-15 | Unmaintained <br> 2023-07-15 estimated | |
| **v3.0.rc3** | Maintained | 2022-10-20 | Unmaintained <br> 2023-10-20 estimated | |
| **v3.0.0** | Maintained | 2023-1-18 | Unmaintained <br> 2024-1-18 estimated | |
# FAQ
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch1.8.1,需要使用源码编译安装。
## CPU架构为ARM架构时,由于社区未提供ARM架构CPU版本的torch包,无法使用PIP3命令安装PyTorch,需要使用源码编译安装。
下载PyTorch v1.8.1源码包。
下载PyTorch v1.11.0源码包。
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
git clone -b v1.11.0 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.11.0
```
进入源码包获取被动依赖代码。
```
cd pytorch_v1.8.1
cd pytorch_v1.11.0
git submodule sync
git submodule update --init --recursive
```
@@ -336,7 +342,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
以下步骤请在root用户下执行。
1. 下载gcc-7.3.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.3.0/gcc-7.3.0.tar.gz)。
1. 下载gcc-7.5.0.tar.gz,下载地址为[https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz](https://mirrors.tuna.tsinghua.edu.cn/gnu/gcc/gcc-7.5.0/gcc-7.5.0.tar.gz)。
2. 安装gcc时候会占用大量临时空间,所以先执行下面的命令清空/tmp目录:
@@ -360,20 +366,20 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
4. 编译安装gcc。
1. 进入gcc-7.3.0.tar.gz源码包所在目录,解压源码包,命令为:
1. 进入gcc-7.5.0.tar.gz源码包所在目录,解压源码包,命令为:
```
tar -zxvf gcc-7.3.0.tar.gz
tar -zxvf gcc-7.5.0.tar.gz
```
2. 进入解压后的文件夹,执行如下命令下载gcc依赖包:
```
cd gcc-7.3.0
cd gcc-7.5.0
./contrib/download_prerequisites
```
如果执行上述命令报错,需要执行如下命令在“gcc-7.3.0/“文件夹下下载依赖包:
如果执行上述命令报错,需要执行如下命令在“gcc-7.5.0/“文件夹下下载依赖包:
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
@@ -393,20 +399,20 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
3. <a name="zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310"></a>执行配置、编译和安装命令:
```
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.3.0
./configure --enable-languages=c,c++ --disable-multilib --with-system-zlib --prefix=/usr/local/linux_gcc7.5.0
make -j15 # 通过grep -w processor /proc/cpuinfo|wc -l查看cpu数,示例为15,用户可自行设置相应参数。
make install
```
>![](figures/icon-notice.gif) **须知:**
>其中“--prefix“参数用于指定linux\_gcc7.3.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.3.0“。
>其中“--prefix“参数用于指定linux\_gcc7.5.0安装路径,用户可自行配置,但注意不要配置为“/usr/local“及“/usr“,因为会与系统使用软件源默认安装的gcc相冲突,导致系统原始gcc编译环境被破坏。示例指定为“/usr/local/linux\_gcc7.5.0“。
4. 修改软连接。
```
ln -s ${install_path}/gcc-7.3.0/bin/gcc /usr/bin/gcc
ln -s ${install_path}/gcc-7.3.0/bin/g++ /usr/bin/g++
ln -s ${install_path}/gcc-7.3.0/bin/c++ /usr/bin/c++
ln -s ${install_path}/gcc-7.5.0/bin/gcc /usr/bin/gcc
ln -s ${install_path}/gcc-7.5.0/bin/g++ /usr/bin/g++
ln -s ${install_path}/gcc-7.5.0/bin/c++ /usr/bin/c++
```
5.配置环境变量。
@@ -417,7 +423,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
export LD_LIBRARY_PATH=${install_path}/lib64:${LD_LIBRARY_PATH}
```
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.3.0安装路径,本示例为“/usr/local/gcc7.3.0/“。
其中$\{install\_path\}为[3.](#zh-cn_topic_0000001135347812_zh-cn_topic_0000001173199577_zh-cn_topic_0000001172534867_zh-cn_topic_0276688294_li1649343041310)中配置的gcc7.5.0安装路径,本示例为“/usr/local/gcc7.5.0/“。
>![](figures/icon-note.gif) **说明:**
>本步骤为用户在需要用到gcc升级后的编译环境时才配置环境变量。
@@ -425,7 +431,7 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
若存在pytorch编译不过,请检查软连接的库是否正确。
libstdc++->libstdc++.so.6.0.24(7.3.0)
libstdc++->libstdc++.so.6.0.24(7.5.0)
## 找不到libblas.so问题
+225
View File
@@ -0,0 +1,225 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import multiprocessing
import glob
import os
import re
import shutil
import subprocess
import sys
import traceback
import platform
from sysconfig import get_paths
from distutils.version import LooseVersion
from distutils import file_util
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def which(thefile):
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
for d in path:
fname = os.path.join(d, thefile)
fnames = [fname]
if sys.platform == 'win32':
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
fnames += [fname + ext for ext in exts]
for name in fnames:
if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name):
return name
return None
def get_cmake_command():
def _get_version(cmd):
for line in subprocess.check_output([cmd, '--version']).decode('utf-8').split('\n'):
if 'version' in line:
return LooseVersion(line.strip().split(' ')[2])
raise RuntimeError('no version found')
"Returns cmake command."
cmake_command = 'cmake'
if platform.system() == 'Windows':
return cmake_command
cmake3 = which('cmake3')
cmake = which('cmake')
if cmake3 is not None and _get_version(cmake3) >= LooseVersion("3.12.0"):
cmake_command = 'cmake3'
return cmake_command
elif cmake is not None and _get_version(cmake) >= LooseVersion("3.12.0"):
return cmake_command
else:
raise RuntimeError('no cmake or cmake3 with version >= 3.12.0 found')
def get_build_type():
build_type = 'Release'
if os.getenv('DEBUG', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'Debug'
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'RelWithDebInfo'
return build_type
def get_pytorch_dir():
try:
import torch
return os.path.dirname(os.path.abspath(torch.__file__))
except Exception:
_, _, exc_traceback = sys.exc_info()
frame_summary = traceback.extract_tb(exc_traceback)[-1]
return os.path.dirname(frame_summary.filename)
def generate_bindings_code(base_dir, verbose):
generate_code_cmd = ["bash", os.path.join(base_dir, 'generate_code.sh'), verbose]
if subprocess.call(generate_code_cmd) != 0:
print(
'Failed to generate ATEN bindings: {}'.format(generate_code_cmd),
file=sys.stderr)
sys.exit(1)
def build_stub(base_dir):
build_stub_cmd = ["sh", os.path.join(base_dir, 'third_party/acl/libs/build_stub.sh')]
if subprocess.call(build_stub_cmd) != 0:
print(
'Failed to build stub: {}'.format(build_stub_cmd),
file=sys.stderr)
sys.exit(1)
def clean_generated_files():
f_ignore = open(os.path.join(BASE_DIR, '.gitignore'), 'r')
ignores = f_ignore.read()
pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
for wildcard in filter(None, ignores.split('\n')):
match = pat.match(wildcard)
if match:
if match.group(1):
# Marker is found and stop reading .gitignore.
break
# Ignore lines which begin with '#'.
else:
for filename in glob.glob(wildcard):
shutil.rmtree(filename, ignore_errors=True)
f_ignore.close()
clean_files = ['torch_npu/csrc/aten/RegisterCPU.cpp', 'torch_npu/csrc/aten/RegisterNPU.cpp',
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp', 'torch_npu/csrc/aten/NpuNativeFunctions.h']
for file in clean_files:
if os.path.exists(os.path.join(BASE_DIR, file)):
os.remove(os.path.join(BASE_DIR, file))
if os.path.exists(os.path.join(BASE_DIR, "libtorch")):
shutil.rmtree(os.path.join(BASE_DIR, "libtorch"))
def run_cmake():
cmake = get_cmake_command()
if cmake is None:
raise RuntimeError(
"CMake must be installed to build the following extensions: ")
build_dir = os.path.join(BASE_DIR, "build")
build_type_dir = os.path.join(build_dir, get_build_type())
output_lib_path = os.path.join(build_type_dir, "packages/torch_npu/lib")
os.makedirs(build_type_dir, exist_ok=True)
os.makedirs(output_lib_path, exist_ok=True)
cmake_args = [
'-DCMAKE_BUILD_TYPE=' + get_build_type(),
'-DCMAKE_INSTALL_PREFIX=' + os.path.abspath(output_lib_path),
'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DTORCHNPU_INSTALL_LIBDIR=' + os.path.abspath(output_lib_path),
'-DPYTHON_INCLUDE_DIR=' + get_paths()['include'],
'-DPYTORCH_INSTALL_DIR=' + get_pytorch_dir(),
'-DBUILD_LIBTORCH=' + "ON"]
build_args = ['-j', str(multiprocessing.cpu_count())]
subprocess.check_call([cmake, BASE_DIR] + cmake_args, cwd=build_type_dir, env=os.environ)
subprocess.check_call(['make'] + build_args, cwd=build_type_dir, env=os.environ)
def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)
"""
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
def copy_hpp():
def get_src_py_and_dst():
ret = []
header_files = [
"torch_npu/csrc/aten/*.h",
"torch_npu/csrc/aten/*/*.h",
"torch_npu/csrc/aten/*/*/*.h",
"torch_npu/csrc/core/*.h",
"torch_npu/csrc/core/*/*.h",
"torch_npu/csrc/core/*/*/*.h",
"torch_npu/csrc/framework/*.h",
"torch_npu/csrc/framework/*/*.h",
"torch_npu/csrc/framework/*/*/*.h",
"third_party/acl/inc/*/*.h",
"third_party/acl/inc/*/*/*.h"
]
glob_header_files = []
for regex_pattern in header_files:
glob_header_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
for src in glob_header_files:
dst = os.path.join(
os.path.join(BASE_DIR, f"libtorch/include/torch_npu"),
os.path.relpath(src, os.path.join(BASE_DIR, "torch_npu")))
os.makedirs(os.path.dirname(dst), exist_ok=True)
ret.append((src, dst))
return ret
ret = get_src_py_and_dst()
for src, dst in ret:
copy_file(src, dst)
def copy_lib():
lib_file = [f"build/{get_build_type()}/packages/torch_npu/lib/*.*"]
glob_lib_files = []
for regex_pattern in lib_file:
glob_lib_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
dst_path = os.path.join(BASE_DIR, f"libtorch/lib")
os.makedirs(dst_path, exist_ok=True)
for src in glob_lib_files:
_, src_file_name = os.path.split(src)
copy_file(src, os.path.join(dst_path, src_file_name))
def build_libtorch_npu():
clean_generated_files()
generate_bindings_code(BASE_DIR, "True")
build_stub(BASE_DIR)
run_cmake()
copy_hpp()
copy_lib()
if __name__ == "__main__":
build_libtorch_npu()
+65 -32
View File
@@ -23,6 +23,7 @@ from abc import ABCMeta, abstractmethod
BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
DEFAULT_UT_FILE = os.path.join(BASE_DIR, 'ci/pytorch_resnet.py')
TEST_OPS = os.path.join(BASE_DIR, 'test/test_ops.py')
class AccurateTest(metaclass=ABCMeta):
@@ -64,7 +65,7 @@ class OpStrategy(AccurateTest):
if filename.find('KernelNpu') >= 0:
feature_line = filename.split('KernelNpu')[0]
features = re.findall('[A-Z][^A-Z]*', feature_line)
regex = '*' + '*'.join(["%s" % feature.lower() for feature in features]) + '*'
regex = '*' + '*'.join([f"{feature.lower()}" for feature in features]) + '*'
return AccurateTest.find_ut_by_regex(regex)
return []
@@ -75,9 +76,7 @@ class DirectoryStrategy(AccurateTest):
"""
def identify(self, modify_file):
second_dir = modify_file.split("/")[0]
if second_dir == 'test':
return [os.path.join(BASE_DIR, modify_file)]
return []
return [os.path.join(BASE_DIR, modify_file)] if second_dir == 'test' else []
class CopyOptStrategy(AccurateTest):
@@ -94,7 +93,10 @@ class CopyOptStrategy(AccurateTest):
class TestMgr():
def __init__(self):
self.modify_files = []
self.ut_files = []
self.test_files = {
'ut_files': [],
'op_ut_files': []
}
def load(self, modify_files):
with open(modify_files) as f:
@@ -104,20 +106,22 @@ class TestMgr():
def analyze(self):
for modify_file in self.modify_files:
self.ut_files += DirectoryStrategy().identify(modify_file)
self.ut_files += OpStrategy().identify(modify_file)
self.ut_files += CopyOptStrategy().identify(modify_file)
unique_files = set(self.ut_files)
self.test_files['ut_files'] += DirectoryStrategy().identify(modify_file)
self.test_files['ut_files'] += CopyOptStrategy().identify(modify_file)
self.test_files['ut_files'] += OpStrategy().identify(modify_file)
self.test_files['op_ut_files'] += OpStrategy().identify(modify_file)
unique_files = set(self.test_files['ut_files'])
exist_ut_file = []
for changed_file in unique_files:
if os.path.exists(changed_file):
exist_ut_file.append(changed_file)
self.ut_files = exist_ut_file
self.ut_files.append(DEFAULT_UT_FILE)
exist_ut_file = [
changed_file
for changed_file in unique_files
if os.path.exists(changed_file)
]
self.test_files['ut_files'] = exist_ut_file
self.test_files['ut_files'].append(DEFAULT_UT_FILE)
def get_ut_files(self):
return self.ut_files
def get_test_files(self):
return self.test_files
def print_modify_files(self):
print("modify files:")
@@ -126,46 +130,74 @@ class TestMgr():
def print_ut_files(self):
print("ut files:")
for ut_file in self.ut_files:
for ut_file in self.test_files['ut_files']:
print(ut_file)
def print_op_ut_files(self):
print("op ut files:")
for op_ut_file in self.test_files['op_ut_files']:
print(op_ut_file)
def exec_ut(ut_files):
def exec_ut(files):
"""
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
"""
def change_dir_and_exec(ut_path):
ut_dir = os.path.dirname(ut_path)
ut_file = os.path.basename(ut_path)
def get_ut_name(ut_file):
return ut_file.split('/')[-1].split('.')[0].lstrip('test_')
def change_dir_and_exec(ut_path, is_op_ut=False):
if is_op_ut:
ut_dir = os.path.dirname(TEST_OPS)
cmd = f'python3 -m unittest test_ops.py -v -k {ut_path}_'
else:
ut_dir = os.path.dirname(ut_path)
ut_file = os.path.basename(ut_path)
cmd = f'python3 {ut_file}'
os.chdir(ut_dir)
cmd = "python3 {}".format(ut_file)
p = subprocess.Popen(['python3', ut_file], stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
p = subprocess.Popen(cmd.split(' '), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
try:
msg = p.communicate(timeout=300)
msg = p.communicate(timeout=2000)
ret = p.poll()
if ret:
print(msg)
stdout = msg[0].decode('utf-8')
stderr = msg[1].decode('utf-8') if msg[1] else msg[1]
print(stdout, stderr)
except subprocess.TimeoutExpired:
p.kill()
p.terminate()
ret = 1
print("Timeout: Command '" + cmd + "' timed out after 300 seconds")
print(f"Timeout: Command '{cmd}' timed out after 2000 seconds")
except Exception as err:
ret = 1
print(err)
return ret
ut_files = files['ut_files']
op_ut_files = files['op_ut_files']
ret_status = 0
exec_infos = []
for ut_file in ut_files:
temp_ret = change_dir_and_exec(ut_file)
if temp_ret:
ret_status = temp_ret
exec_infos.append("exec ut {} failed.".format(ut_file))
else:
exec_infos.append("exec ut {} success.".format(ut_file))
for op_ut_file in op_ut_files:
ut_name = get_ut_name(op_ut_file)
op_ut_ret = change_dir_and_exec(ut_name, True)
if op_ut_ret:
ret_status = op_ut_ret
exec_infos.append("exec ut test_ops.py {} failed.".format(ut_name))
else:
exec_infos.append("exec ut test_ops.py {} success.".format(ut_name))
print("***** Total result:")
for exec_info in exec_infos:
print(exec_info)
@@ -177,10 +209,11 @@ if __name__ == "__main__":
test_mgr = TestMgr()
test_mgr.load(cur_modify_files)
test_mgr.analyze()
cur_ut_files = test_mgr.get_ut_files()
cur_test_files = test_mgr.get_test_files()
test_mgr.print_modify_files()
test_mgr.print_ut_files()
test_mgr.print_op_ut_files()
ret_ut = exec_ut(cur_ut_files)
sys.exit(ret_ut)
ret_ut = exec_ut(cur_test_files)
sys.exit(ret_ut)
@@ -58,12 +58,10 @@ def name(func: FunctionSchema, *, faithful_name_for_out_overloads: bool = False)
# types. Returns None if the type in question is not a value type.
def valuetype_type(t: Type, *, binds: ArgName) -> Optional[NamedCType]:
if isinstance(t, BaseType):
if t.name == BaseTy.Tensor:
if t.name == BaseTy.Tensor or t.name == BaseTy.Scalar:
return None
elif t.name in BaseTypeToCppMapping:
return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
else:
raise AssertionError(f"unsupported type {repr(t)}")
# All other BaseType currently map directly to BaseCppTypes.
return NamedCType(binds, BaseCType(BaseTypeToCppMapping[t.name]))
elif isinstance(t, OptionalType):
elem = valuetype_type(t.elem, binds=binds)
if elem is None:
@@ -205,7 +203,7 @@ JIT_TO_CPP_DEFAULT = {
'None': 'c10::nullopt', # UGH this one is type directed
'Mean': 'at::Reduction::Mean',
'[]': '{}',
'contiguous_format': 'MemoryFormat::Contiguous',
'contiguous_format': 'c10::MemoryFormat::Contiguous',
'long': 'at::kLong',
}
@@ -58,25 +58,35 @@ def returns_type(rs: Sequence[Return]) -> CType:
# At present, there is no difference. But there could be!
return cpp.returns_type(rs)
def jit_arguments(func: FunctionSchema) -> List[Argument]:
def to_argument(a: Union[Argument, TensorOptionsArguments, SelfArgument]) -> List[Argument]:
if isinstance(a, Argument):
return [a]
elif isinstance(a, SelfArgument):
return [a.argument]
elif isinstance(a, TensorOptionsArguments):
return [a.dtype, a.layout, a.device, a.pin_memory]
else:
assert_never(a)
return list(concat_map(to_argument, itertools.chain(
func.arguments.positional,
func.arguments.kwarg_only,
func.arguments.out)))
def argument(a: Union[Argument, SelfArgument, TensorOptionsArguments], *, is_out: bool) -> List[Binding]:
should_default = not is_out
if isinstance(a, Argument):
default: Optional[str] = None
if should_default and a.default is not None:
default = cpp.default_expr(a.default, a.type)
return [
Binding(
nctype=argument_type(a, binds=a.name),
name=a.name,
default=default,
argument=a)
]
elif isinstance(a, SelfArgument):
return argument(a.argument, is_out=is_out)
elif isinstance(a, TensorOptionsArguments):
return (
argument(a.dtype, is_out=is_out) +
argument(a.layout, is_out=is_out) +
argument(a.device, is_out=is_out) +
argument(a.pin_memory, is_out=is_out)
)
else:
assert_never(a)
def arguments(func: FunctionSchema) -> List[Binding]:
return [
Binding(
nctype=argument_type(a, binds=a.name),
name=a.name,
argument=a,
) for a in jit_arguments(func)]
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
args.extend(func.arguments.positional)
args.extend(func.arguments.kwarg_only)
args.extend(func.arguments.out)
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
@@ -17,8 +17,7 @@
from typing import Union, Sequence, List, Optional
from codegen.model import (Argument, FunctionSchema, Return,
SelfArgument, TensorOptionsArguments, Type, UseC10Dispatcher,
assert_never)
SelfArgument, TensorOptionsArguments, Type)
from codegen.api.types import (ArgName, BaseCType, Binding,
ConstRefCType, NamedCType, CType, MutRefCType, ListCType,
@@ -26,6 +25,7 @@ from codegen.api.types import (ArgName, BaseCType, Binding,
deviceT, boolT, scalarTypeT)
from codegen.api import cpp
from codegen import local
from codegen.model import assert_never
# This file describes the translation of JIT schema to the native functions API.
# This looks a lot like the C++ API (which makes historical sense, because the
@@ -53,6 +53,10 @@ def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
return NamedCType(binds, ConstRefCType(tensor_type))
elif str(t) == 'Tensor?[]':
return NamedCType(binds, ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))))
elif str(t) == 'Scalar':
return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
elif str(t) == 'Scalar?':
return NamedCType(binds, ConstRefCType(OptionalCType(BaseCType(scalarT))))
return cpp.argumenttype_type(t, mutable=mutable, binds=binds)
def returns_type(rs: Sequence[Return]) -> CType:
@@ -120,15 +124,4 @@ def arguments(func: FunctionSchema) -> List[Binding]:
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
args.extend(func.arguments.non_out)
args.extend(func.arguments.out)
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
def native_arguments(func: FunctionSchema, dispatch: UseC10Dispatcher) -> List[Binding]:
args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
if dispatch is UseC10Dispatcher.full:
args.extend(func.arguments.non_out)
args.extend(func.arguments.out)
else:
args.extend(func.arguments.out)
args.extend(func.arguments.non_out)
return [r for arg in args for r in argument(arg, is_out=func.is_out_fn())]
@@ -641,7 +641,7 @@ def argument_type_str(t: Type, *, simple_type: bool = False) -> str:
BaseTy.Tensor: 'Tensor',
BaseTy.int: 'int64_t',
BaseTy.float: 'double',
BaseTy.str: 'std::string'
BaseTy.str: 'c10::string_view'
}
if t.name in base_dict:
return base_dict[t.name]
@@ -1048,7 +1048,7 @@ def arg_parser_unpack_method(t: Type, has_default: bool) -> str:
BaseTy.int: 'toInt64',
BaseTy.bool: 'toBool',
BaseTy.float: 'toDouble',
BaseTy.str: 'string'
BaseTy.str: 'stringView'
}
if t.name in [BaseTy.Tensor, BaseTy.Stream, BaseTy.Storage,
BaseTy.Scalar, BaseTy.Dimname]:
@@ -49,7 +49,7 @@ intT = BaseCppType('', 'int64_t')
doubleT = BaseCppType('', 'double')
boolT = BaseCppType('', 'bool')
voidT = BaseCppType('', 'void')
stringT = BaseCppType('std', 'string')
stringT = BaseCppType('c10', 'string_view')
generatorT = BaseCppType('at', 'Generator')
scalarTypeT = BaseCppType('at', 'ScalarType')
tensorT = BaseCppType('at', 'Tensor')
@@ -366,7 +366,11 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
device_check = RegisterDispatchKey.gen_device_check(f.device_check, list(device_check_args), name)
device_guard = "// DeviceGuard omitted" # default
record_func_def = "torch_npu::profiler::NPURecordFunction guard;"
record_func_def = """
#ifndef BUILD_LIBTORCH
torch_npu::profiler::NPURecordFunction guard;
#endif
"""
if f.device_guard and is_cuda_dispatch_key(self.backend_index.dispatch_key):
has_tensor_options = any(isinstance(a.argument, TensorOptionsArguments) for a in args)
if has_tensor_options:
@@ -36,7 +36,6 @@ from codegen.api.signature import (CppSignature, CppSignatureGroup, kernel_signa
import codegen.api.meta as meta
import codegen.api.cpp as cpp
import codegen.api.structured as structured
import codegen.api.native as native_arguments
from codegen.api.translate import translate
from codegen.selective_build.selector import SelectiveBuilder
from codegen.api.types import (BaseCType, TupleCType, BaseCppType)
@@ -19,15 +19,19 @@ from codegen.api.types import (BaseCType, TupleCType, OptionalCType, BaseCppType
from codegen.api.signature import DispatcherSignature, NativeSignature
from codegen.model import SchemaKind, NativeFunction
from codegen.api.native import native_arguments
from codegen.api.native import arguments
backend = None
def transfer_args_of_wrapper_func_to_cpu(sig: DispatcherSignature, func: NativeFunction) -> Tuple[str, List[str]]:
convert: str = f"// Convert args to cpu in order to use at::native kernel \n " \
f"std::cout << \"Cur kernel: {sig.func.name} is running on cpu.\" << std::endl; \n "
f"static auto warn_once = [](){{ \n " \
f"std::cout << \"Warning: kernel [{sig.func.name}] is not supported by NPU currently. " \
f"Now this kernel is running on CPU.\" << std::endl; \n " \
f"return true; \n " \
f"}}(); \n "
args_names: List[str] = []
args = native_arguments(sig.func, func.use_c10_dispatcher)
args = arguments(sig.func)
for arg in args:
arg_type = str(arg.type)
if 'Tensor' not in arg_type:
@@ -126,4 +130,4 @@ auto cpu_ret = {func_call};
else:
assert False, f'Do not support cur func type {sig.func.kind()}'
return ret_code
return ret_code
@@ -41,6 +41,8 @@ def create_backend_index(backend_ops: List[str],
for op in backend_ops:
op_name = OperatorName.parse(op)
assert op_name in native_funcs_map, f"Found an invalid operator name: {op_name}"
if os.environ.get('BSCPP_OPS_ENABLE') is None and native_funcs_map[op_name].bscpp_op:
continue
# See Note [External Backends Follow Dispatcher API]
kernel_name = dispatcher.name(native_funcs_map[op_name].func)
# TODO: allow structured external backends later.
@@ -153,7 +155,8 @@ def parse_backend_yaml(
valid_keys = ['backend', 'cpp_namespace', 'extra_headers', 'supported', 'autograd', 'custom', 'custom_autograd']
true_backend = yaml_values.pop('backend', None)
yaml_backend = yaml_values.pop('backend', None)
true_backend = 'XLA' if yaml_backend=='NPU' else yaml_backend
assert true_backend is not None, 'You must provide a value for "backend"'
backend = "NPU"
@@ -242,16 +245,10 @@ def error_on_missing_kernels(
expected_backend_kernel_name_counts[dispatcher.name(native_f.func)].append(native_f)
missing_kernels_err_msg = ""
unsupported_ops_list = ""
for expected_name, funcs in expected_backend_kernel_name_counts.items():
expected_overload_count = len(funcs)
actual_overload_count = actual_backend_kernel_name_counts[expected_name]
if actual_overload_count == 0:
for func in funcs:
backend_indices[backend_key].index.pop(func.func.name, None)
backend_indices[autograd_key].index.pop(func.func.name, None)
unsupported_ops_list += f"{func.func.name}\n"
elif expected_overload_count != actual_overload_count:
if expected_overload_count != actual_overload_count:
def create_decl(f: NativeFunction) -> str:
with native_function_manager(f):
return DispatcherSignature.from_schema(f.func).decl()
@@ -262,8 +259,7 @@ but expected {expected_overload_count} kernel(s). The expected function schemas
{expected_schemas_str}
"""
assert missing_kernels_err_msg == "", missing_kernels_err_msg
if unsupported_ops_list != "":
print(f"Unsupported Ops List:\n{unsupported_ops_list}")
def error_on_cpu_kernels(
cur_backend_key: DispatchKey,
@@ -283,6 +279,7 @@ def error_on_cpu_kernels(
for func in funcs:
backend_indices[DispatchKey.CPU].index.pop(func.func.name, None)
def main() -> None:
parser = argparse.ArgumentParser(description='Generate backend stub files')
parser.add_argument(
@@ -301,6 +298,7 @@ def main() -> None:
run(options.to_cpu, options.source_yaml, options.output_dir, options.dry_run, options.impl_path)
def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path: Optional[str]) -> None:
template_dir = os.path.join(pathlib.Path(__file__).parent.absolute(), "templates")
@@ -323,6 +321,8 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
backend_indices = parsed_backend_yaml.backend_indices
selector = SelectiveBuilder.get_nop_selector()
if backend_key is not None:
backend_dispatch_key: DispatchKey = backend_key
autograd_dispatch_key: DispatchKey = autograd_key
@@ -393,7 +393,7 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
grouped_native_functions
)),
})
if to_cpu.upper() in ['OFF', '0', 'NO', 'FALSE', 'F', 'N']:
return
@@ -441,5 +441,6 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
)),
})
if __name__ == '__main__':
main()
@@ -21,6 +21,7 @@
import argparse
import os
import re
from collections import defaultdict, namedtuple
from typing import Dict, Optional, List, Tuple, Set, Sequence, Callable
@@ -138,6 +139,9 @@ def parse_custom_yaml(custom_path: str) -> ParsedYaml:
@with_native_function
def should_generate_py_binding(f: NativeFunction) -> bool:
if os.environ.get('BSCPP_OPS_ENABLE') is None and f.bscpp_op:
return False
name = cpp.name(f.func)
for skip_regex in SKIP_PYTHON_BINDINGS:
if skip_regex.match(name):
+52 -27
View File
@@ -95,6 +95,7 @@ class DispatchKey(Enum):
PrivateUse3 = auto()
EndOfBackendKeys = PrivateUse3
ZeroTensor = auto()
Meta = auto()
BackendSelect = auto()
Named = auto()
@@ -172,6 +173,19 @@ class DeviceCheckType(Enum):
NoCheck = 0
ExactSame = 1
class Tag(Enum):
inplace_view = 0
def __str__(self) -> str:
return self.name
@staticmethod
def parse(value: str) -> 'Tag':
for k, v in Tag.__members__.items():
if k == value:
return v
raise AssertionError(f'unknown tag {value}')
# The basic input to the code generation is native_functions.yaml.
# The name "native", BTW, comes from the distinction between native
# functions and legacy TH functions. The legacy TH functions are gone,
@@ -193,10 +207,6 @@ class NativeFunction:
# classes for expository clarity.)
func: 'FunctionSchema'
# Corresponds to the 'use_c10_dispatcher' field. The default
# is 'full'
use_c10_dispatcher: UseC10Dispatcher
# Whether or not to generate mutable tensor arguments like regular
# ones
use_const_ref_for_mutable_tensors: bool
@@ -273,6 +283,14 @@ class NativeFunction:
has_composite_implicit_autograd_kernel: bool
has_composite_explicit_autograd_kernel: bool
# Tags are used to describe semantic information about (groups of) operators,
# That aren't easily inferrable directly from the operator's schema.
# For now operators have at most one tag.
tag: Optional['Tag']
# Whether or not the NativeFunction is bishengcpp kernel
bscpp_op: bool
# NB: The benefit of defining a dataclass is that we automatically get
# a constructor defined for all the fields we specify. No need
# to explicitly write it out.
@@ -295,19 +313,6 @@ class NativeFunction:
cpp_no_default_args = set(cpp_no_default_args_list)
return cpp_no_default_args
def parse_use_dispatcher(e):
use_c10_dispatcher_s = e.pop('use_c10_dispatcher', None)
assert use_c10_dispatcher_s != 'full', \
"No need to specify 'use_c10_dispatcher: full' anymore. This is the default now. Just remove the line."
if use_c10_dispatcher_s is None:
use_c10_dispatcher = UseC10Dispatcher.full
elif use_c10_dispatcher_s == 'hacky_wrapper_for_legacy_signatures':
use_c10_dispatcher = UseC10Dispatcher.hacky_wrapper_for_legacy_signatures
else:
raise AssertionError(f'use_c10_dispatcher must be full or hacky_wrapper_for_legacy_signatures,'
f' got {use_c10_dispatcher_s}')
return use_c10_dispatcher
def parse_variants(e):
variants_s = e.pop('variants', 'function')
assert isinstance(variants_s, str)
@@ -323,7 +328,6 @@ class NativeFunction:
func = parse_func(e)
cpp_no_default_args = parse_cpp_no_default_args(e)
use_c10_dispatcher = parse_use_dispatcher(e)
variants = parse_variants(e)
use_const_ref_for_mutable_tensors = e.pop('use_const_ref_for_mutable_tensors', False)
@@ -374,6 +378,15 @@ class NativeFunction:
precomputed = parse_precomputed(e, structured)
def parse_tag(e, structured):
tag_str = e.pop('tags', None)
assert tag_str is None or isinstance(tag_str, str), f'not a str: {tag_str}'
tag = Tag.parse(tag_str) if tag_str else None
return tag
tag = parse_tag(e, structured)
bscpp_op = e.pop("bscpp_op", False)
from codegen.api import cpp
def parse_dispatch(e, func, manual_kernel_registration, structured_delegate, structured):
@@ -433,7 +446,7 @@ class NativeFunction:
f"if structured_delegate, then must not have {key} in dispatch dictionary " \
"(it is delegated!)"
assert_last(e, structured_delegate, dispatch)
return NativeFunction(func=func, use_c10_dispatcher=use_c10_dispatcher,
return NativeFunction(func=func,
use_const_ref_for_mutable_tensors=use_const_ref_for_mutable_tensors,
variants=variants, structured=structured, structured_delegate=structured_delegate,
structured_inherits=structured_inherits, precomputed=precomputed,
@@ -441,7 +454,8 @@ class NativeFunction:
python_module=python_module, category_override=category_override, device_guard=device_guard,
device_check=device_check, cpp_no_default_args=cpp_no_default_args, is_abstract=is_abstract,
has_composite_implicit_autograd_kernel=has_composite_implicit_autograd_kernel,
has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel), backend_metadata
has_composite_explicit_autograd_kernel=has_composite_explicit_autograd_kernel, tag=tag,
bscpp_op=bscpp_op), backend_metadata
def validate_unstructured(self) -> None:
@@ -481,9 +495,6 @@ class NativeFunction:
if a.default is not None}
invalid_args = set.difference(self.cpp_no_default_args, defaulted_arguments)
assert len(invalid_args) == 0, f'Invalid cpp_no_default_args: {invalid_args}'
if self.structured or self.structured_delegate:
assert self.use_c10_dispatcher is UseC10Dispatcher.full, \
"Structured kernels MUST be use_c10_dispatcher: full; port your argument order"
if self.structured_inherits is not None:
assert self.structured, "structured_inherits must also imply structured: True"
if str(self.func.name).startswith('_foreach'):
@@ -682,7 +693,7 @@ class BackendIndex:
elif isinstance(g, NativeFunctionsGroup):
f = self.primary(g)
else:
assert_never(f)
assert_never(g)
if f.func.name not in self.index:
return None
return self.index[f.func.name]
@@ -771,7 +782,9 @@ class FunctionSchema:
def parse(func: str) -> 'FunctionSchema':
# We should probably get a proper parser here
assert ' -> ' in func, "function schema missing return type (spaces are mandatory)"
func_decl, return_decl = [x.strip() for x in func.split(' -> ')]
last_index = func.rfind(" -> ")
func_decl = func[:last_index]
return_decl = func[last_index + len(" -> "):]
ops, args = func_decl.split('(', 1)
assert args[-1] == ")", "Expecting closing )"
args = args[:-1]
@@ -912,19 +925,31 @@ class Annotation:
# we can conveniently assume it is canonically ordered
alias_set: Tuple[str, ...]
is_write: bool
alias_set_after: str
@staticmethod
def parse(ann: str) -> 'Annotation':
m = re.match(r'^([a-z])(!?)(!?)$', ann)
# Only handling afterSet == Wildcard for now
becomes_wildcard_index = ann.find(" -> *")
if becomes_wildcard_index != -1:
after_set = "*"
# TODO: im not good enough with regexes to ignore -> *
m = re.match(r'^([a-z])(!?)(!?)$',
ann[:becomes_wildcard_index] + ann[becomes_wildcard_index + len(" -> *"):])
else:
after_set = ""
m = re.match(r'^([a-z])(!?)(!?)$', ann)
assert m is not None, f'unrecognized alias annotation {ann}'
alias_set = (m.group(1),)
is_write = m.group(2) == '!'
r = Annotation(alias_set=alias_set, is_write=is_write)
r = Annotation(alias_set=alias_set, is_write=is_write, alias_set_after=after_set)
assert str(r) == ann, f'{r} != {ann}'
return r
def __str__(self) -> str:
alias_set = '|'.join(self.alias_set)
if self.alias_set_after:
alias_set = f'{alias_set}{" -> "}{self.alias_set_after}'
is_write = '!' if self.is_write else ''
return f'{alias_set}{is_write}'
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// Copyright (c) 2022, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#ifndef __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
#define __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
#include <ATen/Tensor.h>
#include <ATen/ATen.h>
#include <c10/core/Device.h>
namespace at_npu {
namespace key {
static constexpr c10::DeviceType NativeDeviceType = c10::DeviceType::XLA;
static constexpr c10::DispatchKey NativeDispatchKey = c10::DispatchKey::XLA;
static constexpr c10::DispatchKey NativeAutogradDispatchKey = c10::DispatchKey::AutogradXLA;
static constexpr c10::Backend NativeBackend = c10::Backend::XLA;
static const std::string npu_device_str = "npu";
static const std::string default_device_str = "xla";
static bool isDeviceTensor(const at::Tensor &tensor) {
return tensor.is_xla();
}
} // namespace key
} // namespace at_npu
// ${generated_comment}
namespace ${cpp_namespace} {
struct ${class_name} {
${dispatch_declarations}
};
} // namespace ${cpp_namespace}
#endif
@@ -33,7 +33,6 @@
#include <ATen/WrapDimUtils.h>
#include <ATen/Dispatch.h>
#include <c10/util/Half.h>
#include <c10/core/TensorImpl.h>
#include <c10/core/UndefinedTensorImpl.h>
#include <c10/util/Optional.h>
#include <ATen/Tensor.h>
@@ -46,11 +45,12 @@
#include <utility>
#include <ATen/Config.h>
#include <ATen/core/op_registration/hacky_wrapper_for_legacy_signatures.h>
#include <torch/library.h>
#include "torch_npu/csrc/profiler/utils.h"
$legacy_th_headers
#ifndef BUILD_LIBTORCH
#include "torch_npu/csrc/profiler/utils.h"
#endif
$external_backend_headers
$namespaced_headers
@@ -1,3 +1,19 @@
// Copyright (c) 2020 Huawei Technologies Co., Ltd
// Copyright (c) 2019, Facebook CORPORATION.
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ${generated_comment}
// Python bindings for torch.* functions implemented through ATen.
@@ -31,6 +47,7 @@
#include <torch/csrc/utils/structseq.h>
#include <torch/csrc/utils/cuda_lazy_init.h>
#include <ATen/ATen.h>
#include <ATen/record_function.h>
#include <functional>
#include <initializer_list>
@@ -39,6 +56,7 @@
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/utils/LazyInit.h"
#include "torch_npu/csrc/utils/DeviceParser.h"
using at::Tensor;
using at::Device;
@@ -13,18 +13,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy
import torch
import torch_npu
from torch_npu.utils.device_guard import torch_device_guard, device
@torch_device_guard
def _device(*args, **kwargs):
new_device = torch_npu.new_device(*args, **kwargs)
if new_device.type == torch.npu.native_device:
return device(type=torch_npu.npu.npu_device, index=new_device.index)
return new_device
from torch_npu.utils.device_guard import torch_device_guard
@torch_device_guard
@@ -62,6 +55,11 @@ def _npu_dropout_gen_mask(*args, **kwargs):
return torch_npu.npu_dropout_gen_mask(*args, **kwargs)
@torch_device_guard
def _new_device(*args, **kwargs):
return torch_npu._C.device(*args, **kwargs)
def jit_script(obj, optimize=None, _frames_up=0, _rcb=None):
# (Ascend) Disable extension of torch.jit.script
return obj
@@ -82,7 +80,6 @@ def _as_tensor(*args, **kwargs):
${device_methods_def_py_dispatch}
def add_torch_funcs():
torch.device = _device
torch.tensor = _tensor
torch.full = _full
torch.randint = _randint
@@ -92,5 +89,6 @@ def add_torch_funcs():
torch.npu_dropout_gen_mask = _npu_dropout_gen_mask
torch.jit.script = jit_script
torch.as_tensor = _as_tensor
torch.new_device = _new_device
${device_methods_def_py}
+1
View File
@@ -375,6 +375,7 @@
| 255 | torch.trapz | Supported |
| 256 | torch.triangular_solve | Supported |
| 257 | torch.vdot | Supported |
| 258 | torch.aminmax | Supported |
## Utilities
@@ -438,7 +438,7 @@ The following uses the torch.add() operator as an example to describe the develo
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize,
outputTensor.options(),
CalcuOpUtil::get_tensor_npu_format(outputTensor));
CalcuOpUtil::GetTensorNpuFormat(outputTensor));
// calculate the output result of the NPU
add_out_npu_nocheck(result, self, other, alpha);
@@ -454,7 +454,7 @@ The following uses the torch.add() operator as an example to describe the develo
auto outputSize = input_same_output_size(self);
// construct the output tensor of the NPU
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
outputSize, self.options(), CalcuOpUtil::GetTensorNpuFormat(self));
// calculate the output result of the NPU
adds_out_npu_nocheck(result, self, other, alpha);
@@ -472,7 +472,7 @@ The following uses the torch.add() operator as an example to describe the develo
{
c10::SmallVector<at::Tensor, N> inputs = {self, other};
c10::SmallVector<at::Tensor, N> outputs = {self};
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
if (!NpuUtils::check_match(&self))
{
@@ -516,7 +516,7 @@ The following uses the torch.add() operator as an example to describe the develo
at::Scalar alpha,
at::Tensor &result)
{
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self);
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
at::Tensor outputTensor;
if (not isSelfWrapped)
@@ -531,7 +531,7 @@ The following uses the torch.add() operator as an example to describe the develo
OpPreparation::CheckOut(
{self},
result,
CalcuOpUtil::get_tensor_npu_format(result),
CalcuOpUtil::GetTensorNpuFormat(result),
outputTensor.scalar_type(),
outputSize);
+1
View File
@@ -570,6 +570,7 @@
| | argmin | 是 |
| | amax | 是 |
| | amin | 是 |
| | aminmax | 是 |
| | all | 是 |
| | any | 是 |
| | max | 是 |
@@ -0,0 +1,318 @@
# PyTorch毕昇C++算子开发指南
- [简介](#简介md)
- [环境准备](#环境准备md)
- [C++ Extension方式开发算子](#Extension方式开发算子md)
- [环境准备](#环境准备md)
- [示例:add算子实现](#add算子md)
- [示例:add算子编译](#add算子安装代码md)
- [示例:add算子测试](#add算子测试md)
- [框架联合编译方式开发算子](#框架联合编译方式开发算子md)
- [FAQ](#FAQmd)
- [示例add算子编译失败](#python-setup_py-install失败md)
- [示例add算子测试失败](#python-test_add_bisheng_py失败md)
<h2 id="简介md">简介</h2>
毕昇C++提供了面向昇腾芯片的通用编程模型抽象,让开发者可以使用标准C++语法编写适用于昇腾芯片的算子。
昇腾PyTorch支持C++ Extension和框架联合编译两种方式开发毕昇C++算子,该文档介绍了怎么在PyTorch中使用毕昇C++开发算子。
<h2 id="环境准备md">环境准备</h2>
在PyTorch框架中开发毕昇C++算子环境准备包括两部分内容:一是CANN和毕昇C++的安装,二是PyTorch框架安装:
- CANN和毕昇C++的安装:当前毕昇C++内置于CANN 6.3.T100版本,安装CANN时同时安装毕昇C++,使用CANN内置脚本配置CANN环境变量时会同时配置毕昇C++环境变量。
- CANN 6.3.T100下载地址及毕昇C++文档请参考:[CANN 6.3.T100(毕昇C++)安装包及文档](https://support.huawei.com/enterprise/zh/ascend-computing/cann-pid-251168373/software/259218207?idAbsPath=fixnode01%7C23710424%7C251366513%7C22892968%7C251168373);
- CANN安装请参考昇腾社区文档中环境安装环节[《CANN软件安装》](https://www.hiascend.com/document?tag=community-developer)
- 安装后运行CANN安装目录下的`set_env.sh`自动配置CANN和毕昇C++相关环境变量。
安装CANN并完成环境变量配置后可以查看CANN和毕昇C++的环境变量:
```
echo $BISHENG_CPP_HOME
echo $ASCEND_HOME_PATH
```
- 参考README里编译安装原生PyTorch和昇腾PyTorch
<h2 id="Extension方式开发算子md">C++ Extension方式开发算子</h2>
<h3 id="环境准备md">环境准备</h3>
参考前文安装CANN、毕昇C++和PyTorch,并配置环境变量
<h3 id="add算子md">示例:add算子实现</h3>
add_bisheng.cpp
```
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <sycl/sycl.hpp>
#include <acl/acl.h>
#include <torch/extension.h>
#include <torch_npu/csrc/core/npu/NPUStream.h>
using namespace at;
using namespace sycl;
using namespace sycl::access;
template <typename T>
using LocalAccessor = accessor<T, 1, mode::read_write, target::local>;
template <typename T, int group_count, typename kernel_name>
void add_bisheng_kernel(queue &sycl_queue, const T *in1, const T *in2, T *out, size_t length) {
sycl_queue.submit([&](handler &cgh)
{
LocalAccessor<T> local_in1(length, cgh);
LocalAccessor<T> local_in2(length, cgh);
LocalAccessor<T> local_out(length, cgh);
cgh.parallel_for_work_group<kernel_name>(sycl::range<1> { group_count }, [=](group<1> grp) {
const auto gid = grp.get_id(0);
const auto idx_base = gid * length;
[[loop::parallel]] for (size_t i = 0; i < length; ++i) {
local_in1[i] = in1[i + idx_base];
local_in2[i] = in2[i + idx_base];
local_out[i] = local_in1[i] + local_in2[i];
out[i + idx_base] = local_out[i];
}
}); });
sycl_queue.wait();
}
template <class T, class kernel_name>
Tensor add_bisheng_launch(const Tensor &self, const Tensor &other) {
Tensor result = at::empty(self.sizes(), self.options());
const T *self_ptr = static_cast<T *>(self.storage().data_ptr().get());
const T *other_ptr = static_cast<T *>(other.storage().data_ptr().get());
T *result_ptr = static_cast<T *>(result.storage().data_ptr().get());
aclrtContext acl_context;
aclrtGetCurrentContext(&acl_context);
sycl::context sycl_context = sycl::make_context<sycl::backend::cce>(acl_context);
int device_id = 0;
aclrtGetDevice(&device_id);
auto npu_stream = c10_npu::getCurrentNPUStream(device_id);
auto acl_stream = npu_stream.stream();
queue sycl_queue = sycl::make_queue<sycl::backend::cce>(acl_stream, sycl_context);
const T *input1 = self_ptr;
const T *input2 = other_ptr;
constexpr size_t group_count = 1;
size_t len = result.numel() / group_count;
add_bisheng_kernel<T, group_count, kernel_name>(sycl_queue, input1, input2, result_ptr, len);
return result;
}
Tensor add_bisheng(const Tensor &self, const Tensor &other) {
if (self.scalar_type() == at::kHalf) {
return add_bisheng_launch<half, class addhalf>(self, other);
} else if (self.scalar_type() == at::kFloat) {
return add_bisheng_launch<float, class addfloat>(self, other);
} else {
return add_bisheng_launch<int64_t, class addint>(self, other);
}
}
PYBIND11_MODULE(add_bisheng, m) {
m.def("add", &add_bisheng, "x + y");
}
```
<h3 id="add算子安装代码md">示例:add算子编译</h3>
python setup.py install
```
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension
from torch_npu.utils.cpp_extension import BiShengExtension
setup(
name='add_bisheng',
ext_modules=[
BiShengExtension(
name='add_bisheng',
sources=['add_bisheng.cpp']),
],
cmdclass={
'build_ext': BuildExtension
})
```
<h3 id="add算子测试md">示例:add算子测试</h3>
python test_add_bisheng.py
```
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import time
import torch
import torch_npu
JIT_COMPILE_EXTENSION = True
if JIT_COMPILE_EXTENSION:
from torch_npu.utils.cpp_extension import load
module = load(name="add_bisheng", sources=["./add_bisheng.cpp"], verbose=1)
else:
# python setup.py install
import add_bisheng as module
torch.manual_seed(0)
npu_device = os.environ.get('SET_NPU_DEVICE')
if npu_device is None:
torch.npu.set_device("npu:0")
else:
torch.npu.set_device(f"npu:{npu_device}")
a = torch.rand(2, 10).npu()
b = torch.rand(2, 10).npu()
print("A: " + str(a))
print("B: " + str(b))
add_result = module.add(a, b)
print("add_result: " + str(add_result))
print("\n")
a = torch.randint(0, 10, (2, 10)).npu()
b = torch.randint(0, 10, (2, 10)).npu()
print("A int: " + str(a))
print("B int: " + str(b))
add_result = module.add(a, b)
print("add_result int: " + str(add_result))
print("\n")
a = torch.rand(2, 10).half()
b = torch.rand(2, 10).half()
a = a.npu()
b = b.npu()
print("A half: " + str(a))
print("B half: " + str(b))
add_result = module.add(a, b)
print("add_result half: " + str(add_result))
```
<h2 id="框架联合编译方式开发算子md">框架联合编译方式开发算子</h2>
- 在torch_npu/csrc/aten/npu_native_functions.yaml增加接口定义, 参考:bscpp_add
```
- func: bscpp_add(Tensor self, Tensor other) -> Tensor
bscpp_op: True
```
- 在torch_npu/csrc/aten/bscpp_ops目录下增加算子实现CPP文件,参考:AddKernel.cpp
- 编译框架:
```
# BSCPP_SYCL_TARGET设置请参考毕昇C++文档
BSCPP_OPS_ENABLE=1 BSCPP_SYCL_TARGET=ascend_910-cce bash ci/build.sh
```
- 安装框架:
```
pip install --upgrade --force-reinstall dist/*.whl
```
<h2 id="FAQmd">FAQ</h2>
- **[示例add算子编译失败](#python-setup_py-install失败md)**
- **[示例add算子测试失败](#python-test_add_bisheng_py失败md)**
<h3 id="python-setup_py-install失败md">示例add算子编译失败</h3>
#### 现象描述
/opt/BiShengCPP/bin/clang: error while loading shared libraries: libtinfo.so.6: cannot open shared object file: No such file or directory
#### 处理方法
复制libtinfo.so.6到 ${BISHENTCPP_ROOT}/lib
```
(***111) root@ubuntu:/home/***/add_bisheng# find / -name "libtinfo.so.6"
/root/miniconda3/pkgs/ncurses-6.3-h2f4d8fa_2/lib/libtinfo.so.6
/root/miniconda3/pkgs/ncurses-6.3-h998d150_3/lib/libtinfo.so.6
/root/miniconda3/envs/pt181/lib/libtinfo.so.6
/root/miniconda3/envs/pt111/lib/libtinfo.so.6
/root/miniconda3/envs/***111/lib/libtinfo.so.6
/root/miniconda3/lib/libtinfo.so.6
/home/syf/miniconda3/pkgs/ncurses-6.3-h2f4d8fa_2/lib/libtinfo.so.6
/home/syf/miniconda3/pkgs/ncurses-6.3-h998d150_3/lib/libtinfo.so.6
/home/syf/miniconda3/lib/libtinfo.so.6
(***111) root@ubuntu:/home/***/add_bisheng# cp /root/miniconda3/lib/libtinfo.so.6 ${BISHENTCPP_ROOT}/lib
```
<h3 id="python-test_add_bisheng_py失败md">示例add算子测试失败</h3>
#### 现象描述
```
ERROR: setUpClass (__main__.test_add_bisheng)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/testing/testcase.py", line 71, in setUpClass
self.npu_device = set_npu_device()
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/testing/common_utils.py", line 83, in set_npu_device
torch.npu.set_device(npu_device)
File "/root/miniconda3/envs/***111/lib/python3.7/site-packages/torch_npu/npu/utils.py", line 149, in set_device
torch_npu._C._npu_setDevice(torch.device(device).index)
RuntimeError: Initialize:/home/***/PyTorch/torch_npu/csrc/core/npu/sys_ctrl/npu_sys_ctrl.cpp:97 NPU error, error code is 507033
EL0003: The argument is invalid.
Solution: Try again with a valid argument.
TraceBack (most recent call last):
Failed to open device, retCode=0x7020014, deviceId=0.[FUNC:Init][FILE:device.cc][LINE:227]
Check param failed, dev can not be NULL![FUNC:DeviceRetain][FILE:runtime.cc][LINE:2133]
Check param failed, dev can not be NULL![FUNC:PrimaryContextRetain][FILE:runtime.cc][LINE:1946]
Check param failed, ctx can not be NULL![FUNC:PrimaryContextRetain][FILE:runtime.cc][LINE:1973]
Check param failed, context can not be null.[FUNC:NewDevice][FILE:api_impl.cc][LINE:1315]
new device failed, retCode=0x7010006[FUNC:SetDevice][FILE:api_impl.cc][LINE:1336]
rtSetDevice execute failed, reason=[device retain error][FUNC:FuncErrorReason][FILE:error_message_manage.cc][LINE:49]
open device 0 failed, runtime result = 507033.[FUNC:ReportCallError][FILE:log_inner.cpp][LINE:161]
ctx is NULL![FUNC:GetDevErrMsg][FILE:api_impl.cc][LINE:3490]
rtGetDevMsg execute failed, reason=[context pointer null][FUNC:FuncErrorReason][FILE:error_message_manage.cc][LINE:49]
```
#### 处理方法
export SET_NPU_DEVICE=1
@@ -446,7 +446,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize,
outputTensor.options(),
CalcuOpUtil::get_tensor_npu_format(outputTensor));
CalcuOpUtil::GetTensorNpuFormat(outputTensor));
// calculate the output result of the NPU
add_out_npu_nocheck(result, self, other, alpha);
@@ -462,7 +462,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
auto outputSize = input_same_output_size(self);
// construct the output tensor of the NPU
at::Tensor result = OpPreparation::ApplyTensorWithFormat(
outputSize, self.options(), CalcuOpUtil::get_tensor_npu_format(self));
outputSize, self.options(), CalcuOpUtil::GetTensorNpuFormat(self));
// calculate the output result of the NPU
adds_out_npu_nocheck(result, self, other, alpha);
@@ -480,7 +480,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
{
c10::SmallVector<at::Tensor, N> inputs = {self, other};
c10::SmallVector<at::Tensor, N> outputs = {self};
CalcuOpUtil::check_memory_over_laps(inputs, outputs);
CalcuOpUtil::CheckMemoryOverLaps(inputs, outputs);
if (!NpuUtils::check_match(&self))
{
@@ -524,7 +524,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
at::Scalar alpha,
at::Tensor &result)
{
bool isSelfWrapped = CalcuOpUtil::is_scalar_wrapped_to_tensor(self);
bool isSelfWrapped = CalcuOpUtil::IsScalarWrappedToTensor(self);
at::Tensor outputTensor;
if (not isSelfWrapped)
@@ -539,7 +539,7 @@ custom_autograd: # 自定义继承自Function的自定义算子
OpPreparation::CheckOut(
{self},
result,
CalcuOpUtil::get_tensor_npu_format(result),
CalcuOpUtil::GetTensorNpuFormat(result),
outputTensor.scalar_type(),
outputSize);
@@ -264,6 +264,43 @@ print(tensor_data[2]) # 数据类型
print(tensor_data[3]) # 数据尺寸
```
基于step粒度控制精度对比数据导出,通过在register_hook方法设置schedule参数控制需要导出数据的step。
* **schedule**用于控制使能的step,入参分别为:**起始step(begin=0)、终止step(end=sys.maxsize)、步长(stride=1)**,例:
schedule() 使能所有step;
schedule(4, 10, 2) 使能的step为:4,6,8,10;
schedule(begin=5, stride=3) 使能的step为:5,8,11,14...;
schedule(end=10, stride=3) 使能的step为:0,3,6,9。
* 变量step_num用于记录step数,调用**step_schedule.step**使变量step_num加1,step_num初始值为0;**step_schedule.reset_step**初始化step_num为0。
```python
from torch_npu.hooks import register_hook, wrap_acc_cmp_hook, schedule, step_schedule
# add step schedule, begin=4 end=10 stride=2
register_hook(model, wrap_acc_cmp_hook, schedule=schedule(4, 10, 2))
for epoch in range(num_train_epochs):
# init step_num as 0
step_schedule.reset_step()
for step, inputs in enumerate(dataloader):
output = model(inputs)
loss = output.sum()
loss.backward()
# step_num increase 1
step_schedule.step()
```
异步算子数据导出wrap_async_datadump_hook(仅应用于npu算子导出);针对精度对比工具同步tensor数据导出,npu同cpu数据同步耗时较长的问题,利用npu上tdtchannel实现tensor数据的异步导出。
* 通过register_hook方法注册异步导出hook wrap_async_datadump_hook,并通过path参数指定导出tensor数据的路径;导出算子较多时,可以通过capacity参数调整异步导出队列长度,默认3,参数范围3~2048。
* 导出的文件名为:唯一索引_算子名_前反向_输入输出_shape_stride_offset_format.npy,例:16_Functional_relu_backward_input0_shape[2,1]_stride[1,1]_offset[0]_format[2].npy;导出的文件可以使用numpy.load方便导入。
* wrap_async_datadump_hook依赖OutfeedEnqueueOpV2算子,该算子不支持runtime2.0;需设置环境变量规避**export RUNTIME_V2_BLACKLIST=OutfeedEnqueueOpV2**。
```python
from torch_npu.hooks import register_hook, wrap_async_datadump_hook, schedule, step_schedule
# register wrap_async_datadump_hook and add datadump path
register_hook(module, wrap_async_datadump_hook, path='./output', schedule=schedule(1, 2))
# load datadump data by numpy
numpy.load('./output/16_Functional_relu_backward_input0_shape[2,1]_stride[1,1]_offset[0]_format[2].npy')
```
- [**PyTorch溢出检测工具使用指南**](#pytorch精度对比工具使用指南)
- [**使用场景**](#使用场景)
+128 -1
View File
@@ -1,4 +1,11 @@
# FrameworkPTAdapter 3.0.RC3 版本说明书
# FrameworkPTAdapter 3.0.0 版本说明书
- [FrameworkPTAdapter 3.0.0](#FrameworkPTAdapter-3-0-0md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
- [特性修改](#特性修改md)
- [已修复问题](#已修复问题md)
- [已知问题](#已知问题md)
- [兼容性](#兼容性md)
- [FrameworkPTAdapter 3.0.RC3](#FrameworkPTAdapter-3-0-RC3md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
@@ -42,6 +49,126 @@
- [已知问题](#已知问题-4md)
- [兼容性](#兼容性-5md)
<h2 id="FrameworkPTAdapter-3-0-0md">FrameworkPTAdapter 3.0.0</h2>
<h3 id="用户须知md">用户须知</h3>
本框架基于Facebook主导的开源PyTorch进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
PyTorch1.8.1版本开始采用插件化适配方式,与原生PyTorch框架实现彻底解耦,功能、性能与PyTorch1.5.0基本保持一致,对后端算子适配提供较好开发体验。PyTorch 1.11.0当前为beta版本,建议优先使用PyTorch 1.8.1版本。
<h3 id="新增特性md">新增特性</h3>
**表 1** PyTorch支持的版本特性列表
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="25.590000000000003%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>一级特性</p>
</th>
<th class="cellrowborder" valign="top" width="15.52%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>二级特性</p>
</th>
<th class="cellrowborder" valign="top" width="58.89%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="row91681125173610"><td class="cellrowborder" valign="top" width="25.590000000000003%" headers="mcps1.2.4.1.1 "><p id="p1712174492611"><a name="p1712174492611"></a><a name="p1712174492611"></a>适配NPU的PyTorch1.5.0特性</p>
</td>
<td class="cellrowborder" valign="top" width="15.52%" headers="mcps1.2.4.1.2 "><p id="p2168172519364"><a name="p2168172519364"></a><a name="p2168172519364"></a>框架基础功能</p>
</td>
<td class="cellrowborder" valign="top" width="58.89%" headers="mcps1.2.4.1.3 "><p id="p1416815259367"><a name="p1416815259367"></a><a name="p1416815259367"></a>适配CANN算子IR变更。</p>
</td>
</tr>
<tr id="row2620183971614"><td class="cellrowborder" rowspan="3" valign="top" width="25.590000000000003%" headers="mcps1.2.4.1.1 "><p id="p0819102247"><a name="p0819102247"></a><a name="p0819102247"></a>适配NPU的PyTorch1.8.1特性</p>
<p id="p15488161812213"><a name="p15488161812213"></a><a name="p15488161812213"></a></p>
</td>
<td class="cellrowborder" valign="top" width="15.52%" headers="mcps1.2.4.1.2 "><p id="p76365489137"><a name="p76365489137"></a><a name="p76365489137"></a>框架基础功能</p>
</td>
<td class="cellrowborder" valign="top" width="58.89%" headers="mcps1.2.4.1.3 "><p id="p363616485131"><a name="p363616485131"></a><a name="p363616485131"></a>支持NPU Tensor类型,修复少量BUG</p>
</td>
</tr>
<tr id="row945906124515"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1077934311314"><a name="p1077934311314"></a><a name="p1077934311314"></a>序列化存取</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p977954315133"><a name="p977954315133"></a><a name="p977954315133"></a>支持NPU Tensor直接序列化存取,完善torch.save/load接口能力</p>
</td>
</tr>
<tr id="row13545374516"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p44561110214"><a name="p44561110214"></a><a name="p44561110214"></a>精度对比工具</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p412459182110"><a name="p412459182110"></a><a name="p412459182110"></a>支持溢出检测,优化数据dump性能</p>
</td>
</tr>
<tr id="row3722227133312"><td class="cellrowborder" rowspan="3" valign="top" width="25.590000000000003%" headers="mcps1.2.4.1.1 "><p id="p107221327153315"><a name="p107221327153315"></a><a name="p107221327153315"></a>适配NPU的PyTorch1.11.0特性</p>
</td>
<td class="cellrowborder" valign="top" width="15.52%" headers="mcps1.2.4.1.2 "><p id="p153563917719"><a name="p153563917719"></a><a name="p153563917719"></a>框架基础功能</p>
</td>
<td class="cellrowborder" valign="top" width="58.89%" headers="mcps1.2.4.1.3 "><p id="p272242719336"><a name="p272242719336"></a><a name="p272242719336"></a>支持NPU Tensor类型,修复少量BUG</p>
</td>
</tr>
<tr id="row6631141014305"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1416445591310"><a name="p1416445591310"></a><a name="p1416445591310"></a>序列化存取</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p11164185561312"><a name="p11164185561312"></a><a name="p11164185561312"></a>支持NPU Tensor直接序列化存取,完善torch.save/load接口能力</p>
</td>
</tr>
<tr id="row270811563411"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p121645556134"><a name="p121645556134"></a><a name="p121645556134"></a>精度对比工具</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1716425591313"><a name="p1716425591313"></a><a name="p1716425591313"></a>支持溢出检测,优化数据dump性能</p>
</td>
</tr>
</tbody>
</table>
<h3 id="特性修改md">特性修改</h3>
不涉及
<h3 id="已修复问题md">已修复问题</h3>
不涉及
<h3 id="已知问题md">已知问题</h3>
<a name="table1969972073016"></a>
<table><thead align="left"><tr id="row3699162017307"><th class="cellrowborder" valign="top" width="18.22%" id="mcps1.1.3.1.1"><p id="p16992020153010"><a name="p16992020153010"></a><a name="p16992020153010"></a>已知问题</p>
</th>
<th class="cellrowborder" valign="top" width="81.78%" id="mcps1.1.3.1.2"><p id="p269919203308"><a name="p269919203308"></a><a name="p269919203308"></a>问题描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row9699142003011"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1769932017300"><a name="p1769932017300"></a><a name="p1769932017300"></a>数据类型支持</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p13699152010301"><a name="p13699152010301"></a><a name="p13699152010301"></a>NPU不支持float16类型的inf/nan数据输入输出。</p>
</td>
</tr>
<tr id="row146991520153016"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p156997200308"><a name="p156997200308"></a><a name="p156997200308"></a>数据Format</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p10699182020308"><a name="p10699182020308"></a><a name="p10699182020308"></a>出现4D以上的format时不能降维。</p>
</td>
</tr>
<tr id="row11121205610549"><td class="cellrowborder" rowspan="3" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p1647216219558"><a name="p1647216219558"></a><a name="p1647216219558"></a>集合通信约束</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p3116115695415"><a name="p3116115695415"></a><a name="p3116115695415"></a>要求一次训练任务中不同device上执行的图相同。</p>
</td>
</tr>
<tr id="row51211656105411"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p1311616560541"><a name="p1311616560541"></a><a name="p1311616560541"></a>当前只支持1/2/4/8P粒度的分配。</p>
</td>
</tr>
<tr id="row8647195765419"><td class="cellrowborder" valign="top" headers="mcps1.1.3.1.1 "><p id="p2064225716544"><a name="p2064225716544"></a><a name="p2064225716544"></a>只支持int8,int32,float16和float32数据类型。</p>
</td>
</tr>
<tr id="row4646195719548"><td class="cellrowborder" valign="top" width="18.22%" headers="mcps1.1.3.1.1 "><p id="p4642195718541"><a name="p4642195718541"></a><a name="p4642195718541"></a>Apex功能支持</p>
</td>
<td class="cellrowborder" valign="top" width="81.78%" headers="mcps1.1.3.1.2 "><p id="p864205725412"><a name="p864205725412"></a><a name="p864205725412"></a>Apex当前版本的实现方式主要为python实现,不支持APEX中的自定义优化CUDA Kernel。</p>
</td>
</tr>
</tbody>
</table>
<h3 id="兼容性md">兼容性</h3>
A800-9010:CentOS 7.6/Ubuntu 18.04, 2.04/BC-Linux 7.6/Debian 9.9/Debian 10/OpenEuler 20.03 LTS
A800-9000:CentOS 7.6/Ubuntu 18.04, 2.04/Euler 2.8, 2.10/Kylin v10/BC-Linux 7.6/OpenEuler 20.03 LTS/UOS 20 1020e
<h2 id="FrameworkPTAdapter-3-0-RC3md">FrameworkPTAdapter 3.0.RC3</h2>
<h3 id="用户须知md">用户须知</h3>
@@ -0,0 +1,136 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor
import torch_npu
JIT_COMPILE_EXTENSION = True
if JIT_COMPILE_EXTENSION:
from torch_npu.utils.cpp_extension import load
relu_bisheng = load(name="relu_bisheng", sources=["./relu_bisheng.cpp"], verbose=1)
else:
# need run before: python setup.py install
import relu_bisheng
DEVICE = "npu"
class ReLUBiShengFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input1):
ctx.save_for_backward(input1)
output = relu_bisheng.forward(input1)
return output
@staticmethod
def backward(ctx, grad_output):
output, *_ = ctx.saved_tensors
grad_input = relu_bisheng.backward(grad_output, output)
return grad_input
class BiShengReLU(torch.nn.Module):
def forward(self, x):
return ReLUBiShengFunction.apply(x)
class NeuralNetwork(nn.Module):
def __init__(self):
super().__init__()
self.flatten = nn.Flatten()
self.linear_relu_stack = nn.Sequential(
nn.Linear(28*28, 512),
BiShengReLU(),
nn.Linear(512, 512),
BiShengReLU(),
nn.Linear(512, 10))
def forward(self, x):
x = self.flatten(x)
logits = self.linear_relu_stack(x)
return logits
def train_nn(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset)
model.train()
for batch, (x, y) in enumerate(dataloader):
x, y = x.to(DEVICE), y.to(DEVICE)
pred = model(x)
loss = loss_fn(pred, y)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if batch % 100 == 0:
loss, current = loss.item(), batch * len(x)
print(f"loss: {loss:>7f} [{current:>5d}/{size:>5d}]")
def test_nn(dataloader, model, loss_fn):
size = len(dataloader.dataset)
num_batches = len(dataloader)
model.eval()
test_loss, correct = 0, 0
with torch.no_grad():
for x, y in dataloader:
x, y = x.to(DEVICE), y.to(DEVICE)
pred = model(x)
test_loss += loss_fn(pred, y).item()
correct += (pred.argmax(1) == y).type(torch.float).sum().item()
test_loss /= num_batches
correct /= size
print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")
def main():
torch.manual_seed(0)
training_data = datasets.FashionMNIST(
root="./data",
train=True,
download=True,
transform=ToTensor())
test_data = datasets.FashionMNIST(
root="./data",
train=False,
download=True,
transform=ToTensor())
nn_model = NeuralNetwork().to(DEVICE)
print(nn_model)
nn_loss_fn = nn.CrossEntropyLoss()
nn_optimizer = torch.optim.SGD(nn_model.parameters(), lr=1e-3)
batch_size = 64
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)
epochs = 5
for t in range(epochs):
print(f"Epoch {t+1}\n-------------------------------")
train_nn(train_dataloader, nn_model, nn_loss_fn, nn_optimizer)
test_nn(test_dataloader, nn_model, nn_loss_fn)
print("Done!")
if __name__ == "__main__":
main()
+190
View File
@@ -0,0 +1,190 @@
// Copyright (c) 2023 Huawei Technologies Co., Ltd
// All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <acl/acl.h>
#include <sycl/sycl.hpp>
#include <torch/extension.h>
#include <torch/script.h>
#include <torch_npu/csrc/aten/NPUNativeFunctions.h>
#include <torch_npu/csrc/core/npu/NPUStream.h>
using namespace at;
using namespace sycl;
using namespace sycl::access;
template <typename T>
using LocalAccessor = accessor<T, 1, mode::read_write, target::local>;
const size_t UB_BUF_SIZE = 256 * 1024;
template <typename T, int group_count, typename kernel_name>
void relu_forward_kernel(queue &sycl_queue, const T *in, T *out, size_t length) {
const size_t num_accessor = 2;
const size_t ub_load = UB_BUF_SIZE / (sizeof(T) * num_accessor);
const size_t times = length / ub_load;
size_t inner_length;
for (size_t n = 0; n <= times; ++n) {
if (length >= ub_load) {
inner_length = ub_load;
length -= ub_load;
} else {
inner_length = length;
}
sycl_queue.submit([&](handler &cgh) {
LocalAccessor<T> local_in(inner_length, cgh);
LocalAccessor<T> local_out(inner_length, cgh);
cgh.parallel_for_work_group<kernel_name>(
sycl::range<1>{group_count}, [=](group<1> grp) {
const auto gid = grp.get_id(0);
const auto idx_base = gid * inner_length;
[[loop::parallel]] for (size_t i = 0; i < inner_length; ++i) {
local_in[i] = in[i + idx_base + n * ub_load];
local_out[i] = local_in[i] < 0 ? (T)0 : local_in[i];
out[i + idx_base + n * ub_load] = local_out[i];
}
});
});
sycl_queue.wait();
}
}
template <class T, class kernel_name>
torch::Tensor relu_forward_launch(torch::Tensor self) {
Tensor result = at::empty(self.sizes(), self.options());
const T *self_ptr = static_cast<T *>(self.storage().data_ptr().get());
T *result_ptr = static_cast<T *>(result.storage().data_ptr().get());
aclrtContext acl_context;
aclrtGetCurrentContext(&acl_context);
sycl::context sycl_context = sycl::make_context<sycl::backend::cce>(acl_context);
int device_id = 0;
aclrtGetDevice(&device_id);
auto npu_stream = c10_npu::getCurrentNPUStream(device_id);
auto acl_stream = npu_stream.stream();
queue sycl_queue = sycl::make_queue<sycl::backend::cce>(acl_stream, sycl_context);
const T *input1 = self_ptr;
constexpr size_t group_count = 1;
size_t len = result.numel() / group_count;
relu_forward_kernel<T, group_count, kernel_name>(sycl_queue, input1, result_ptr, len);
return result;
}
torch::Tensor relu_forward(torch::Tensor self) {
at::Tensor fortmat_self = at_npu::native::NPUNativeFunctions::npu_format_cast(self, ACL_FORMAT_ND);
const at::Tensor self_dtype = fortmat_self.scalar_type() == at::kDouble
? at_npu::native::NPUNativeFunctions::npu_dtype_cast(fortmat_self, at::kFloat) : fortmat_self;
if (!at_npu::native::NPUNativeFunctions::check_match(self_dtype)) {
at::Tensor contiguous_self =
at_npu::native::NPUNativeFunctions::format_contiguous(self_dtype);
self_dtype.copy_(contiguous_self);
}
torch::Tensor ret_tensor;
if (self_dtype.scalar_type() == at::kHalf) {
ret_tensor = relu_forward_launch<half, class relu_forward_launch_half>(self_dtype);
} else if (self_dtype.scalar_type() == at::kFloat) {
ret_tensor = relu_forward_launch<float, class relu_forward_launch_float>(self_dtype);
} else {
ret_tensor = relu_forward_launch<int, class relu_forward_launch_int>(self_dtype);
}
if (self.scalar_type() == at::kDouble) {
ret_tensor = at_npu::native::NPUNativeFunctions::npu_dtype_cast(ret_tensor, at::kDouble);
}
return ret_tensor;
}
template <typename T, int group_count, typename kernel_name>
void relu_backward_kernel(queue &sycl_queue, const T *in, const T *grad_output, T *out, size_t length) {
const size_t num_accessor = 4;
const size_t ub_load = UB_BUF_SIZE / (sizeof(T) * num_accessor); //ub最大256K
const size_t times = length / ub_load;
size_t inner_length;
for (size_t n = 0; n <= times; ++n) {
if (length >= ub_load) {
inner_length = ub_load;
length -= ub_load;
} else {
inner_length = length;
}
sycl_queue.submit([&](handler &cgh) {
LocalAccessor<T> local_in1(inner_length, cgh);
LocalAccessor<T> local_in2(inner_length, cgh);
LocalAccessor<T> local_out(inner_length, cgh);
cgh.parallel_for_work_group<kernel_name>(
sycl::range<1>{group_count}, [=](group<1> grp) {
const auto gid = grp.get_id(0);
const auto idx_base = gid * inner_length;
[[loop::parallel]] for (size_t i = 0; i < inner_length; ++i) {
local_in1[i] = grad_output[i + idx_base + n * ub_load];
local_in2[i] = in[i + idx_base + n * ub_load] <= 0 ? 0 : 1;
local_out[i] = local_in1[i] * local_in2[i];
out[i + idx_base + n * ub_load] = local_out[i];
}
});
});
sycl_queue.wait();
}
}
template <class T, class kernel_name>
torch::Tensor relu_backward_launch(torch::Tensor grad, torch::Tensor self) {
Tensor result = at::empty(self.sizes(), self.options());
const T *self_ptr = static_cast<T *>(self.storage().data_ptr().get());
const T *grad_ptr = static_cast<T *>(grad.storage().data_ptr().get());
T *result_ptr = static_cast<T *>(result.storage().data_ptr().get());
aclrtContext acl_context;
aclrtGetCurrentContext(&acl_context);
sycl::context sycl_context = sycl::make_context<sycl::backend::cce>(acl_context);
int device_id = 0;
aclrtGetDevice(&device_id);
auto npu_stream = c10_npu::getCurrentNPUStream(device_id);
auto acl_stream = npu_stream.stream();
queue sycl_queue = sycl::make_queue<sycl::backend::cce>(acl_stream, sycl_context);
const T *input1 = self_ptr;
const T *grad_output = grad_ptr;
constexpr size_t group_count = 1;
size_t len = result.numel() / group_count;
relu_backward_kernel<T, group_count, kernel_name>(sycl_queue, input1, grad_output, result_ptr, len);
return result;
}
torch::Tensor relu_backward(torch::Tensor grad, torch::Tensor self) {
at::TensorList inputs = {grad, self};
at::TensorList outputs;
at_npu::native::NPUNativeFunctions::check_memory_overlaps(inputs, outputs);
if (!at_npu::native::NPUNativeFunctions::check_match(self)) {
at::Tensor contiguous_self = at_npu::native::NPUNativeFunctions::format_contiguous(self);
self.copy_(contiguous_self);
}
if (self.scalar_type() == at::kHalf) {
return relu_backward_launch<half, class relu_backward_launch_half>(grad, self);
} else if (self.scalar_type() == at::kFloat) {
return relu_backward_launch<float, class relu_backward_launch_float>(grad, self);
} else {
return relu_backward_launch<int, class relu_backward_launch_int>(grad, self);
}
}
PYBIND11_MODULE(relu_bisheng, m) {
m.def("forward", &relu_forward, "relu forward");
m.def("backward", &relu_backward, "relu backward");
}
@@ -1,6 +1,4 @@
#!/bin/bash
# Copyright (c) 2021, Huawei Technologies Co., Ltd
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
@@ -15,11 +13,19 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension
OFFICIAL_PYTORCH=$1
PATCH_PYTORCH=$2
OUT_PATCH_FILE=$3
from torch_npu.utils.cpp_extension import BiShengExtension
diff -Nur --exclude=.git* --exclude=OWNERS \
--exclude=access_control_test.py --exclude=third_party \
--exclude=README* -Nur ${OFFICIAL_PYTORCH} ${PATCH_PYTORCH} > ${OUT_PATCH_FILE}
setup(
name='relu_bisheng',
ext_modules=[
BiShengExtension(
name='relu_bisheng',
sources=['relu_bisheng.cpp']),
],
cmdclass={
'build_ext': BuildExtension
})
+138
View File
@@ -0,0 +1,138 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import os
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
JIT_COMPILE_EXTENSION = True
if JIT_COMPILE_EXTENSION:
from torch_npu.utils.cpp_extension import load
relu_bisheng = load(name="relu_bisheng", sources=["./relu_bisheng.cpp"], verbose=True)
else:
# need run before: python setup.py install
import relu_bisheng
torch.manual_seed(0)
class ReLUBiShengFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, input1):
ctx.save_for_backward(input1)
output = relu_bisheng.forward(input1)
return output
@staticmethod
def backward(ctx, grad_output):
output, *_ = ctx.saved_tensors
grad_input = relu_bisheng.backward(grad_output, output)
return grad_input
class BiShengReLU(torch.nn.Module):
def forward(self, x):
return ReLUBiShengFunction.apply(x)
class TestRelu(TestCase):
def cpu_op_back_exec(self, input1):
w = torch.ones_like(input1)
input1.requires_grad_(True)
output = torch.relu(input1)
output.backward(w)
res = input1.grad
res = res.numpy()
return output.detach().numpy(), res
def npu_op_back_exec(self, input1):
w = torch.ones_like(input1)
input1.requires_grad_(True)
output = BiShengReLU()(input1)
output.backward(w)
output = output.to("cpu")
res = input1.grad.to("cpu")
res = res.numpy()
return output.detach().numpy(), res
def cpu_inp_op_exec(self, input1):
output = torch.relu_(input1)
output = output.numpy()
return output
def npu_inp_op_exec(self, input1):
output = torch.relu_(input1)
output = output.to("cpu")
output = output.numpy()
return output
def test_relu_shape_format_fp32(self, device='npu'):
format_list = [-1]
shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)]
shape_format = [
[np.float32, i, j] for i in format_list for j in shape_list
]
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item, -100, 100)
if cpu_input1.dtype == torch.float16:
cpu_input1 = cpu_input1.to(torch.float32)
cpu_output, cpu_res = self.cpu_op_back_exec(cpu_input1)
npu_output, npu_res = self.npu_op_back_exec(npu_input1)
cpu_output = cpu_output.astype(npu_output.dtype)
cpu_res = cpu_res.astype(npu_res.dtype)
self.assertRtolEqual(cpu_output, npu_output)
self.assertRtolEqual(cpu_res, npu_res)
def test_relu_shape_format_fp16(self, device='npu'):
format_list = [-1]
shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)]
shape_format = [
[np.float16, i, j] for i in format_list for j in shape_list
]
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item, -100, 100)
if cpu_input1.dtype == torch.float16:
cpu_input1 = cpu_input1.to(torch.float32)
cpu_output, cpu_res = self.cpu_op_back_exec(cpu_input1)
npu_output, npu_res = self.npu_op_back_exec(npu_input1)
cpu_output = cpu_output.astype(npu_output.dtype)
cpu_res = cpu_res.astype(npu_res.dtype)
self.assertRtolEqual(cpu_output, npu_output)
self.assertRtolEqual(cpu_res, npu_res)
def test_relu_shape_format_fp16_inp(self, device='npu'):
format_list = [-1]
shape_list = [(1000, 1280), (32, 3, 3), (1024, 464, 7, 7)]
shape_format = [
[np.float16, i, j] for i in format_list for j in shape_list
]
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item, -100, 100)
if cpu_input1.dtype == torch.float16:
cpu_input1 = cpu_input1.to(torch.float32)
cpu_output = self.cpu_inp_op_exec(cpu_input1)
npu_output = self.npu_inp_op_exec(npu_input1)
cpu_output = cpu_output.astype(npu_output.dtype)
self.assertRtolEqual(cpu_output, npu_output)
if __name__ == "__main__":
run_tests()
+35
View File
@@ -0,0 +1,35 @@
#!/bin/bash
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
CDIR="$(cd "$(dirname "$0")" ; pwd -P)"
cd $CDIR
build_libtorch="$1"
python3 -m codegen.gen_backend_stubs \
--output_dir="$CDIR/torch_npu/csrc/aten/" \
--source_yaml="$CDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \
--impl_path="$CDIR/torch_npu/csrc/aten" # Used to double-check the yaml file definitions.
if [[ ${build_libtorch} != "True" ]]; then
python3 -m codegen.gen_python_functions \
--output_dir="$CDIR/torch_npu/csrc/aten/" \
--source_yaml="$CDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \
--native_yaml="$CDIR/codegen/native_functions.yaml" \
--template_path="$CDIR/codegen/templates"
fi
-177
View File
@@ -1,177 +0,0 @@
#pragma once
#include <c10/core/Allocator.h>
#include <c10/core/ScalarType.h>
#include <c10/util/intrusive_ptr.h>
namespace c10 {
struct C10_API StorageImpl : public c10::intrusive_ptr_target {
public:
struct use_byte_size_t {};
StorageImpl(
use_byte_size_t use_byte_size,
size_t size_bytes,
at::DataPtr data_ptr,
at::Allocator* allocator,
bool resizable)
: data_ptr_(std::move(data_ptr)),
size_bytes_(size_bytes),
resizable_(resizable),
received_cuda_(false),
allocator_(allocator) {
if (resizable) {
TORCH_INTERNAL_ASSERT(
allocator_, "For resizable storage, allocator must be provided");
}
}
StorageImpl(
use_byte_size_t use_byte_size,
size_t size_bytes,
at::Allocator* allocator,
bool resizable)
: StorageImpl(
use_byte_size_t(),
size_bytes,
allocator->allocate(size_bytes),
allocator,
resizable) {}
StorageImpl& operator=(StorageImpl&& other) = default;
StorageImpl& operator=(const StorageImpl&) = delete;
StorageImpl() = delete;
StorageImpl(StorageImpl&& other) = default;
StorageImpl(const StorageImpl&) = delete;
~StorageImpl() = default;
void reset() {
data_ptr_.clear();
size_bytes_ = 0;
}
template <typename T>
inline T* data() const {
return unsafe_data<T>();
}
template <typename T>
inline T* unsafe_data() const {
return static_cast<T*>(this->data_ptr_.get());
}
void release_resources() override {
data_ptr_.clear();
}
size_t nbytes() const {
return size_bytes_;
}
void set_nbytes(size_t size_bytes) {
size_bytes_ = size_bytes;
}
bool resizable() const {
return resizable_;
};
at::DataPtr& data_ptr() {
return data_ptr_;
};
const at::DataPtr& data_ptr() const {
return data_ptr_;
};
// Returns the previous data_ptr
at::DataPtr set_data_ptr(at::DataPtr&& data_ptr) {
std::swap(data_ptr_, data_ptr);
return std::move(data_ptr);
};
void* data() {
return data_ptr_.get();
}
void* data() const {
return data_ptr_.get();
}
at::DeviceType device_type() const {
return data_ptr_.device().type();
}
at::Allocator* allocator() {
return allocator_;
}
const at::Allocator* allocator() const {
return allocator_;
};
// You generally shouldn't use this method, but it is occasionally
// useful if you want to override how a tensor will be reallocated,
// after it was already allocated (and its initial allocator was
// set)
void set_allocator(at::Allocator* allocator) {
allocator_ = allocator;
}
Device device() const {
return data_ptr_.device();
}
void set_resizable(bool resizable) {
if (resizable) {
// We need an allocator to be resizable
AT_ASSERT(allocator_);
}
resizable_ = resizable;
}
/**
* Can only be called when use_count is 1
*/
void UniqueStorageShareExternalPointer(
void* src,
size_t size_bytes,
DeleterFnPtr d = nullptr) {
UniqueStorageShareExternalPointer(
at::DataPtr(src, src, d, data_ptr_.device()), size_bytes);
}
/**
* Can only be called when use_count is 1
*/
void UniqueStorageShareExternalPointer(
at::DataPtr&& data_ptr,
size_t size_bytes) {
data_ptr_ = std::move(data_ptr);
size_bytes_ = size_bytes;
allocator_ = nullptr;
resizable_ = false;
}
// This method can be used only after storage construction and cannot be used
// to modify storage status
void set_received_cuda(bool received_cuda) {
received_cuda_ = received_cuda;
}
bool received_cuda() {
return received_cuda_;
}
private:
DataPtr data_ptr_;
size_t size_bytes_;
bool resizable_;
// Identifies that Storage was received from another process and doesn't have
// local to process cuda memory allocation
bool received_cuda_;
Allocator* allocator_;
};
} // namespace c10
-125
View File
@@ -1,125 +0,0 @@
#pragma once
#include <ATen/ATen.h>
#include <ATen/core/ivalue.h>
#include <c10d/ProcessGroup.hpp>
namespace c10d {
// Broadcast many tensors to all processes in the process group.
void broadcast_coalesced(
c10::intrusive_ptr<c10d::ProcessGroup> process_group,
at::TensorList tensors,
size_t buffer_size,
int rank = 0);
// This class passes bucket contents tensor (for multiple replicas) to
// DDP communication hook.
// Optionally in the future this can be enhanced with parameter to bucket
// mappings as well.
class GradBucket {
public:
explicit GradBucket(
size_t index,
const std::vector<at::Tensor>& tensors,
const std::vector<size_t>& offsets = {},
const std::vector<size_t>& lengths = {},
const std::vector<c10::IntArrayRef>& sizes_vec = {})
: index_(index),
tensors_(tensors),
offsets_(offsets),
lengths_(lengths),
sizes_vec_(sizes_vec) {}
// Returns the index of the bucket, which is unique across all the buckets.
size_t getIndex() const {
return index_;
}
// Each tensor in the list that getTensors returns refers to the replica on
// each device. There will be multiple replicas only in the case of single
// process multiple device mode. In the single process single device mode,
// this list would consist of only a single tensor.
const std::vector<at::Tensor>& getTensors() const {
return tensors_;
}
// Returns a mutable tensor vector compared with the above method.
std::vector<at::Tensor>& getTensorsRef() {
return tensors_;
}
// Returns the start index of each variable in tensors_[0].
const std::vector<size_t>& getOffsets() const {
return offsets_;
}
// Returns the total (i.e., flattened) length of each variable in
// tensors_[0].
const std::vector<size_t>& getLengths() const {
return lengths_;
}
// Returns the multi-dimensional sizes/shape of each variable in tensors_[0].
const std::vector<c10::IntArrayRef>& getSizesVec() const {
return sizes_vec_;
}
private:
size_t index_;
std::vector<at::Tensor> tensors_;
// Per-variable info in tensors_[0].
std::vector<size_t> offsets_;
std::vector<size_t> lengths_;
std::vector<c10::IntArrayRef> sizes_vec_;
};
// Base class of both `PythonCommHook` and `CppCommHook`.
// Requires implementing 1) `runHook` method that communicates gradients
// asynchronously, and 2) `parseHookResult` method that converts the hook
// result into a tensor vector.
class TORCH_PYTHON_API CommHookInterface {
public:
virtual ~CommHookInterface() {}
// Passes the input grad bucket to the registered communication hook.
// Once the tensors in the bucket are ready, kicks off the hook asynchronously
// and returns a future that holds the communication results.
virtual c10::intrusive_ptr<c10::ivalue::Future> runHook(
GradBucket& bucket) = 0;
// Returns the resulting tensors once the communication hook result is
// ready. The resulting tensors will then be copied to the grads of
// individual parameters.
virtual std::vector<at::Tensor> parseHookResult(
const c10::IValue& result) = 0;
};
// This CppCommHook interface only requires implementing runHook method that
// potentially uses a state.
// Still need TORCH_PYTHON_API instead of TORCH_API to support Windows platform.
template <typename T>
class TORCH_PYTHON_API CppCommHookInterface : public CommHookInterface {
public:
explicit CppCommHookInterface(T& state) : state_(state) {}
virtual ~CppCommHookInterface() {}
std::vector<at::Tensor> parseHookResult(const c10::IValue& result) override {
TORCH_INTERNAL_ASSERT(
result.isTensor() || result.isTensorList(),
"expected the hook result is either a Tensor or a TensorList");
if (result.isTensor()) {
return {result.toTensor()};
}
return result.toTensorVector();
}
protected:
T state_; // Not owned.
};
} // namespace c10d
-33
View File
@@ -1,33 +0,0 @@
#pragma once
#include <c10d/comm.hpp>
#include <c10d/ProcessGroup.hpp>
namespace c10d {
enum class BuiltinCommHookType {
ALLREDUCE = 1,
FP16_COMPRESS = 2,
};
class AllReduceCommHook : public CppCommHookInterface<ProcessGroup*> {
public:
explicit AllReduceCommHook(ProcessGroup* state)
: CppCommHookInterface<ProcessGroup*>(state) {}
~AllReduceCommHook() override {}
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
class FP16CompressCommHook : public CppCommHookInterface<ProcessGroup*> {
public:
explicit FP16CompressCommHook(ProcessGroup* state)
: CppCommHookInterface<ProcessGroup*>(state) {}
~FP16CompressCommHook() override {}
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
} // namespace c10d
-261
View File
@@ -1,261 +0,0 @@
#pragma once
#include <ATen/ATen.h>
#include <c10/util/Optional.h>
#include <c10d/ProcessGroup.hpp>
#include <c10d/Store.hpp>
#include <chrono>
#include <memory>
#include <string>
#include <unordered_map>
namespace c10d {
#ifdef USE_C10D_GLOO
constexpr char* GLOO_SOCKET_IFNAME_ENV = "GLOO_SOCKET_IFNAME";
#endif
inline std::vector<std::string> split(
char separator,
const std::string& string) {
std::vector<std::string> pieces;
std::stringstream ss(string);
std::string item;
while (std::getline(ss, item, separator)) {
pieces.push_back(std::move(item));
}
return pieces;
}
class Backend {
public:
// Maps to Backend.__new__ in Python.
static std::string get(const std::string&);
// TODO: How to support registering third_party backend?
static void registerBackend();
private:
// TODO: Should this be an enum list instead since this set doesn't
// change at all.
std::unordered_set<std::string> registered_backends_;
};
class TORCH_PYTHON_API DistributedC10d : public torch::CustomClassHolder {
public:
static c10::intrusive_ptr<DistributedC10d> get();
DistributedC10d() = default;
void initProcessGroup(
const std::string& backend,
const std::string& init_method,
const std::chrono::milliseconds& timeout,
int64_t world_size,
int64_t rank,
c10::intrusive_ptr<Store> store,
const std::string& group_name);
void destroyProcessGroup(c10::intrusive_ptr<ProcessGroup> group);
int64_t getRank(const c10::intrusive_ptr<ProcessGroup>& group) const;
int64_t getWorldSize(const c10::intrusive_ptr<ProcessGroup>& group) const;
c10::intrusive_ptr<ProcessGroup::Work> isend(
at::Tensor tensor,
int64_t dst,
const c10::intrusive_ptr<ProcessGroup>& group,
c10::optional<int64_t>& tag);
c10::intrusive_ptr<ProcessGroup::Work> irecv(
at::Tensor tensor,
int64_t src,
const c10::intrusive_ptr<ProcessGroup>& group,
c10::optional<int64_t>& tag);
void send(
at::Tensor tensor,
int64_t dst,
const c10::intrusive_ptr<ProcessGroup>& group,
c10::optional<int64_t>& tag);
int64_t recv(
at::Tensor tensor,
const c10::optional<int64_t>& src,
const c10::intrusive_ptr<ProcessGroup>& group,
c10::optional<int64_t>& tag);
c10::intrusive_ptr<ProcessGroup::Work> broadcastMultiGPU(
std::vector<at::Tensor>& tensor_list,
int64_t src,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false,
int64_t src_tensor = 0);
c10::intrusive_ptr<ProcessGroup::Work> broadcast(
at::Tensor tensor,
int64_t src,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allReduceMultiGPU(
std::vector<at::Tensor>& tensor_list,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allReduce(
at::Tensor tensor,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allReduceCoalesced(
std::vector<at::Tensor>& tensors,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> reduceMultiGPU(
std::vector<at::Tensor>& tensor_list,
int64_t dst,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false,
int64_t dst_tensor = 0);
c10::intrusive_ptr<ProcessGroup::Work> reduce(
at::Tensor tensor,
int64_t dst,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allGatherMultiGPU(
std::vector<std::vector<at::Tensor>>& output_tensor_lists,
std::vector<at::Tensor>& input_tensor_list,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allGather(
std::vector<at::Tensor>& tensor_list,
at::Tensor tensor,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allGatherCoalesced(
std::vector<std::vector<at::Tensor>>& output_tensor_lists,
std::vector<at::Tensor>& input_tensor_list,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> gather(
at::Tensor tensor,
const c10::optional<std::vector<at::Tensor>>& gather_list,
const c10::intrusive_ptr<ProcessGroup>& group,
int64_t dst = 0,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> scatter(
at::Tensor tensor,
std::vector<at::Tensor>& scatter_list,
const c10::intrusive_ptr<ProcessGroup>& group,
int64_t src = 0,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> reduceScatterMultiGPU(
std::vector<at::Tensor>& output_tensor_list,
std::vector<std::vector<at::Tensor>>& input_tensor_lists,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> reduceScatter(
at::Tensor output,
std::vector<at::Tensor>& input_tensor_list,
const c10::intrusive_ptr<ProcessGroup>& group,
ReduceOp op = ReduceOp::SUM,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allToAllSingle(
at::Tensor output,
at::Tensor input,
std::vector<int64_t>& output_split_sizes,
std::vector<int64_t>& input_split_sizes,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> allToAll(
std::vector<at::Tensor>& output_tensor_list,
std::vector<at::Tensor>& input_tensor_list,
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup::Work> barrier(
const c10::intrusive_ptr<ProcessGroup>& group,
bool async_op = false);
c10::intrusive_ptr<ProcessGroup> newGroup(
std::vector<int64_t> ranks,
std::chrono::milliseconds timeout,
Backend backend);
c10::intrusive_ptr<ProcessGroup> worldProcessGroup();
c10::intrusive_ptr<ProcessGroup> newProcessGroupHelper(
const int64_t world_size,
const int64_t rank,
const std::vector<int64_t>& group_ranks,
const std::string& backend_str,
const c10::intrusive_ptr<Store>& store,
c10::optional<std::string> group_name,
int64_t timeout_milisesonds);
c10::intrusive_ptr<ProcessGroup> getProcessGroupByName(
const std::string& name) const;
std::string getNameOfProcessGroup(
const c10::intrusive_ptr<ProcessGroup>& pg) const;
void registerProcessGroupName(const c10::intrusive_ptr<ProcessGroup>& process_group, const std::string& name);
private:
bool rankNotInGroup(const c10::intrusive_ptr<ProcessGroup>& group) const;
int64_t getGroupRank(
const c10::intrusive_ptr<ProcessGroup>& group,
const int64_t rank) const;
int64_t getGlobalRank(
const c10::intrusive_ptr<ProcessGroup>& group,
const int64_t group_rank) const;
void checkDefaultPg() const;
int64_t getGroupSize(const c10::intrusive_ptr<ProcessGroup>& group) const;
std::string getBackend(const c10::intrusive_ptr<ProcessGroup>& group);
std::string backend_;
// TODO: Ask Alex what kind of equality we need. It determine whether we
// need to use ProcessGroup or ProcesGroup* as key.
std::unordered_map<
c10::intrusive_ptr<ProcessGroup>,
std::pair<std::string, c10::intrusive_ptr<Store>>>
pg_map_;
// Note, this is different mapping relationship than original Python
// implementation.
std::unordered_map<c10::intrusive_ptr<ProcessGroup>, std::string> pg_names_;
// Process group's global rank to local rank mapping
std::unordered_map<
c10::intrusive_ptr<ProcessGroup>,
std::unordered_map<int64_t, int64_t>>
pg_group_ranks_;
c10::intrusive_ptr<ProcessGroup> default_pg_;
// Default value should be "env://"
std::string default_pg_init_method_;
int64_t group_count_;
};
} // namespace c10d
@@ -1,6 +1,5 @@
#pragma once
#include <torch/csrc/WindowsTorchApiMacro.h>
#include <cstdint>
namespace torch {
@@ -0,0 +1,140 @@
#pragma once
#include <ATen/ATen.h>
#include <ATen/core/ivalue.h>
#include <c10d/ProcessGroup.hpp>
#include <torch/csrc/Export.h>
namespace c10d {
// Broadcast many tensors to all processes in the process group.
TORCH_API void broadcast_coalesced(
c10::intrusive_ptr<c10d::ProcessGroup> process_group,
at::TensorList tensors,
size_t buffer_size,
int rank = 0);
// This class passes bucket contents tensor to DDP communication hook.
class TORCH_API GradBucket {
public:
explicit GradBucket(
size_t index,
size_t bucket_count,
const at::Tensor& tensor,
const std::vector<size_t>& offsets,
const std::vector<size_t>& lengths,
const std::vector<c10::IntArrayRef>& sizes_vec,
const std::vector<at::Tensor>& parameters)
: index_(index),
bucket_count_(bucket_count),
buffer_(tensor),
offsets_(offsets),
lengths_(lengths),
sizes_vec_(sizes_vec),
parameters_(parameters) {}
// Returns the index of the bucket, which is unique across all the buckets.
size_t getIndex() const {
return index_;
}
const at::Tensor& getBuffer() const {
return buffer_;
}
// Returns a mutable buffer compared with the above method.
at::Tensor& getBufferRef() {
return buffer_;
}
// Overwrites the buffer at a specific index.
void setBuffer(at::Tensor& buffer) {
buffer_ = buffer;
}
// Each tensor in the list that getGradients corresponds to a
// parameter.
std::vector<at::Tensor> getGradients() const;
// Returns model parameters belonging to this bucket. They are returned in the
// same order as gradient tensors via getGradients(). For example,
// getParameters[i] will have its gradient stored in
// getGradients[i]
const std::vector<at::Tensor> getParameters() const {
return parameters_;
}
// Returns whther this bucket is the last bucket to allreduce in an iteration.
bool isLast() const {
return index_ == bucket_count_ - 1;
}
private:
size_t index_;
size_t bucket_count_;
at::Tensor buffer_;
// Per-variable info in buffer_.
std::vector<size_t> offsets_;
std::vector<size_t> lengths_;
std::vector<c10::IntArrayRef> sizes_vec_;
// Model parameters for this bucket.
const std::vector<at::Tensor> parameters_;
};
// Base class of both `PythonCommHook` and `CppCommHook`.
// Requires implementing 1) `runHook` method that communicates gradients
// asynchronously, and 2) `parseHookResult` method that converts the hook
// result into a tensor.
class TORCH_API CommHookInterface {
public:
virtual ~CommHookInterface() = default;
// Passes the input grad bucket to the registered communication hook.
// Once the tensor in the bucket are ready, kicks off the hook asynchronously
// and returns a future that holds the communication results.
virtual c10::intrusive_ptr<c10::ivalue::Future> runHook(
GradBucket& bucket) = 0;
// Returns the resulting tensor once the communication hook result is
// ready. The resulting tensor will then be copied to the grads of
// individual parameters.
virtual at::Tensor parseHookResult(
const c10::IValue& result) = 0;
};
namespace detail {
// This helper function is called both by CppCommHookInterface below and inside
// reducer.
inline at::Tensor parseCppCommHookResult(
const c10::IValue& result) {
TORCH_INTERNAL_ASSERT(
result.isTensor() || result.isTensorList(),
"expected the hook result is either a Tensor or a TensorList");
if (result.isTensor()) {
return result.toTensor();
}
return result.toTensorVector()[0];
}
} // namespace detail
// This CppCommHook interface only requires implementing runHook method that
// potentially uses a state.
template <typename T>
class CppCommHookInterface : public CommHookInterface {
public:
explicit CppCommHookInterface(T& state) : state_(state) {}
~CppCommHookInterface() override = default;
at::Tensor parseHookResult(const c10::IValue& result) override {
return detail::parseCppCommHookResult(result);
}
protected:
T state_;
};
} // namespace c10d
@@ -0,0 +1,27 @@
// Copyright (c) Meta Platforms, Inc. and its affiliates.
// All rights reserved.
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.
#pragma once
#include <c10/macros/Macros.h>
namespace c10d {
enum class DebugLevel {
Off,
Info,
Detail
};
TORCH_API void setDebugLevel(DebugLevel level);
// Sets the debug level based on the value of the `TORCH_DISTRIBUTED_DEBUG`
// environment variable.
TORCH_API void setDebugLevelFromEnvironment();
TORCH_API DebugLevel debug_level() noexcept;
} // namespace c10d
@@ -0,0 +1,48 @@
#pragma once
#include <c10d/ProcessGroup.hpp>
#include <c10d/comm.hpp>
namespace c10d {
enum class BuiltinCommHookType {
ALLREDUCE = 1,
FP16_COMPRESS = 2,
};
class AllReduceCommHook : public CppCommHookInterface<ProcessGroup*> {
public:
explicit AllReduceCommHook(ProcessGroup* state)
: CppCommHookInterface<ProcessGroup*>(state) {}
~AllReduceCommHook() override = default;
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
class FP16CompressCommHook : public CppCommHookInterface<ProcessGroup*> {
public:
explicit FP16CompressCommHook(ProcessGroup* state)
: CppCommHookInterface<ProcessGroup*>(state) {}
~FP16CompressCommHook() override = default;
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
// Almost same as AllReduceCommHook, but without division inside the hook.
// This enables the optimization of fusing copy and division and saves one scan
// over all the input parameters, when no communication hook is provided by the user.
// Only used internally and not released as a public built-in communication hook.
class _AllReduceBySumCommHook
: public CppCommHookInterface<ProcessGroup*> {
public:
explicit _AllReduceBySumCommHook(ProcessGroup* state)
: CppCommHookInterface<ProcessGroup*>(state) {}
~_AllReduceBySumCommHook() override = default;
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
};
} // namespace c10d
@@ -0,0 +1,110 @@
#include <c10/util/Logging.h>
#include <c10d/reducer.hpp>
#include <mutex>
namespace c10d {
class TORCH_API Logger {
public:
explicit Logger(std::shared_ptr<c10d::Reducer> reducer);
// Set logging data that can be got during DistributedDataParallel
// construction time.
void set_construction_data_and_log(
const std::string& module_name,
const std::vector<int>& device_ids,
int output_device,
bool broadcast_buffers,
bool has_sync_bn);
void set_static_graph();
// An interface for users to get DDPLoggingData and log them
// in the applications. Explanation of logging fields are in
// "struct DDPLoggingData" of "torch/c10/util/Logging.h".
at::DDPLoggingData get_ddp_logging_data();
// Stream insertion operator for logging data to stream under
// TORCH_DISTRIBUTED_DEBUG.
friend std::ostream& operator<<(std::ostream& output, const Logger& logger);
~Logger() noexcept(false) {
// Log if DDP graph is static in Logger dtor instead of Reducer dtor since
// Logger is deleted before Reducer.
log_if_graph_static(reducer_->ddp_graph_static());
}
// Set environment variables.
void set_env_variables();
// Set parameters stats.
void set_parameter_stats();
// Get size of each bucket (Bytes).
std::vector<int> get_bucket_sizes();
// Get bucket size limits specified during DDP construction.
std::vector<int> get_bucket_size_limits();
// Get variable indices for each bucket.
std::vector<std::vector<size_t>> get_per_bucket_variable_indices();
// Set comm. hook, if used
void set_comm_hook(const std::string& hook);
// Set running with uneven input detection (model.join() context manager)
void set_uneven_input_join();
// Reset performance stats at current iteration
void reset_performance_stats();
// Calculate avg stats using cpu timer and gpu timer
// that has been recorded in reducer.
void calculate_avg_time(
int64_t& avg_time,
int64_t& time_duration,
Timer& timer,
Timer::Event start_event,
Timer::Event end_event);
// Set the absolute time of the event that has been recorded in reducer.
void set_event_time(
int64_t& event_time,
Timer& timer,
Timer::Event event
);
// Set stats that can be collected only during
// training loop. It is called at the beginning of forward call
// to record the run time stats of sampled iterations that previouly ran.
// GPU performance stats are collected only for single process
// single device program and single device module right now.
// TODO to support single process multiple devices and multi device modules,
// events need to be created and recorded on multiple devices.
void set_runtime_stats_and_log();
// Called when DDP/reducer is failing with an error. The
// logging data structure will have two fields filled: "has_error" indicating
// that this iteration encountered an error and other fields are not valid,
// and "error", a string which contains the error message that DDP failed
// with.
template <typename... Args>
void set_error_and_log(const std::string& ddp_error, const Args&... args) {
ddp_logging_data_->ints_map["has_error"] = 1;
auto err = c10::str(ddp_error, args...);
ddp_logging_data_->strs_map["error"] = err;
// Report the iteration we are erroring at so user knows how many examples
// successfully processed before this error was hit.
ddp_logging_data_->ints_map["iteration"] = reducer_->num_iterations_;
at::LogPyTorchDDPUsage(*ddp_logging_data_);
}
// When running without static graph, called when reducer is destroyed to log
// if graph was actually static and is a candidate for static graph
// optimization.
void log_if_graph_static(bool is_static);
private:
// ddp_logging_data_ is used to hold all the ddp related logging
// data fields.
std::unique_ptr<at::DDPLoggingData> ddp_logging_data_;
std::shared_ptr<c10d::Reducer> reducer_;
// track the number of iterations when runtime stats are collected so far.
long num_iterations_stats_recorded_ = 0;
};
} // namespace c10d
@@ -23,8 +23,7 @@ class TORCH_PYTHON_API PythonCommHook : public CommHookInterface {
c10::intrusive_ptr<c10::ivalue::Future> runHook(GradBucket& bucket) override;
std::vector<at::Tensor> parseHookResult(const c10::IValue& result) override;
at::Tensor parseHookResult(const c10::IValue& result) override;
private:
// Only needed for stateful communication.
py::object state_;
@@ -1,6 +1,5 @@
#pragma once
#include <torch/csrc/utils/future.h>
#include <torch/types.h>
#include <vector>
@@ -0,0 +1,83 @@
#pragma once
#include <torch/csrc/distributed/rpc/rref_impl.h>
#include <torch/csrc/python_headers.h>
#include <torch/csrc/utils/pybind.h>
namespace torch {
namespace distributed {
namespace rpc {
enum RRefProxyType { RPC_SYNC, RPC_ASYNC, REMOTE };
// Python wrapper of an RRef shared_ptr that supports Python
// pickle and unpickle.
class PYBIND11_EXPORT PyRRef {
public:
// The first ctor can only be called while holding GIL. See its implementation
// for more explanations.
explicit PyRRef(const py::object& value, const py::object& type_hint);
explicit PyRRef(c10::intrusive_ptr<RRef> rref);
~PyRRef();
bool isOwner() const;
bool confirmedByOwner() const;
WorkerInfo owner() const;
std::string ownerName() const;
py::object toHere(
const float timeoutSeconds =
torch::distributed::rpc::kUnsetRpcTimeout) const;
py::object localValue() const;
std::string str() const;
py::tuple pickle() const;
static PyRRef unpickle(const py::tuple& t);
c10::IValue toIValue() const;
// Future that is associated with the creation of this RRef on the remote end.
// This is only used to get the future corresponding to the rref for profiling
// use cases.
c10::intrusive_ptr<JitFuture> getFuture() const;
// Keeps track of the future responsible for profiling owner creation
// acknowledgement
c10::intrusive_ptr<JitFuture> getProfilingFuture() const;
// Sets the future responsible for profiling owner creation acknowledgement.
// This future is set from python to be a future that returns when profiling
// callbacks have been run.
void setProfilingFuture(c10::intrusive_ptr<JitFuture> profilingFuture);
// create a proxy on this RRef, which can be used to launch RPC on the owner
// of this RRef to run functions on the object referenced by this RRef.
py::object createRRefProxy(
const RRefProxyType& mode,
float timeoutSeconds = rpc::kUnsetRpcTimeout) const;
// get the type of the data object referenced by this RRef. Timeout argument
// is only used in the first invocation of this function as an argument to the
// RPC to the owner node of the RRef.
py::object getRRefType(
float timeout = rpc::kUnsetRpcTimeout,
bool blocking = true);
// Run the backward pass with the RRef as the root.
void backward(int64_t autogradContextId, bool retainGraph);
// Helper static function to run backward on a given rref.
static void backward(
int64_t autogradContextId,
bool retainGraph,
const c10::intrusive_ptr<RRef>& rref);
// Specialization of backward if the rref is an OwnerRRef.
static void backwardOwnerRRef(
int64_t autogradContextId,
bool retainGraph,
IValue value);
private:
c10::intrusive_ptr<RRef> rref_;
c10::optional<c10::intrusive_ptr<JitFuture>> profilingFuture_;
c10::optional<py::object> type_;
};
} // namespace rpc
} // namespace distributed
} // namespace torch
@@ -0,0 +1,413 @@
#pragma once
#include <ATen/core/jit_type.h>
#include <ATen/core/rref_interface.h>
#include <c10/core/Event.h>
#include <c10/util/Optional.h>
#include <torch/csrc/distributed/rpc/message.h>
#include <torch/csrc/distributed/rpc/rpc_agent.h>
#include <torch/csrc/distributed/rpc/types.h>
#include <atomic>
namespace torch {
namespace distributed {
namespace rpc {
class RRef;
class RRefContext;
class UserRRef;
constexpr int OWNER_IDX = 0; // index of ownerId in the tuple
constexpr int RREFID_ON_IDX = 1; // index of RRefId.createdOn_ in the tuple
constexpr int RREFID_ID_IDX = 2; // index of RRefId.localId_ in the tuple
constexpr int FORKID_ON_IDX = 3; // index of ForkId.createdOn_ in the tuple
constexpr int FORKID_ID_IDX = 4; // index of ForkId.localId_ in the tuple
constexpr int PARENT_IDX = 5; // index of parent in the tuple
constexpr int TYPE_IDX = 6; // index of parent in the tuple
// NB: if more fields are added, make sure this field is also bumped
constexpr int RFD_TUPLE_SIZE = 7; // number of RRefForkData fields in py::tuple
// Represents fork of an RRef to be sent over the wire.
struct TORCH_API RRefForkData {
const worker_id_t ownerId_;
const RRefId rrefId_;
const ForkId forkId_;
const worker_id_t parent_;
const std::string typeStr_;
RRefForkData(
worker_id_t ownerId,
const RRefId& rrefId,
const ForkId& forkId,
worker_id_t parent,
std::string typeStr);
};
// Note [RRef Protocol]
// ~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// [Background]
//
// RRef stands for Remote REFerence. Each RRef is owned by a single worker
// (i.e., owner) and can be used by multiple users. The owner stores the real
// data referenced by its RRefs. RRef needs to support fast and scalable RPC.
// Hence, in the design, we avoid using a single global master to keep RRef
// states, instead owners will keep track of the global reference counts
// for its RRefs. Every RRef can be uniquely identified by a global RRefId,
// which is assigned at the time it is first created either on a user or on the
// owner.
//
// On the owner worker, there is only one OwnerRRef instance, which contains the
// real data, while on user workers, there can be as many UserRRefs as
// necessary, and UserRRef does not hold the data. All usage on the OwnerRRef
// should retrieve the unique OwnerRRef instance using the globally unique
// RRefId. //A UserRRef will be created when it is used as an argument or return
// value in dist.rpc or dist.remote call, but RRef forking and reference
// counting (RC) are completely transparent to applications. Every UserRRef will
// also have its globally unique ForkId.
//
// [Assumptions]
//
// 1. Transient Network Failures
//
// The RRef design handles transient network failures by retrying
// messages. Node crashes or permanent network partition is beyond the scope.
// When those incidents occur, the application may take down all workers, revert
// to the previous checkpoint, and resume training.
//
// 2. Non-idempotent UDFs
//
// We assume UDFs are not idempotent and therefore cannot be retried. However,
// internal RRef control messages are idempotent and retried upon message
// failure.
//
// 3. Out of Order Message Delivery
//
// We do not assume message delivery order between any pair of nodes, because
// both sender and receiver are using multiple threads. There is no guarantee on
// which message will be processed first.
//
// [RRef Lifetime]
//
// The goal of the protocol is to delete an OwnerRRef at an appropriate time.
// The right time to delete an OwnerRRef is when there are no living UserRRefs
// and Python GC also agrees to delete the OwnerRRef instance on the owner. The
// tricky part is to determine if there are any living UserRRefs.
//
// A user can get a UserRRef in three situations:
//
// (1). Receiving a UserRRef from the owner.
// (2). Receiving a UserRRef from another user.
// (3). Creating a new UserRRef owned by another worker.
//
// (1) is the simplest case where the owner initiates the fork, and hence it can
// easily increment local RC. The only requirement is that any UserRRef must
// notify the owner before destruction. Hence, we need the first guarantee:
//
// G1. The owner will be notified when any UserRRef is deleted.
//
// As messages might come delayed or out-of-order, we need more one guarantee to
// make sure the delete message is not sent out too soon. Let us first introduce
// a new concept. If A sends an RPC to B that involves an RRef, we call the RRef
// on A the parent RRef and the RRef on B the child RRef.
//
// G2. Parent RRef cannot be deleted until the child RRef is confirmed by the
// owner.
//
// Under (1), where the caller is UserRRef and callee is OwnerRRef, it simply
// means that the user will not send out the delete message until all previous
// messages are ACKed. Note that ACKed does not mean the owner finishes
// executing the function, instead, it only means the owner has retrieved its
// local OwnerRRef and about to pass it to the function, which is sufficient to
// keep the OwnerRRef alive even if the delete message from the user arrives at
// the owner before the function finishes execution.
//
// With (2) and (3), it is possible that the owner only partially knows the RRef
// fork graph or not even knowing it at all. For example, the RRef could be
// constructed on a user, and before the owner receives the RPC call, the
// creator user might have already shared the RRef with other users, and those
// users could further share the RRef. One invariant is that the fork graph of
// any RRef is always a tree rooted at the owner, because forking an RRef always
// creates a new RRef instance, and hence every RRef has a single parent. One
// nasty detail is that when an RRef is created on a user, technically the owner
// is not its parent but we still consider it that way and it does not break the
// argument below.
//
// The owner's view on any node (fork) in the tree has three stages:
//
// 1) unknown -> 2) known -> 3) deleted.
//
// The owner's view on the entire tree keeps changing. The owner deletes its
// OwnerRRef instance when it thinks there are no living UserRRefs, i.e., when
// OwnerRRef is deleted, all UserRRefs could be either indeed deleted or
// unknown. The dangerous case is when some forks are unknown and others are
// deleted.
//
// G2 trivially guarantees that no parent UserRRef Y can be deleted before the
// owner knows all of Y's children UserRRefs.
//
// However, it is possible that the child UserRRef Z may be deleted before the
// owner knows its parent Y. More specifically, this can happen when all of Z's
// messages are processed by the owner before all messages from Y, including the
// delete message. Nevertheless, this does not cause any problem. Because, at
// least one of Y's ancestor will be alive, and it will prevent the owner from
// deleting the OwnerRRef. Consider the following example: (NB: this scenario
// will no longer relevant when we block UDF until all RRefs are confirmed by
// the owner)
//
// OwnerRRef -> A -> Y -> Z
//
// OwnerRRef forks to A, then A forks to Y, and Y forks to Z. Z can be deleted
// without OwnerRRef knowing Y. However, the OwnerRRef will at least know A, as
// the owner directly forks the RRef to A. A won't die before the owner knows Y.
//
// Things get a little trickier if the RRef is created on a user:
//
// OwnerRRef
// ^
// |
// A -> Y -> Z
//
// If Z calls to_here on the UserRRef, the owner at least knows A when Z is
// deleted, because otherwise to_here wouldn't finish. If Z does not call
// to_here, it is possible that the owner receives all messages from Z before
// any message from A and Y. In this case, as the real data of the OwnerRRef has
// not been created yet, there is nothing to be deleted either. It is the same
// as Z does not exist at all Hence, it's still OK.
//
// See #26759 for more details and discussions.
//
// ``RRef`` is the base type for both ``UserRRef`` and ``OwnerRRef``.
// Each ``RRef`` has a globally unique ``RRefId``.
class TORCH_API RRef : public RRefInterface {
public:
// RRef is made NOT copyable NOT movable to prevent messing up reference
// counting.
explicit RRef(const RRef& other) = delete;
explicit RRef(RRef&& other) = delete;
RRef& operator=(RRef&& other) = delete;
~RRef() override = default;
// returns the worker id of the owner
inline worker_id_t owner() const override {
return ownerId_;
}
// returns the worker name of the owner
inline std::string ownerName() const override {
return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_).name_;
}
// returns the worker info of the owner
inline WorkerInfo ownerWorkerInfo() const {
return RpcAgent::getCurrentRpcAgent()->getWorkerInfo(ownerId_);
}
// Returns the globally unique RRefId of this RRef
inline const RRefId& rrefId() const {
return rrefId_;
}
inline bool isPyObj() const {
return type_ == PyObjectType::get();
}
inline const TypePtr type() const override {
return type_;
}
// Save the future corresponding to the creation of this RRef on a remote
// node. Note that this is only set when processing requests invoked with
// rpc.remote. This is only used to get the future corresponding to the rref
// for profiling use cases.
inline void registerOwnerCreationFuture(c10::intrusive_ptr<JitFuture> fut) {
ownerCreationFuture_ = std::move(fut);
}
// Get the future corresponding to the creation of this rref.
inline c10::intrusive_ptr<JitFuture> getOwnerCreationFuture() const {
return ownerCreationFuture_;
}
// Check if creation of this RRef on owner node has timed out.
inline bool getTimedOut() const {
return timedOut_.load();
}
// Dispatches an error to the correct handler based on its RPCErrorType.
void handleError(RPCErrorType errorType, const JitFuture& JitFuture);
// Send delete UserRRef request to Owner,
// if the request hasn't been sent yet.
// There are 2 cases to call it,
// 1, Python GC decides end of UserRRef lifetime, calling destructor.
// 2, RPC module graceful shutdown calls it on all UserRRefs tracked
// in the RRefContext.
virtual void tryDel() {}
protected:
// Indicates that the creation of this RRef on owner node has timed out.
inline void setTimedOut() {
timedOut_ = true;
}
friend class RRefContext;
RRef(worker_id_t ownerId, const RRefId& rrefId, TypePtr type);
virtual RRefForkData fork() const;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const worker_id_t ownerId_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const RRefId rrefId_;
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
std::atomic<bool> timedOut_{false};
// type field to denote the type of the element that the RRef is holding
// it could be any TypePtr that JIT support, including PyObjectType
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
const TypePtr type_;
// Future corresponding to request to create RRef on remote node.
// NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes)
c10::intrusive_ptr<JitFuture> ownerCreationFuture_;
};
// ``UserRRef`` represents a user of an RRef. Besides the ``RRefId``, each user
// also has a globally unique ``ForkId`` to identify this user. ``UserRRef``
// never owns the real value, the only way to get the value of the ``RRef`` is
// to call ``to_here()`` and get a copy..
class TORCH_API UserRRef final : public RRef {
public:
UserRRef(const UserRRef& other) = delete;
UserRRef(UserRRef&& other) = delete;
UserRRef& operator=(const UserRRef& other) = delete;
UserRRef& operator=(UserRRef&& other) = delete;
UserRRef(
worker_id_t ownerId,
const RRefId& rrefId,
const ForkId& forkId,
TypePtr type);
inline bool isOwner() const override {
return false;
}
inline bool confirmedByOwner() const override {
return confirmedByOwner_;
}
// Returns the globally unique ForkId of this RRef
const ForkId& forkId() const;
// Get of copy of the value from the ``OwnerRRef``. If the value is not ready
// yet, this call will block.
IValue toHere(
const float timeoutSeconds =
torch::distributed::rpc::kUnsetRpcTimeout) const;
void tryDel() override;
// Will be called when refcount reaches 0.
// Upon destruction, this ``UserRRef`` will tell the owner to deref.
void release_resources() override;
// Will be called when both refcount and weakcount reach 0. See
// https://github.com/pytorch/pytorch/blob/9116f02bebf3a5260feef5732d36c54ecb3b4033/c10/util/intrusive_ptr.h#L204
// This is called on destructing the wrapping intrusive_ptr_target instance
// and it's data members. We don't need to implement anything here.
~UserRRef() override = default;
private:
friend class RRefContext;
RRefForkData fork() const override;
inline void confirm() {
confirmedByOwner_ = true;
}
const ForkId forkId_;
// Indicates if this user has sent delete message to it's owner.
// Note, thread safety is needed because delete message could be sent by
// either the destructor called by Python garbage collection or RRefContext
// proactive cleanup on RPC graceful shutdown.
std::mutex deletedOnOwnerMutex_;
bool deletedOnOwner_{false};
// Indicating whether this UserRRef has been confirmed by its owner.
std::atomic<bool> confirmedByOwner_;
};
// Keep the template only on the derived class because ``RRefContext`` needs to
// erase the type on ``RRef`` and keep them in one map.
class TORCH_API OwnerRRef final : public RRef {
public:
OwnerRRef(const OwnerRRef& other) = delete;
OwnerRRef(OwnerRRef&& other) = delete;
OwnerRRef& operator=(const OwnerRRef& other) = delete;
OwnerRRef& operator=(OwnerRRef&& other) = delete;
OwnerRRef(
worker_id_t ownerId,
const RRefId& rrefId,
TypePtr type,
std::vector<c10::Device> devices);
OwnerRRef(
worker_id_t ownerId,
const RRefId& rrefId,
TypePtr type,
c10::optional<IValue> value,
std::vector<c10::Device> devices);
inline bool isOwner() const override {
return true;
}
// OwnerRRef is always confirmed, while UserRRef is only confirmed when the
// owner knows about it.
inline bool confirmedByOwner() const override {
return true;
}
// Get a constant reference of the real value. This method will block if the
// value is not ready. This method does not need GIL as it does not create
// any new py::object. It will throw if there is an error.
const IValue& getValue() const;
// Set the value of this ``OwnerRRef``. This method does not need GIL as it
// does not create any new py::object.
void setValue(IValue&& value);
// Sets the value of this ``OwnerRRef`` to contain an exception.
void setError(std::exception_ptr eptr);
// Has a value or error been set?
bool hasValue() const;
// Gets a future that is satisfied when the value or error is set.
c10::intrusive_ptr<JitFuture> getFuture();
private:
friend class RRefContext;
c10::intrusive_ptr<JitFuture> future_;
};
TORCH_API std::ostream& operator<<(std::ostream& os, const RRef& rref);
// Helper function that casts from c10::RRefInterface to OwnerRRef
inline TORCH_API c10::intrusive_ptr<OwnerRRef> fromRRefInterface(
const c10::intrusive_ptr<c10::RRefInterface>& rrefInterface) {
return c10::static_intrusive_pointer_cast<OwnerRRef>(rrefInterface);
}
// Helper function that casts from OwnerRRef to c10::RRefInterface
inline TORCH_API c10::intrusive_ptr<c10::RRefInterface> fromOwnerRRef(
const c10::intrusive_ptr<RRef>& ownerRRef) {
return c10::static_intrusive_pointer_cast<c10::RRefInterface>(ownerRRef);
}
} // namespace rpc
} // namespace distributed
} // namespace torch
+1 -1
View File
@@ -4,7 +4,7 @@
#include <torch/csrc/StorageDefs.h>
THP_API PyObject * THPStorage_(New)(THWStorage *ptr);
TORCH_PYTHON_API PyObject * THPStorage_(New)(c10::intrusive_ptr<c10::StorageImpl> ptr);
extern PyObject *THPStorageClass;
#include <torch/csrc/Types.h>
@@ -3,9 +3,10 @@
#else
template <class io>
void THPStorage_(writeFileRaw)(THWStorage *self, io fd, bool save_size);
void THPStorage_(writeFileRaw)(c10::StorageImpl *self, io fd, bool save_size, uint64_t element_size);
template <class io>
THWStorage * THPStorage_(readFileRaw)(io fd, THWStorage *storage);
c10::intrusive_ptr<c10::StorageImpl> THPStorage_(readFileRaw)(
io fd, c10::intrusive_ptr<c10::StorageImpl> storage, uint64_t element_size);
#endif
-2
View File
@@ -11,8 +11,6 @@
struct THPStorage;
struct THSPTensor;
typedef class THPPointer<THWStorage> THWStoragePtr;
typedef class THPPointer<THWTensor> THWTensorPtr;
typedef class THPPointer<THPStorage> THPStoragePtr;
#if (!defined(THC_GENERIC_FILE)) && \
-53
View File
@@ -1,53 +0,0 @@
#!/bin/bash
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
CDIR="$(cd "$(dirname "$0")" ; pwd -P)"
NDIR="$CDIR/.."
TOCPU=$1
cd $NDIR/scripts
cp -f codegen/native_functions.yaml codegen/native_functions.yaml_bk
sed -i '/ _foreach/a\ device_check: NoCheck' codegen/native_functions.yaml # Only for pytorch 1.8.1
python3 -m codegen.gen_backend_stubs \
--to_cpu=${TOCPU} \
--output_dir="$NDIR/torch_npu/csrc/aten/" \
--source_yaml="$NDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \
--impl_path="$NDIR/torch_npu/csrc/aten" # Used to double-check the yaml file definitions.
if [ $? -ne 0 ]; then
echo "Failed to generate NPU backend stubs."
mv -f codegen/native_functions.yaml_bk codegen/native_functions.yaml
exit 1
fi
python3 -m codegen.gen_python_functions \
--output_dir="$NDIR/torch_npu/csrc/aten/" \
--source_yaml="$NDIR/torch_npu/csrc/aten/npu_native_functions.yaml" \
--native_yaml="$NDIR/scripts/codegen/native_functions.yaml" \
--template_path="$NDIR/scripts/codegen/templates"
if [ $? -ne 0 ]; then
echo "Failed to generate python bindings."
mv -f codegen/native_functions.yaml_bk codegen/native_functions.yaml
exit 1
fi
mv -f codegen/native_functions.yaml_bk codegen/native_functions.yaml
+27 -11
View File
@@ -38,12 +38,14 @@ from setuptools.command.build_clib import build_clib
from setuptools.command.egg_info import egg_info
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
VERSION = '1.8.1.post1'
VERSION = '1.11.0'
def generate_torch_npu_version():
torch_npu_root = Path(__file__).parent
version_path = torch_npu_root / "torch_npu" / "version.py"
if version_path.exists():
version_path.unlink()
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
modes = stat.S_IWUSR | stat.S_IRUSR
with os.fdopen(os.open(version_path, flags, modes), 'w') as f:
@@ -93,7 +95,7 @@ def get_build_type():
if os.getenv('DEBUG', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'Debug'
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'RelWithDebInfo'
return build_type
@@ -106,6 +108,7 @@ def _get_build_mode():
raise RuntimeError("Run setup.py without build mode.")
def get_pytorch_dir():
try:
import torch
@@ -117,7 +120,7 @@ def get_pytorch_dir():
def generate_bindings_code(base_dir, verbose):
generate_code_cmd = ["sh", os.path.join(base_dir, 'scripts', 'generate_code.sh'), verbose]
generate_code_cmd = ["bash", os.path.join(base_dir, 'generate_code.sh'), verbose]
if subprocess.call(generate_code_cmd) != 0:
print(
'Failed to generate ATEN bindings: {}'.format(generate_code_cmd),
@@ -181,9 +184,21 @@ class Clean(distutils.command.clean.clean):
# It's an old-style class in Python 2.7...
distutils.command.clean.clean.run(self)
os.remove('torch_npu/csrc/aten/RegisterCPU.cpp')
os.remove('torch_npu/csrc/aten/RegisterNPU.cpp')
os.remove('torch_npu/csrc/aten/RegisterAutogradNPU.cpp')
remove_files = [
'torch_npu/csrc/aten/RegisterCPU.cpp',
'torch_npu/csrc/aten/RegisterNPU.cpp',
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp',
'torch_npu/csrc/aten/NPUNativeFunctions.h',
'torch_npu/csrc/aten/python_custom_functions.cpp',
'torch_npu/utils/torch_funcs.py',
'torch_npu/version.py',
]
for remove_file in remove_files:
file_path = os.path.join(BASE_DIR, remove_file)
if os.path.exists(file_path):
os.remove(file_path)
class CPPLibBuild(build_clib, object):
def run(self):
@@ -200,8 +215,8 @@ class CPPLibBuild(build_clib, object):
output_lib_path = os.path.join(build_type_dir, "packages/torch_npu/lib")
os.makedirs(build_type_dir, exist_ok=True)
os.makedirs(output_lib_path, exist_ok=True)
self.build_lib = os.path.relpath(os.path.join(build_dir, "packages/torch_npu"))
self.build_temp = os.path.relpath(build_type_dir)
self.build_lib = os.path.relpath(os.path.join(build_dir, "packages/torch_npu"))
self.build_temp = os.path.relpath(build_type_dir)
cmake_args = [
'-DCMAKE_BUILD_TYPE=' + get_build_type(),
@@ -222,8 +237,8 @@ class Build(build_ext, object):
def run(self):
self.run_command('build_clib')
self.build_lib = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages"))
self.build_temp = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}"))
self.build_lib = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages"))
self.build_temp = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}"))
self.library_dirs.append(
os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages/torch_npu/lib")))
super(Build, self).run()
@@ -232,7 +247,7 @@ class Build(build_ext, object):
class InstallCmd(install):
def finalize_options(self) -> None:
self.build_lib = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages"))
self.build_lib = os.path.relpath(os.path.join(BASE_DIR, f"build/{get_build_type()}/packages"))
return super(InstallCmd, self).finalize_options()
@@ -306,6 +321,7 @@ class PythonPackageBuild(build_py, object):
self.copy_file(src, dst)
super(PythonPackageBuild, self).finalize_options()
to_cpu = os.getenv('NPU_TOCPU', default='TRUE')
build_mode = _get_build_mode()
if build_mode not in ['clean']:
+69 -2
View File
@@ -122,7 +122,7 @@ class TestAmp(TestCase):
def run(data, model, optimizer, scaler, loss_fn, skip_iter, try_scaling_api):
for i, (input_data, target) in enumerate(data):
optimizer.zero_grad()
with autocast(enabled=try_scaling_api):
with torch.autocast('npu', enabled=try_scaling_api):
output = model(input_data)
loss = loss_fn(output, target)
if try_scaling_api:
@@ -298,6 +298,73 @@ class TestAmp(TestCase):
s = s.cpu().to(torch.float).detach().numpy()
self.assertRtolEqual(c, s, 1e-7)
def test_autocast_custom_enabled(self):
class MyMM(torch.autograd.Function):
@staticmethod
@torch.npu.amp.custom_fwd
def forward(ctx, a, b):
self.assertTrue(a.dtype is torch.float32)
self.assertTrue(b.dtype is torch.float32)
self.assertTrue(torch.is_autocast_enabled())
ctx.save_for_backward(a, b)
return a.mm(b)
@staticmethod
@torch.npu.amp.custom_bwd
def backward(ctx, grad):
self.assertTrue(torch.is_autocast_enabled())
a, b = ctx.saved_tensors
return grad.mm(b.t()), a.t().mm(grad)
mymm = MyMM.apply
x = torch.randn((8, 8), device="npu", dtype=torch.float32, requires_grad=True)
y = torch.randn((8, 8), device="npu", dtype=torch.float32, requires_grad=True)
with torch.npu.amp.autocast():
output = mymm(x, y)
self.assertTrue(output.dtype is torch.float16)
loss = output.sum()
loss.backward()
def test_autocast_custom_cast_inputs(self):
class MyMM(torch.autograd.Function):
@staticmethod
@torch.npu.amp.custom_fwd(cast_inputs=torch.float32)
def forward(ctx, a, container, expect_type):
b = container[1][0]
self.assertTrue(a.dtype is expect_type)
self.assertTrue(b.dtype is expect_type)
self.assertFalse(torch.is_autocast_enabled())
ctx.save_for_backward(a, b)
return a.mm(b)
@staticmethod
@torch.npu.amp.custom_bwd
def backward(ctx, grad):
a, b = ctx.saved_tensors
return grad.mm(b.t()), None, None
mymm = MyMM.apply
x = torch.randn((8, 8), device="npu", dtype=torch.float16, requires_grad=True)
# Puts one input tensor in a nested container. y's contained Tensor won't receive a gradient,
# because torch.autograd.Function can't hand gradients back to non-Tensor forward arguments.
# Sets requires_grad=False explicitly so we don't lie about expecting a gradient.
y = (0, {0: torch.randn((8, 8), device="npu", dtype=torch.float16, requires_grad=False)})
with torch.autocast('npu', ):
output = mymm(x, y, torch.float32)
self.assertTrue(output.dtype is torch.float32)
loss = output.sum()
loss.backward()
# Tests if custom_fwd becomes a no-op when mymm runs outside an autocast-enabled region.
output = mymm(x, y, torch.float16)
self.assertTrue(output.dtype is torch.float16)
loss = output.sum()
loss.backward()
if __name__ == "__main__":
run_tests()
run_tests()
@@ -15,15 +15,14 @@
import expecttest
import torch
import torch_npu
import torch_npu._C
import numpy as np
import torch_npu
import torch_npu._C
import torch_npu.npu.utils as utils
from torch_npu.testing.testcase import TestCase, run_tests
class TestCheckOverFlow(TestCase):
def test_check_over_flow(self):
@@ -36,7 +35,7 @@ class TestCheckOverFlow(TestCase):
else:
rtn = utils.npu_check_over_flow(a)
self.assertTrue(rtn)
if __name__ == "__main__":
run_tests()
run_tests()
@@ -73,8 +73,15 @@ class TestSerialization(TestCase):
torch.save(x, path)
self.assertExpectedInline(f'{x.device.type}:{x.device.index}', f'{torch_npu.npu.npu_device}:0')
x_loaded = torch.load(path, map_location="npu:0")
x_loaded = x_loaded.npu()
self.assertRtolEqual(x.cpu(), x_loaded.cpu())
y_loaded = torch.load(path, map_location="npu")
self.assertRtolEqual(x.cpu(), y_loaded.cpu())
z_loaded = torch.load(path, map_location=torch.device("npu"))
self.assertRtolEqual(x.cpu(), z_loaded.cpu())
m_loaded = torch.load(path, map_location="cpu")
self.assertRtolEqual(x.cpu(), m_loaded)
n_loaded = torch.load(path, map_location=torch.device("cpu"))
self.assertRtolEqual(x.cpu(), n_loaded)
def test_load_maplocation(self):
x = torch.randn(2, 3)
+7
View File
@@ -169,6 +169,13 @@ class TorchNPUApiTestCase(TestCase):
def test_npu_get_device_name(self):
res = torch_npu.npu.get_device_name(0)
self.assertIsInstance(res, str)
res = torch_npu.npu.get_device_name()
self.assertIsInstance(res, str)
res = torch_npu.npu.get_device_name("npu:0")
self.assertIsInstance(res, str)
device = torch.device("npu:0")
res = torch_npu.npu.get_device_name(device)
self.assertIsInstance(res, str)
def test_npu_get_device_properties(self):
name = torch_npu.npu.get_device_properties(0).name
+8 -4
View File
@@ -143,7 +143,8 @@ class ComputeBucketAssignmentTest(TestCase):
torch.empty([50], dtype=torch.float).npu(),
]
result = dist._compute_bucket_assignment_by_size(tensors, [1792 * 4 + 1])
self.assertEqual([[0, 1], [2, 3]], result)
expec_result = ([[0, 1, 2, 3]], [7169])
self.assertEqual(expec_result, result)
def test_single_limit_multi_dtype(self):
tensors = [
@@ -155,7 +156,8 @@ class ComputeBucketAssignmentTest(TestCase):
torch.empty([25], dtype=torch.double).npu(),
]
result = dist._compute_bucket_assignment_by_size(tensors, [400])
self.assertEqual([[0, 2], [1, 3], [4], [5]], result)
expec_result = ([[0, 2], [1, 3], [4], [5]], [400, 400, 400, 400])
self.assertEqual(expec_result, result)
def test_multi_limit_single_dtype(self):
tensors = [
@@ -165,7 +167,8 @@ class ComputeBucketAssignmentTest(TestCase):
torch.empty([10], dtype=torch.float).npu(),
]
result = dist._compute_bucket_assignment_by_size(tensors, [40, 80])
self.assertEqual([[0], [1, 2], [3]], result)
expec_result = ([[0], [1, 2], [3]], [40, 80, 80])
self.assertEqual(expec_result, result)
def test_multi_limit_multi_dtype(self):
tensors = [
@@ -183,7 +186,8 @@ class ComputeBucketAssignmentTest(TestCase):
torch.empty([25], dtype=torch.double).npu(),
]
result = dist._compute_bucket_assignment_by_size(tensors, [200, 400])
self.assertEqual([[0], [1], [2, 4], [3, 5], [6, 8], [7, 9]], result)
expec_result = ([[0], [1], [2, 4], [3, 5], [6, 8], [7, 9]], [200, 200, 400, 400, 400, 400])
self.assertEqual(expec_result, result)
if __name__ == '__main__':
+170
View File
@@ -0,0 +1,170 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.utils import npu_combine_tensors, get_part_combined_tensor, is_combined_tensor_valid
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.decorator import Dtypes, instantiate_tests
@instantiate_tests
class TestCombineTensors(TestCase):
@Dtypes(torch.half, torch.float)
def test_change_data_ptr(self, dtype, device="npu"):
x = torch.randn((2, 2, 2, 2), device=device, dtype=dtype)
y = torch.randn((4, 4), device=device, dtype=dtype)
z = torch.randn((3, 3, 3), device=device, dtype=dtype)
x_clone = x.clone()
y_clone = y.clone()
z_clone = z.clone()
list_of_tensor = [x, y, z]
total_numel = 0
for tensor in list_of_tensor:
total_numel += torch_npu.get_storage_size(tensor)
combined_tensor = torch.zeros(total_numel, dtype=dtype).npu()
idx = 0
for tensor in list_of_tensor:
tmp = tensor.clone()
torch_npu.npu_change_data_ptr(tensor, combined_tensor, idx)
tensor.copy_(tmp)
idx += torch_npu.get_storage_size(tensor)
self.assertEqual(x, x_clone)
self.assertEqual(y, y_clone)
self.assertEqual(z, z_clone)
x_new = torch.zeros((2, 2, 2, 2), device=device, dtype=dtype)
y_new = torch.zeros((4, 4), device=device, dtype=dtype)
z_new = torch.zeros((3, 3, 3), device=device, dtype=dtype)
list_of_tensor_new = [x_new, y_new, z_new]
idx = 0
for tensor_new, tensor in zip(list_of_tensor_new, list_of_tensor):
torch_npu.npu_change_data_ptr(tensor_new, combined_tensor, idx)
self.assertEqual(tensor_new, tensor)
idx += torch_npu.get_storage_size(tensor)
@Dtypes(torch.half, torch.float)
def test_combine_tensors(self, dtype, device="npu"):
x = torch.zeros((2, 2, 2, 2), device=device, dtype=dtype)
y = torch.zeros((4, 4), device=device, dtype=dtype)
z = torch.zeros((3, 3, 3), device=device, dtype=dtype)
lst = [x, y, z]
combine_tensor = npu_combine_tensors(lst)
x_storage_size = torch_npu.get_storage_size(x)
y_storage_size = torch_npu.get_storage_size(y)
z_storage_size = torch_npu.get_storage_size(z)
combine_tensor_storage_size = torch_npu.get_storage_size(combine_tensor)
# test if combine_tensor is contiguous, and x,y,z are moved into the combine_tensor.
self.assertEqual(True, combine_tensor.is_contiguous())
self.assertEqual(combine_tensor.data_ptr(), x.data_ptr())
self.assertEqual(x.data_ptr() + x_storage_size * x.element_size(), y.data_ptr())
self.assertEqual(y.data_ptr() + y_storage_size * y.element_size(), z.data_ptr())
self.assertEqual(combine_tensor_storage_size, x_storage_size + y_storage_size + z_storage_size)
@Dtypes(torch.half, torch.float)
def test_combine_tensors_large(self, dtype, device="npu"):
x = torch.zeros((200, 20, 200, 20), device=device, dtype=dtype)
y = torch.zeros((4000, 4000), device=device, dtype=dtype)
z = torch.zeros((300, 300, 300), device=device, dtype=dtype)
lst = [x, y, z]
combine_tensor = npu_combine_tensors(lst)
x_storage_size = torch_npu.get_storage_size(x)
y_storage_size = torch_npu.get_storage_size(y)
z_storage_size = torch_npu.get_storage_size(z)
combine_tensor_storage_size = torch_npu.get_storage_size(combine_tensor)
# test if combine_tensor is contiguous, and x,y,z are moved into the combine_tensor.
self.assertEqual(True, combine_tensor.is_contiguous())
self.assertEqual(combine_tensor.data_ptr(), x.data_ptr())
self.assertEqual(x.data_ptr() + x_storage_size * x.element_size(), y.data_ptr())
self.assertEqual(y.data_ptr() + y_storage_size * y.element_size(), z.data_ptr())
self.assertEqual(combine_tensor_storage_size, x_storage_size + y_storage_size + z_storage_size)
@Dtypes(torch.half, torch.float)
def test_computation(self, dtype, device="npu"):
x = torch.zeros((2, 2, 2, 2), device=device, dtype=dtype)
y = torch.zeros((4, 4), device=device, dtype=dtype)
z = torch.zeros((3, 3, 3), device=device, dtype=dtype)
lst = [x, y, z]
combine_tensor = npu_combine_tensors(lst)
combine_tensor += 2
self.assertEqual(32, x.sum())
self.assertEqual(32, y.sum())
self.assertEqual(54, z.sum())
for tensor in lst:
tensor.mul_(2)
self.assertEqual(236, combine_tensor.sum().long().item())
self.assertEqual(combine_tensor.sum().long().item(), (x.sum() + y.sum() + z.sum()).long().item())
@Dtypes(torch.half, torch.float)
def test_get_part_combined_tensor(self, dtype, device="npu"):
x = torch.randn((2, 2, 2, 2), device=device, dtype=dtype)
y = torch.randn((4, 4), device=device, dtype=dtype)
z = torch.randn((3, 3, 3), device=device, dtype=dtype)
lst = [x, y, z]
combine_tensor = npu_combine_tensors(lst)
x_storage_size = torch_npu.get_storage_size(x)
y_storage_size = torch_npu.get_storage_size(y)
z_storage_size = torch_npu.get_storage_size(z)
part_tensor_x = get_part_combined_tensor(combine_tensor, 0, x_storage_size)
part_tensor_y = get_part_combined_tensor(combine_tensor, x_storage_size, y_storage_size)
part_tensor_z = get_part_combined_tensor(
combine_tensor, x_storage_size + y_storage_size, z_storage_size)
self.assertEqual(part_tensor_x.reshape_as(x), x)
self.assertEqual(part_tensor_y.reshape_as(y), y)
self.assertEqual(part_tensor_z.reshape_as(z), z)
@Dtypes(torch.half, torch.float)
def test_is_combined_tensor_valid(self, dtype, device="npu"):
x = torch.randn((2, 2, 2, 2), device=device, dtype=dtype)
y = torch.randn((4, 4), device=device, dtype=dtype)
z = torch.randn((3, 3, 3), device=device, dtype=dtype)
lst = [x, y, z]
combine_tensor = npu_combine_tensors(lst)
self.assertEqual(True, is_combined_tensor_valid(combine_tensor, lst))
self.assertEqual(False, is_combined_tensor_valid(combine_tensor, lst + [None]))
self.assertEqual(False, is_combined_tensor_valid(combine_tensor, [x.clone(), y.clone(), z.clone()]))
lst = []
combine_tensor = npu_combine_tensors(lst)
self.assertEqual(True, is_combined_tensor_valid(combine_tensor, lst))
if __name__ == '__main__':
run_tests()
+608
View File
@@ -0,0 +1,608 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import shutil
import math
import torch
from torch.nn.parameter import Parameter
from torch.nn import init
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
import torch_npu.onnx
class TestOnnxOps(TestCase):
test_onnx_path = os.path.join(
os.path.abspath(os.path.dirname(__file__)), "test_onnx_combined")
@classmethod
def setUpClass(cls):
os.makedirs(TestOnnxOps.test_onnx_path, exist_ok=True)
@classmethod
def tearDownClass(cls):
assert os.path.exists(TestOnnxOps.test_onnx_path)
shutil.rmtree(TestOnnxOps.test_onnx_path, ignore_errors=True)
def onnx_export(self, model, inputs, onnx_model_name,
input_names=None, output_names=None):
if input_names is None:
input_names = ["input_names"]
if output_names is None:
output_names = ["output_names"]
model.eval()
with torch.no_grad():
torch.onnx.export(model, inputs,
os.path.join(
TestOnnxOps.test_onnx_path, onnx_model_name),
opset_version=11, input_names=input_names,
output_names=output_names)
def test_wrapper_npu_linear(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.weight = Parameter(torch.empty(3, 16))
bias = True
if bias:
self.bias = Parameter(torch.empty(3))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
bound = 1 / math.sqrt(fan_in) if fan_in > 0 else 0
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
return torch_npu.npu_linear(input_, self.weight, self.bias)
def export_onnx(onnx_model_name):
input_ = torch.randn(4, 16).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_linear.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_transpose(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
perm = (2, 0, 1)
require_contiguous = False
return torch_npu.npu_transpose(input_, perm, require_contiguous)
def export_onnx(onnx_model_name):
input_ = torch.randn(2, 3, 5).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_transpose.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_broadcast(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
size = (3, 4)
return torch_npu.npu_broadcast(input_, size)
def export_onnx(onnx_model_name):
input_ = torch.tensor([[1], [2], [3]]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_broadcast.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_one_(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
return torch_npu.one_(input_)
def export_onnx(onnx_model_name):
input_ = torch.rand(3, 4).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_one_.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_conv_transpose2d(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.weight = Parameter(torch.empty([3, 2, 3, 3]))
bias = True
if bias:
self.bias = Parameter(torch.empty(2))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
if fan_in != 0:
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
stride, paddings, output_padding, dilation, groups = \
[1, 1], [0, 0], [0, 0], [1, 1], 1
return torch_npu.npu_conv_transpose2d(input_, self.weight, self.bias,
paddings, output_padding, stride, dilation, groups)
def export_onnx(onnx_model_name):
input_ = torch.rand([1, 3, 3, 3]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_conv_transpose2d.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_conv2d(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.weight = Parameter(torch.empty([256, 128, 3, 3]))
bias = True
if bias:
self.bias = Parameter(torch.empty(256))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
if fan_in != 0:
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
stride, paddings, dilation, groups = \
[1, 1], [1, 1], [1, 1], 1
return torch_npu.npu_conv2d(input_, self.weight, self.bias,
stride, paddings, dilation, groups)
def export_onnx(onnx_model_name):
input_ = torch.rand([16, 128, 112, 112]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_conv2d.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_conv3d(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.weight = Parameter(torch.empty([1, 128, 3, 3, 3]))
bias = False
if bias:
self.bias = Parameter(torch.empty(1))
else:
self.register_parameter("bias", None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
if fan_in != 0:
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
stride, paddings, dilation, groups = \
[1, 1, 1], [1, 1, 1], [1, 1, 1], 1
return torch_npu.npu_conv3d(input_, self.weight, self.bias,
stride, paddings, dilation, groups)
def export_onnx(onnx_model_name):
input_ = torch.rand([1, 128, 4, 14, 14]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_conv3d.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_stride_copy(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
shape = (2, 2)
stride = (1, 2)
storage_offset = 0
return torch_npu.npu_stride_copy(input_, shape, stride, storage_offset)
def export_onnx(onnx_model_name):
input_ = torch.rand(3, 3).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_stride_copy.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_sort_v2(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
dim = -1
descending = False
return torch_npu.npu_sort_v2(input_, dim, descending)
def export_onnx(onnx_model_name):
input_ = torch.randn(3, 4).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_sort_v2.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_layer_norm_eval(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
normalized_shape = 4
self.elementwise_affine = True
if self.elementwise_affine:
self.weight = Parameter(torch.empty(normalized_shape))
self.bias = Parameter(torch.empty(normalized_shape))
else:
self.register_parameter('weight', None)
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self) -> None:
if self.elementwise_affine:
init.ones_(self.weight)
init.zeros_(self.bias)
def forward(self, input_):
normalized_shape = input_.size()[1:]
eps = 1e-5
return torch_npu.npu_layer_norm_eval(input_, normalized_shape,
self.weight, self.bias, eps)
def export_onnx(onnx_model_name):
input_ = torch.rand((6, 4), dtype=torch.float32).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_layer_norm_eval.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_reshape(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
shape = (4, 4)
can_refresh = False
return torch_npu.npu_reshape(input_, shape, can_refresh)
def export_onnx(onnx_model_name):
input_ = torch.rand(2, 8).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_reshape.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_pad(self):
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, input_):
paddings = [1, 1, 1, 1]
return torch_npu.npu_pad(input_, paddings)
def export_onnx(onnx_model_name):
input_ = torch.tensor([[20, 20, 10, 10]],
dtype=torch.float16).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"], ["output_name"])
onnx_model_name = "model_npu_pad.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_convolution(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.weight = Parameter(torch.empty([64, 32, 3, 3]))
bias = True
if bias:
self.bias = Parameter(torch.empty([64]))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
if fan_in != 0:
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
stride, paddings, dilation, groups = \
[1, 1], [1, 1], [1, 1], 1
return torch_npu.npu_convolution(input_, self.weight, self.bias,
stride, paddings, dilation, groups)
def export_onnx(onnx_model_name):
input_ = torch.rand([16, 32, 24, 24]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_convolution.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_convolution_transpose(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.weight = Parameter(torch.empty([3, 2, 3, 3]))
bias = True
if bias:
self.bias = Parameter(torch.empty([2]))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
init.kaiming_uniform_(self.weight, a=math.sqrt(5))
if self.bias is not None:
fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
if fan_in != 0:
bound = 1 / math.sqrt(fan_in)
init.uniform_(self.bias, -bound, bound)
def forward(self, input_):
padding, output_padding, stride, dilation, groups = \
[1, 1], [0, 0], [1, 1], [1, 1], 1
return torch_npu.npu_convolution_transpose(input_, self.weight, self.bias, padding,
output_padding, stride, dilation, groups)
def export_onnx(onnx_model_name):
input_ = torch.rand([1, 3, 3, 3]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_convolution_transpose.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_confusion_transpose(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
perm = (0, 2, 1, 3)
shape = [1, 576, 32, 80]
transpose_first = False
return torch_npu.npu_confusion_transpose(input_, perm, shape, transpose_first)
def export_onnx(onnx_model_name):
input_ = torch.rand([1, 576, 2560]).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_confusion_transpose.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_max(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
dim = 2
return torch_npu.npu_max(input_, dim)
def export_onnx(onnx_model_name):
input_ = torch.rand((2, 2, 2, 2)).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name,
["input_"], ["values", "indices"])
onnx_model_name = "model_npu_max.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_bmmV2(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_, mat2):
output_sizes = []
return torch_npu.npu_bmmV2(input_, mat2, output_sizes)
def export_onnx(onnx_model_name):
input_ = torch.rand((10, 3, 4)).npu()
mat2 = torch.rand((10, 4, 5)).npu()
model = Model().to("npu")
self.onnx_export(model, (input_, mat2),
onnx_model_name, ["input_", "mat2"])
onnx_model_name = "model_npu_bmmV2.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_dtype_cast(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
return torch_npu.npu_dtype_cast(input_, torch.int32)
def export_onnx(onnx_model_name):
input_ = torch.rand((8, 10)).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_dtype_cast.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_silu(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
return torch_npu.npu_silu(input_)
def export_onnx(onnx_model_name):
input_ = torch.randn(5, 5).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_silu.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_mish(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
return torch_npu.npu_mish(input_)
def export_onnx(onnx_model_name):
input_ = torch.randn(5, 5).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name, ["input_"])
onnx_model_name = "model_npu_mish.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_min(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_):
dim = 2
return torch_npu.npu_min(input_, dim)
def export_onnx(onnx_model_name):
input_ = torch.rand((2, 2, 2, 2)).npu()
model = Model().to("npu")
self.onnx_export(model, input_, onnx_model_name,
["input_"], ["values", "indices"])
onnx_model_name = "model_npu_min.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
def test_wrapper_npu_scaled_masked_softmax(self):
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
def forward(self, input_, mask):
scale = 0.56
fixed_triu_mask = False
return torch_npu.npu_scaled_masked_softmax(input_, mask,
scale, fixed_triu_mask)
def export_onnx(onnx_model_name):
input_ = torch.rand((4, 3, 64, 64)).npu()
mask = torch.rand((4, 3, 64, 64)).npu() > 0
model = Model().to("npu")
self.onnx_export(model, (input_, mask), onnx_model_name,
["input_", "mask"])
onnx_model_name = "model_npu_scaled_masked_softmax.onnx"
export_onnx(onnx_model_name)
assert (os.path.isfile(os.path.join(TestOnnxOps.test_onnx_path,
onnx_model_name)))
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,64 @@
## Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestConvolutionTranspose(TestCase):
def supported_op_exec(self, input1, weight, bias, padding, output_padding, stride, dilation, groups):
dim = input1.dim()
if dim == 4:
output = torch.nn.functional.conv_transpose2d(input1, weight, bias, stride, padding,
output_padding, groups, dilation)
elif dim == 5:
output = torch.nn.functional.conv_transpose3d(input1, weight, bias, stride, padding,
output_padding, groups, dilation)
return output.cpu().detach()
def custom_op_exec(self, input1, weight, bias, padding, output_padding, stride, dilation, groups):
output = torch_npu.npu_convolution_transpose(input1, weight, bias, padding, output_padding,
stride, dilation, groups)
return output.cpu().detach()
def test_npu_convolution_transpose(self):
items = [[[np.float32, 0, [1, 3, 3, 3]], [np.float32, 0, [3, 2, 3, 3]], [np.float32, 2, [2]],
[1, 1], [0, 0], [0, 0], [1, 1], 1],
[[np.float32, 2, [20, 16, 50, 10, 20]], [np.float32, 2, [16, 33, 3, 3, 3]], None,
[0, 0, 0], [0, 0, 0], [1, 1, 1], [1, 1, 1], 1]]
for item in items:
_, npu_input = create_common_tensor(item[0], 0, 0.001)
_, weight = create_common_tensor(item[1], 0, 0.001)
_, bias = create_common_tensor(item[2], 1, 200) if item[2] else _, None
padding = item[3]
output_padding = item[4]
stride = item[5]
dilation = item[6]
groups = item[7]
supported_output = self.supported_op_exec(npu_input, weight, bias, padding, output_padding,
stride, dilation, groups)
custom_output = self.custom_op_exec(npu_input, weight, bias, padding, output_padding,
stride, dilation, groups)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
+49
View File
@@ -0,0 +1,49 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestFastGelu(TestCase):
def supported_op_exec(self, input1):
attr = 1.702
attr_half = attr / 2
abs_input1 = torch.abs(input1)
numerator = input1 * torch.exp((attr_half * input1) * (input1 - abs_input1))
denominator = 1.0 + torch.exp(- attr * abs_input1)
output = numerator / denominator
return output.cpu().detach()
def custom_op_exec(self, input1):
output = torch_npu.fast_gelu(input1)
return output.cpu().detach()
def test_fast_gelu(self, device="npu"):
item = [np.float32, 0, [3, 16, 32]]
_, npu_input = create_common_tensor(item, 0, 100)
supported_output = self.supported_op_exec(npu_input)
custom_output = self.custom_op_exec(npu_input)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,59 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import numpy as np
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestNpuAnchorResponseFlags(TestCase):
def custom_op_exec(self, gt_bboxes, featmap_size, strides, num_base_anchors):
if gt_bboxes.dtype == torch.float16:
gt_bboxes = gt_bboxes.to(torch.float32)
feat_h, feat_w = featmap_size
gt_bboxes_cx = ((gt_bboxes[:, 0] + gt_bboxes[:, 2]) * 0.5)
gt_bboxes_cy = ((gt_bboxes[:, 1] + gt_bboxes[:, 3]) * 0.5)
gt_bboxes_grid_x = torch.floor(gt_bboxes_cx / strides[0]).int()
gt_bboxes_grid_y = torch.floor(gt_bboxes_cy / strides[1]).int()
gt_bboxes_grid_idx = gt_bboxes_grid_y * feat_w + gt_bboxes_grid_x
responsible_grid = torch.zeros(feat_h * feat_w, dtype=torch.uint8).npu()
gt_bboxes_grid_idx = gt_bboxes_grid_idx.long()
responsible_grid[gt_bboxes_grid_idx] = 1
responsible_grid = responsible_grid[:, None].expand(
responsible_grid.size(0), num_base_anchors).contiguous().view(-1)
return responsible_grid.cpu().numpy()
def npu_op_exec(self, input_npu, featmap_size, strides, num_base_anchors):
out = torch_npu.npu_anchor_response_flags(input_npu, featmap_size, strides, num_base_anchors)
out = out.cpu().numpy()
return out
def test_npu_anchor_response_flags(self):
shape_format = [
[[np.float32, -1, [100, 4]], [60, 60], [2, 2], 9],
[[np.float16, -1, [200, 4]], [10, 10], [32, 32], 3],
[[np.float16, -1, [500, 4]], [32, 32], [16, 16], 5]
]
for item in shape_format:
_, npu_input = create_common_tensor(item[0], 0, 100)
custom_output = self.custom_op_exec(npu_input, *item[1:])
npu_output = self.npu_op_exec(npu_input, *item[1:])
self.assertRtolEqual(custom_output, npu_output)
if __name__ == "__main__":
run_tests()
+47
View File
@@ -0,0 +1,47 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestBatchMatMulV2(TestCase):
def supported_op_exec(self, input1, input2, output_sizes):
output = torch.matmul(input1, input2)
return output.cpu().detach()
def custom_op_exec(self, input1, input2, output_sizes):
output = torch_npu.npu_bmmV2(input1, input2, output_sizes)
return output.cpu().detach()
def test_npu_bmmV2(self, device="npu"):
item1 = [np.float32, 0, (10, 3, 4)]
item2 = [np.float32, 0, (10, 4, 5)]
_, npu_input1 = create_common_tensor(item1, -1, 1)
_, npu_input2 = create_common_tensor(item2, -1, 1)
output_sizes = []
supported_output = self.supported_op_exec(npu_input1, npu_input2, output_sizes)
custom_output = self.custom_op_exec(npu_input1, npu_input2, output_sizes)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,106 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestBoundingBoxDecode(TestCase):
def npu_bounding_box_decode(self, rois, deltas, means0, means1, means2, means3,
stds0, stds1, stds2, stds3, max_shape, wh_ratio_clip):
means = [means0, means1, means2, means3]
stds = [stds0, stds1, stds2, stds3]
means = deltas.new_tensor(means).repeat(1, deltas.size(1) // 4)
stds = deltas.new_tensor(stds).repeat(1, deltas.size(1) // 4)
denorm_deltas = deltas * stds + means
dx = denorm_deltas[:, 0::4]
dy = denorm_deltas[:, 1::4]
dw = denorm_deltas[:, 2::4]
dh = denorm_deltas[:, 3::4]
max_ratio = torch.abs(torch.log(torch.tensor(wh_ratio_clip)))
dw = torch.clamp(dw, min=-max_ratio, max=max_ratio)
dh = torch.clamp(dh, min=-max_ratio, max=max_ratio)
ax = ((rois[:, 0] + rois[:, 2]) * 0.5).unsqueeze(1).expand_as(dx)
ay = ((rois[:, 1] + rois[:, 3]) * 0.5).unsqueeze(1).expand_as(dy)
aw = (rois[:, 2] - rois[:, 0] * 0.5).unsqueeze(1).expand_as(dw)
ah = (rois[:, 3] - rois[:, 1] * 0.5).unsqueeze(1).expand_as(dh)
pw = aw * dw.exp()
ph = ah * dh.exp()
px = torch.addcmul(ax, 1, aw, dx)
py = torch.addcmul(ay, 1, ah, dy)
x1 = px - pw * 0.5 + 0.5
y1 = py - ph * 0.5 + 0.5
x2 = px + pw * 0.5 - 0.5
y2 = py + ph * 0.5 - 0.5
if max_shape is not None:
x1 = torch.clamp(x1, min=0, max=(max_shape[1] - 1))
y1 = torch.clamp(y1, min=0, max=(max_shape[0] - 1))
x2 = torch.clamp(x2, min=0, max=(max_shape[1] - 1))
y2 = torch.clamp(y2, min=0, max=(max_shape[0] - 1))
boxes = torch.stack([x1, y1, x2, y2], dim=-1).view_as(deltas)
return boxes
def custom_op_exec(self, rois, deltas, means0, means1, means2, means3,
stds0, stds1, stds2, stds3, max_shape, wh_ratio_clip):
output = self.npu_bounding_box_decode(rois, deltas, means0, means1,
means2, means3, stds0, stds1,
stds2, stds3, max_shape, wh_ratio_clip)
output = output.to("cpu")
output = output.numpy()
return output
def npu_op_exec(self, rois, deltas, means0, means1, means2, means3,
stds0, stds1, stds2, stds3, max_shape, wh_ratio_clip):
output = torch_npu.npu_bounding_box_decode(rois, deltas, means0, means1,
means2, means3, stds0, stds1,
stds2, stds3, max_shape, wh_ratio_clip)
output = output.to("cpu")
output = output.numpy()
return output
def test_decode_shape_format_fp32(self):
input1 = torch.tensor([[1., 2., 3., 4.], [3.,4., 5., 6.]],
dtype = torch.float32).to("npu")
input2 = torch.tensor([[5., 6., 7., 8.], [7.,8., 9., 6.]],
dtype = torch.float32).to("npu")
npu_output = self.npu_op_exec(input1, input2, 0, 0, 0, 0,
1, 1, 1, 1, (10, 10), 0.1)
custom_output = self.custom_op_exec(input1, input2, 0, 0, 0, 0,
1, 1, 1, 1, (10, 10), 0.1)
self.assertRtolEqual(npu_output, custom_output)
def test_decode_shape_format_fp16(self):
input1_fp16 = torch.tensor([[1., 2., 3., 4.], [3.,4., 5., 6.]],
dtype = torch.float16).to("npu")
input2_fp16 = torch.tensor([[5., 6., 7., 8.], [7.,8., 9., 6.]],
dtype = torch.float16).to("npu")
npu_output = self.npu_op_exec(input1_fp16, input2_fp16, 0, 0, 0, 0,
1, 1, 1, 1, (10, 10), 0.1)
custom_output = self.custom_op_exec(input1_fp16, input2_fp16, 0, 0, 0, 0,
1, 1, 1, 1, (10, 10), 0.1)
self.assertRtolEqual(npu_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,91 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestBoundingBoxEncode(TestCase):
def npu_bounding_box_encode(self, anchor_box, ground_truth_box, means0, means1,
means2, means3, stds0, stds1, stds2, stds3):
means = [means0, means1, means2, means3]
stds = [stds0, stds1, stds2, stds3]
px = (anchor_box[..., 0] + anchor_box[..., 2]) * 0.5
py = (anchor_box[..., 1] + anchor_box[..., 3]) * 0.5
pw = anchor_box[..., 2] - anchor_box[..., 0] + 1.0
ph = anchor_box[..., 3] - anchor_box[..., 1] + 1.0
gx = (ground_truth_box[..., 0] + ground_truth_box[..., 2]) * 0.5
gy = (ground_truth_box[..., 1] + ground_truth_box[..., 3]) * 0.5
gw = ground_truth_box[..., 2] - ground_truth_box[..., 0] + 1.0
gh = ground_truth_box[..., 3] - ground_truth_box[..., 1] + 1.0
eps = 1e-7
dx = (gx - px) / (pw + eps)
dy = (gy - py) / (ph + eps)
dw = torch.log(torch.abs(gw) / torch.abs(pw + eps))
dh = torch.log(torch.abs(gh) / torch.abs(ph + eps))
deltas = torch.stack([dx, dy, dw, dh], dim=-1)
means = deltas.new_tensor(means).unsqueeze(0)
stds = deltas.new_tensor(stds).unsqueeze(0)
deltas = deltas.sub_(means) .div_(stds)
return deltas
def custom_op_exec(self, anchor_box, ground_truth_box, means0, means1,
means2, means3, stds0, stds1, stds2, stds3):
output = self.npu_bounding_box_encode(anchor_box, ground_truth_box, means0, means1,
means2, means3, stds0, stds1, stds2, stds3)
output = output.to("cpu")
output = output.numpy()
return output
def npu_op_exec(self, anchor_box, ground_truth_box, means0, means1,
means2, means3, stds0, stds1, stds2, stds3):
output = torch_npu.npu_bounding_box_encode(anchor_box, ground_truth_box, means0, means1,
means2, means3, stds0, stds1, stds2, stds3)
output = output.to("cpu")
output = output.numpy()
return output
def test_encode_shape_format_fp32(self):
input1 = torch.tensor([[1., 2., 3., 4.], [3.,4., 5., 6.]],
dtype = torch.float32).to("npu")
input2 = torch.tensor([[5., 6., 7., 8.], [7.,8., 9., 6.]],
dtype = torch.float32).to("npu")
npu_output = self.npu_op_exec(input1, input2, 0, 0, 0, 0,
0.1, 0.1, 0.2, 0.2)
custom_output = self.custom_op_exec(input1, input2, 0, 0, 0, 0,
0.1, 0.1, 0.2, 0.2)
self.assertRtolEqual(npu_output, custom_output, 1e-3)
def test_encode_shape_format_fp16(self):
input1_fp16 = torch.tensor([[1., 2., 3., 4.], [3.,4., 5., 6.]],
dtype = torch.float16).to("npu")
input2_fp16 = torch.tensor([[5., 6., 7., 8.], [7.,8., 9., 6.]],
dtype = torch.float16).to("npu")
npu_output = self.npu_op_exec(input1_fp16, input2_fp16, 0, 0, 0, 0,
0.1, 0.1, 0.2, 0.2)
custom_output = self.custom_op_exec(input1_fp16, input2_fp16, 0, 0, 0, 0,
0.1, 0.1, 0.2, 0.2)
self.assertRtolEqual(npu_output, custom_output, 1e-3)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,50 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestConfusionTranspose(TestCase):
def supported_op_exec(self, input1, perm, shape, transpose_first):
if transpose_first:
output = input1.permute(*perm).contiguous().view(shape)
else:
output = input1.view(shape).permute(*perm)
return output.cpu().detach()
def custom_op_exec(self, input1, perm, shape, transpose_first):
output = torch_npu.npu_confusion_transpose(input1, perm, shape, transpose_first)
return output.cpu().detach()
def test_npu_confusion_transpose(self, device="npu"):
item = [np.float32, 0, [1, 576, 2560]]
_, npu_input = create_common_tensor(item, 0, 100)
perm = (0, 2, 1, 3)
shape = [1, 576, 32, 80]
transpose_first = False
supported_output = self.supported_op_exec(npu_input, perm, shape, transpose_first)
custom_output = self.custom_op_exec(npu_input, perm, shape, transpose_first)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
+100
View File
@@ -0,0 +1,100 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.common_utils import create_common_tensor
from torch_npu.testing.testcase import TestCase, run_tests
class TestNpuConv2d(TestCase):
def custom_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
output = torch.nn.functional.conv2d(input1, weight, bias, stride, padding, dilation, groups)
output = output.cpu().numpy()
return output
def npu_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
output = torch_npu.npu_conv2d(input1, weight, bias, stride, padding, dilation, groups)
output = output.cpu().numpy()
return output
def test_npu_conv2d_fp16(self):
shape_format = [
# input, weigth, bias, stride, padding, dilation, groups
[[np.float16, 0, [16, 128, 112, 112]], [np.float16, 0, [256, 128, 3, 3]], [np.float16, 2, [256]], [1, 1],
[1, 1], [1, 1], 1],
[[np.float16, 0, [1024, 232, 7, 7]], [np.float16, 0, [232, 232, 1, 1]], [np.float16, 2, [232]], [1, 2],
[1, 2], [1, 2], 1],
[[np.float16, 0, [1024, 116, 14, 14]], [np.float16, 0, [116, 116, 1, 1]], None, [1, 1], [1, 1], [1, 1], 1],
[[np.float16, 0, [4, 8, 300, 40]], [np.float16, 0, [16, 8, 3, 3]], None, [1, 2], [1, 2], [1, 2], 1],
]
for item in shape_format:
_, input_npu = create_common_tensor(item[0], -1, 1)
_, weight_npu = create_common_tensor(item[1], -1, 1)
_, bias_npu = create_common_tensor(item[2], -1, 1) if item[2] else None, None
custom_output = self.custom_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
npu_output = self.npu_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
self.assertRtolEqual(custom_output, npu_output)
def test_npu_conv2d_fp32(self):
shape_format = [
# input, weigth, bias, stride, padding, dilation, groups
[[np.float32, 0, [16, 128, 112, 112]], [np.float32, 0, [256, 128, 3, 3]], [np.float32, 2, [256]], [1, 1],
[1, 1], [1, 1], 1],
[[np.float32, 0, [1024, 232, 7, 7]], [np.float32, 0, [232, 232, 1, 1]], [np.float32, 2, [232]], [1, 2],
[1, 2], [1, 2], 1],
[[np.float32, 0, [1024, 116, 14, 14]], [np.float32, 0, [116, 116, 1, 1]], None, [1, 1], [1, 1], [1, 1], 1],
[[np.float32, 0, [4, 8, 300, 40]], [np.float32, 0, [16, 8, 3, 3]], None, [1, 2], [1, 2], [1, 2], 1],
]
for item in shape_format:
_, input_npu = create_common_tensor(item[0], -1, 1)
_, weight_npu = create_common_tensor(item[1], -1, 1)
_, bias_npu = create_common_tensor(item[2], -1, 1) if item[2] else None, None
custom_output = self.custom_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
npu_output = self.npu_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
self.assertRtolEqual(custom_output, npu_output)
if __name__ == "__main__":
run_tests()
+100
View File
@@ -0,0 +1,100 @@
# Copyright (c) 2020 Huawei Technologies Co., Ltd
# Copyright (c) 2019, Facebook CORPORATION.
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.common_utils import create_common_tensor
from torch_npu.testing.testcase import TestCase, run_tests
class TestNpuConv3d(TestCase):
def custom_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
output = torch.nn.functional.conv3d(input1, weight, bias, stride, padding, dilation, groups)
output = output.cpu().numpy()
return output
def npu_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
output = torch_npu.npu_conv3d(input1, weight, bias, stride, padding, dilation, groups)
output = output.cpu().numpy()
return output
def test_npu_conv3d_fp16(self):
shape_format = [
# input, weigth, bias, stride, padding, dilation, groups
[[np.float16, 30, [1, 128, 4, 14, 14]], [np.float16, 30, [1, 128, 3, 3, 3]], None, [1, 1, 1], [1, 1, 1],
[1, 1, 1], 1],
[[np.float16, 30, [1, 64, 4, 14, 14]], [np.float16, 30, [1, 64, 3, 3, 3]], None, [1, 1, 1], [2, 2, 2],
[1, 1, 1], 1],
[[np.float16, 30, [20, 16, 50, 10, 20]], [np.float16, 30, [33, 16, 3, 3, 3]], [np.float16, 2, [33]],
[1, 1, 1], [2, 2, 2], [1, 1, 1], 1],
]
for item in shape_format:
_, input_npu = create_common_tensor(item[0], -1, 1)
_, weight_npu = create_common_tensor(item[1], -1, 1)
_, bias_npu = create_common_tensor(item[2], -1, 1) if item[2] else None, None
custom_output = self.custom_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
npu_output = self.npu_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
self.assertRtolEqual(custom_output, npu_output)
def test_npu_conv3d_fp32(self):
shape_format = [
# input, weigth, bias, stride, padding, dilation, groups
[[np.float32, 30, [1, 128, 4, 14, 14]], [np.float32, 30, [1, 128, 3, 3, 3]], None, [1, 1, 1], [1, 1, 1],
[1, 1, 1], 1],
[[np.float32, 30, [1, 64, 4, 14, 14]], [np.float32, 30, [1, 64, 3, 3, 3]], None, [1, 1, 1], [2, 2, 2],
[1, 1, 1], 1],
[[np.float32, 30, [20, 16, 50, 10, 20]], [np.float32, 30, [33, 16, 3, 3, 3]], [np.float32, 2, [33]],
[1, 1, 1], [2, 2, 2], [1, 1, 1], 1],
]
for item in shape_format:
_, input_npu = create_common_tensor(item[0], -1, 1)
_, weight_npu = create_common_tensor(item[1], -1, 1)
_, bias_npu = create_common_tensor(item[2], -1, 1) if item[2] else None, None
custom_output = self.custom_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
npu_output = self.npu_op_exec(input_npu,
weight_npu,
bias_npu,
stride=item[3],
padding=item[4],
dilation=item[5],
groups=item[6])
self.assertRtolEqual(custom_output, npu_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,65 @@
## Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestConvolution(TestCase):
def supported_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
dim = input1.dim()
if dim == 4:
output = torch.nn.functional.conv2d(input1, weight, bias, stride, padding, dilation, groups)
if dim == 5:
is_dilated = False
for d in dilation:
is_dilated |= (d != 1)
if groups == 1 and not is_dilated:
kernel_size = weight.size()[2]
output = torch._C._nn.slow_conv3d(input1, weight, kernel_size, bias, stride, padding)
else:
output = torch.nn.functional.conv3d(input1, weight, bias, stride, padding, dilation, groups)
return output.cpu().detach()
def custom_op_exec(self, input1, weight, bias, stride, padding, dilation, groups):
output = torch_npu.npu_convolution(input1, weight, bias, stride, padding, dilation, groups)
return output.cpu().detach()
def test_npu_convolution(self, device="npu"):
items = [[[np.float32, 0, [16, 128, 112, 112]], [np.float32, 0, [256, 128, 3, 3]], [np.float32, 2, [256]],
[1, 1], [1, 1], [1, 1], 1],
[[np.float16, 30, [1, 128, 4, 14, 14]], [np.float16, 30, [1, 128, 3, 3, 3]], None,
[1, 1, 1], [1, 1, 1], [1, 1, 1], 1]]
for item in items:
_, npu_input = create_common_tensor(item[0], -1, 1)
_, weight = create_common_tensor(item[1], -1, 1)
_, bias = create_common_tensor(item[2], -1, 1) if item[2] else _, None
stride = item[3]
padding = item[4]
dilation = item[5]
groups = item[6]
supported_output = self.supported_op_exec(npu_input, weight, bias, stride, padding, dilation, groups)
custom_output = self.custom_op_exec(npu_input, weight, bias, stride, padding, dilation, groups)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,45 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestDtypeCast(TestCase):
def supported_op_exec(self, input1, dst_dtype):
output = input1.to(dst_dtype)
return output.cpu().detach()
def custom_op_exec(self, input1, dst_dtype):
output = torch_npu.npu_dtype_cast(input1, dst_dtype)
return output.cpu().detach()
def test_npu_dtype_cast(self, device="npu"):
item = [np.float32, 0, (64, 10)]
_, npu_input = create_common_tensor(item, -1, 1)
dst_dtype = torch.float16
supported_output = self.supported_op_exec(npu_input, dst_dtype)
custom_output = self.custom_op_exec(npu_input, dst_dtype)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,46 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestFormatCast(TestCase):
def supported_op_exec(self, input1):
m = torch.nn.Identity(54, unused_argument1=0.1, unused_argument2=False)
output = m(input1)
return output.cpu().detach()
def custom_op_exec(self, input1, acl_format):
output = torch_npu.npu_format_cast(input1, acl_format)
return output.cpu().detach()
def test_npu_format_cast(self, device="npu"):
item = [np.float16, 0, (2, 2, 4, 4)]
_, npu_input = create_common_tensor(item, -1, 1)
acl_format = 3
supported_output = self.supported_op_exec(npu_input)
custom_output = self.custom_op_exec(npu_input, acl_format)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,83 @@
## Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestFusedAttentionQKV(TestCase):
def confusion_transpose(self, x, new_shape):
return x.view(new_shape).permute(0, 2, 1, 3).npu_format_cast(29)
def supported_op_exec(self, ln_input, q_kernel, k_kernel, v_kernel, gamma, beta, q_bias, k_bias, v_bias):
q_kernel = q_kernel.t().contiguous().npu_format_cast(29)
k_kernel = k_kernel.t().contiguous().npu_format_cast(29)
v_kernel = v_kernel.t().contiguous().npu_format_cast(29)
norm_shape = (1024,)
norm, mean, variance = torch.native_layer_norm(ln_input, norm_shape, gamma, beta, eps=1e-05)
q_layer = self.confusion_transpose(torch.nn.functional.linear(norm, q_kernel, q_bias), (24, 512, 16, 64))
k_layer = self.confusion_transpose(torch.nn.functional.linear(norm, k_kernel, k_bias), (24, 512, 16, 64))
v_layer = self.confusion_transpose(torch.nn.functional.linear(norm, v_kernel, v_bias), (24, 512, 16, 64))
return norm.cpu(), mean.cpu(), variance.cpu(), q_layer.cpu(), k_layer.cpu(), v_layer.cpu()
def custom_op_exec(self, hidden_states, q_kernel, k_kernel, v_kernel, gamma, beta, q_bias, k_bias, v_bias):
hidden_states = hidden_states.npu_format_cast(29)
q_kernel = q_kernel.npu_format_cast(29)
k_kernel = k_kernel.npu_format_cast(29)
v_kernel = v_kernel.npu_format_cast(29)
gamma = gamma.npu_format_cast(1)
beta = beta.npu_format_cast(1)
seq_len = 512
num_heads = 16
norm, q_layer, k_layer, v_layer, mean, variance = torch_npu.npu_fused_attention_layernorm_qkv_fwd(
hidden_states, q_kernel, k_kernel, v_kernel, gamma, beta, q_bias, k_bias, v_bias, seq_len, num_heads)
return norm.cpu(), mean.cpu(), variance.cpu(), q_layer.cpu(), k_layer.cpu(), v_layer.cpu()
def test_npu_fused_attention_layernorm_qkv_fwd(self, device="npu"):
ln_input = torch.rand(12288, 1024).uniform_(-6, 6).half().npu()
q_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half().npu()
k_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half().npu()
v_weight = torch.rand(1024, 1024).uniform_(-0.1, 0.1).half().npu()
gamma = torch.rand(1024).half().npu()
beta = torch.rand(1024).half().npu()
q_bias = torch.rand(1024).half().npu()
k_bias = torch.rand(1024).half().npu()
v_bias = torch.rand(1024).half().npu()
supported_norm, supported_mean, supported_variance, \
supported_q, supported_k, supported_v = self.supported_op_exec(
ln_input, q_weight, k_weight, v_weight, gamma, beta, q_bias, k_bias, v_bias)
custom_norm, custom_mean, custom_variance, \
custom_q, custom_k, custom_v = self.custom_op_exec(
ln_input, q_weight, k_weight, v_weight, gamma, beta, q_bias, k_bias, v_bias)
self.assertRtolEqual(supported_norm, custom_norm)
self.assertRtolEqual(supported_mean, custom_mean)
self.assertRtolEqual(supported_variance, custom_variance)
self.assertRtolEqual(supported_q, custom_q, prec16=0.003)
self.assertRtolEqual(supported_k, custom_k, prec16=0.003)
self.assertRtolEqual(supported_v, custom_v, prec16=0.003)
if __name__ == '__main__':
run_tests()
@@ -0,0 +1,59 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestGridAssignPositive(TestCase):
def supported_op_exec(self, input1, box_responsible_flags, max_overlaps, argmax_overlaps, pos_iou_thr):
pos_inds = (max_overlaps > pos_iou_thr) & box_responsible_flags.type(torch.bool)
argmax_overlaps = argmax_overlaps.to(input1.dtype)
input1[pos_inds] = argmax_overlaps[pos_inds] + 1
return input1.cpu().detach()
def custom_op_exec(self, input1, overlaps, box_responsible_flags, max_overlaps, argmax_overlaps,
gt_max_overlaps, gt_argmax_overlaps, num_gts, pos_iou_thr, min_pos_iou, gt_max_assign_all):
output = torch_npu.npu_grid_assign_positive(input1, overlaps, box_responsible_flags, max_overlaps,
argmax_overlaps, gt_max_overlaps, gt_argmax_overlaps, num_gts,
pos_iou_thr, min_pos_iou, gt_max_assign_all)
return output.cpu().detach()
def test_npu_grid_assign_positive(self):
npu_input = torch.rand((4,), dtype=torch.float32).to("npu")
overlaps = torch.rand((2, 4), dtype=torch.float32).to("npu")
box_responsible_flags = torch.tensor([1, 1, 1, 0], dtype=torch.uint8).to("npu")
max_overlaps = torch.rand((4,), dtype=torch.float32).to("npu")
argmax_overlaps = torch.tensor([1, 0, 1, 0], dtype=torch.int32).to("npu")
gt_max_overlaps = torch.rand((2,), dtype=torch.float32).to("npu")
gt_argmax_overlaps = torch.tensor([1, 0], dtype=torch.int32).to("npu")
num_gts = 128
pos_iou_thr = .5
min_pos_iou = .0
gt_max_assign_all = True
supported_output = self.supported_op_exec(npu_input, box_responsible_flags, max_overlaps,
argmax_overlaps, pos_iou_thr)
custom_output = self.custom_op_exec(npu_input, overlaps, box_responsible_flags, max_overlaps,
argmax_overlaps, gt_max_overlaps, gt_argmax_overlaps, num_gts,
pos_iou_thr, min_pos_iou, gt_max_assign_all)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()
+106
View File
@@ -0,0 +1,106 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestIFMR(TestCase):
def supported_op_exec(self, input1, data_min, data_max, cumsum, bins_num, min_percentile,
max_percentile, search_start, search_end, search_step, with_offset):
cdf = cumsum / torch.numel(input1)
max_index = torch.sum(torch.where(cdf >= max_percentile, 0, 1))
min_index = torch.sum(torch.where(cdf >= (1 - min_percentile), 0, 1))
max_init = max_index / torch.tensor([bins_num]).npu() * (data_max - data_min) + data_min
min_init = min_index / torch.tensor([bins_num]).npu() * (data_max - data_min) + data_min
step = torch.arange(search_start, search_end, search_step)
step = step.to('npu')
if with_offset:
if max_init < 0:
max_init = torch.tensor([0]).npu()
if min_init > 0:
min_init = torch.tensor([0]).npu()
min_list = min_init * torch.ones(step.shape).npu()
else:
max_init = torch.max(torch.abs(max_init), torch.abs(min_init))
max_list = max_init * step
if with_offset:
scale = (max_list - min_list) / torch.tensor([255]).npu()
scale = torch.where(scale < 1.192092896e-07, torch.ones([1]).npu(), scale)
offset = torch.round(min_list / scale)
offset = -(offset + 128)
else:
scale = max_list / torch.tensor([127]).npu()
offset = torch.round(scale * 0)
loss_list = torch.zeros(step.shape)
for i in range(torch.numel(step)):
quant_data = torch.round(input1 / scale[i]) + offset[i]
quant_data = quant_data.clip(-128, 127)
quant_data = (quant_data - offset[i]) * scale[i]
loss_list[i] = torch.sum(torch.square(quant_data - input1))
index = torch.argmin(loss_list)
return scale[index].cpu().detach(), offset[index].cpu().detach()
def custom_op_exec(self, input1, data_min, data_max, cumsum, min_percentile, max_percentile, search_start,
search_end, search_step, with_offset):
scale, offset = torch_npu.npu_ifmr(input1, data_min, data_max, cumsum, min_percentile, max_percentile,
search_start, search_end, search_step, with_offset)
return scale.cpu().detach(), offset.cpu().detach()
def test_npu_ifmr(self, device="npu"):
item = [np.float32, 0, (2, 2, 4, 4)]
_, npu_input = create_common_tensor(item, -1, 1)
bins_num = 128
min_percentile = 0.999999
max_percentile = 0.999999
search_start = 0.7
search_end = 1.3
search_step = 0.01
with_offset = False
data_min = torch.min(npu_input)
data_max = torch.max(npu_input)
data_min = torch.reshape(data_min, (1,))
data_max = torch.reshape(data_max, (1,))
hist = torch.histc(npu_input.to('cpu'),
bins=bins_num,
min=data_min[0].to('cpu'),
max=data_max[0].to('cpu'))
cumsum = torch.cumsum(hist, dim=0).int()
cumsum = cumsum.to('npu')
supported_scale, supported_offset = self.supported_op_exec(npu_input, data_min, data_max, cumsum, bins_num,
min_percentile, max_percentile, search_start,
search_end, search_step, with_offset)
custom_scale, custom_offset = self.custom_op_exec(npu_input, data_min, data_max, cumsum, min_percentile,
max_percentile, search_start, search_end, search_step,
with_offset)
self.assertRtolEqual(supported_scale, custom_scale[0])
self.assertRtolEqual(supported_offset, custom_offset[0])
if __name__ == "__main__":
run_tests()
+94
View File
@@ -0,0 +1,94 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.decorator import Dtypes, instantiate_tests
@instantiate_tests
class TestNpuIndexing(TestCase):
def _split_npu_indexing(self,
mat,
begin,
end,
strides,
begin_mask=0,
end_mask=0,
ellipsis_mask=0,
new_axis_mask=0,
shrink_axis_mask=0):
if begin_mask or end_mask or ellipsis_mask or new_axis_mask or new_axis_mask or shrink_axis_mask:
raise "Error: Unknown arguments."
dims = mat.size()
dim_num = len(dims)
for i in range(dim_num):
index_i = [j for j in range(begin[i], end[i], strides[i])]
mat = torch.index_select(input=mat,
dim=i,
index=torch.tensor(index_i, device="npu"))
return mat
def _split_npu_indexing_out(self,
mat,
begin,
end,
strides,
begin_mask=0,
end_mask=0,
ellipsis_mask=0,
new_axis_mask=0,
shrink_axis_mask=0,
out=None):
if begin_mask or end_mask or ellipsis_mask or new_axis_mask or new_axis_mask or shrink_axis_mask:
raise "Error: Unknown arguments."
dims = mat.size()
dim_num = len(dims)
for i in range(dim_num):
index_i = [j for j in range(begin[i], end[i], strides[i])]
mat = torch.index_select(input=mat,
dim=i,
index=torch.tensor(index_i, device="npu"))
out = mat.clone()
return out
def npu_op_exec(self, mat, begin, end, strides):
output = torch.npu_indexing(mat, begin, end, strides)
return output
def split_op_exec(self, mat, begin, end, strides):
output = self._split_npu_indexing(mat, begin, end, strides)
return output
@Dtypes(torch.float, torch.half, torch.int32, torch.uint8, torch.int8, torch.int16, torch.long)
def test_slice(self, dtype):
input_data = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]).npu().to(dtype)
split_out = self.split_op_exec(input_data, [0, 0], [2, 2], [1, 1])
exp_out = self.npu_op_exec(input_data, [0, 0], [2, 2], [1, 1])
self.assertRtolEqual(split_out, exp_out)
input_data = torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]]).npu().to(dtype)
split_out = self.split_op_exec(input_data, [0, 0, 0], [2, 2, 2], [1, 1, 1])
exp_out = self.npu_op_exec(input_data, [0, 0, 0], [2, 2, 2], [1, 1, 1])
self.assertRtolEqual(split_out, exp_out)
if __name__ == "__main__":
run_tests()
+89
View File
@@ -0,0 +1,89 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestNpuIou(TestCase):
def npu_iou(self, bboxes, gtboxes, mode=0):
def box_area(boxes):
return (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
# Logics here have some differents from torchvision.
lt = torch.max(bboxes[:, :2], gtboxes[:, None, :2])
rb = torch.min(bboxes[:, 2:], gtboxes[:, None, 2:])
wh = torch.clamp(rb - lt, min=0)
inter = wh[:, :, 0] * wh[:, :, 1]
eps = 1e-7
if mode == 0:
b_area = box_area(bboxes)
gt_area = box_area(gtboxes)
iou = inter / (gt_area[:, None] + b_area - inter + eps)
return iou
else:
gt_area = box_area(gtboxes)
iof = inter / (gt_area[:, None] + eps)
return iof
def custom_op_exec(self, bboxes, gtboxes, mode=0):
output = self.npu_iou(bboxes, gtboxes, mode)
output = output.to("cpu")
output = output.numpy()
return output
def npu_op_exec(self, bboxes, gtboxes, mode=0):
output = torch_npu.npu_iou(bboxes, gtboxes, mode)
output = output.to("cpu")
output = output.numpy()
return output
def test_iou_fp16(self):
bboxes = torch.tensor([[0, 0, 10, 10],
[10, 10, 20, 20],
[32, 32, 38, 42]], dtype=torch.float16).to("npu")
gtboxes = torch.tensor([[0, 0, 10, 20],
[0, 10, 10, 10],
[10, 10, 20, 20]], dtype=torch.float16).to("npu")
output_npu = self.npu_op_exec(bboxes, gtboxes, 1)
output_custom = self.custom_op_exec(bboxes, gtboxes, 1)
self.assertRtolEqual(output_npu, output_custom)
output_npu = self.npu_op_exec(bboxes, gtboxes)
output_custom = self.custom_op_exec(bboxes, gtboxes)
self.assertRtolEqual(output_npu, output_custom)
def test_iou_fp16_pt(self):
bboxes = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]], dtype = torch.float16).npu()
gtboxes = torch.tensor([[1, 2, 3, 4],
[5, 6, 7, 8]], dtype = torch.float16).npu()
output_npu = self.npu_op_exec(bboxes, gtboxes, 1)
output_custom = self.custom_op_exec(bboxes, gtboxes, 1)
self.assertRtolEqual(output_npu, output_custom)
output_npu = self.npu_op_exec(bboxes, gtboxes)
output_custom = self.custom_op_exec(bboxes, gtboxes)
self.assertRtolEqual(output_npu, output_custom)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,45 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestLayernormeval(TestCase):
def supported_op_exec(self, input1, normalized_shape, weight, bias, eps):
result, _, _ = torch.native_layer_norm(input1, normalized_shape, weight, bias, eps)
return result
def custom_op_exec(self, input1, normalized_shape, weight, bias, eps):
return torch_npu.npu_layer_norm_eval(input1, normalized_shape, weight, bias, eps)
def test_npu_layer_norm_eval(self, device="npu"):
input1 = torch.rand((6, 4), dtype=torch.float32).npu()
normalized_shape = input1.size()[1:]
weight = torch.Tensor(*normalized_shape).npu()
bias = torch.Tensor(*normalized_shape).npu()
supported_result = self.supported_op_exec(input1, normalized_shape, weight, bias, 1e-5)
custom_result = self.custom_op_exec(input1, normalized_shape, weight, bias, 1e-5)
self.assertRtolEqual(supported_result, custom_result)
if __name__ == "__main__":
run_tests()
+142
View File
@@ -0,0 +1,142 @@
# Copyright (c) 2023, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch import _VF
from torch_npu.testing.common_utils import create_common_tensor
from torch_npu.testing.testcase import TestCase, run_tests
class TestLSTM(TestCase):
def cpu_to_exec(self, input_data, weight, bias, seq_len, h, c, has_biases=True,
num_layers=1, dropout=0.0, train=True, bidirectional=False,
batch_first=False, flag_seq=False, direction=False):
"""
def lstm(
data: Tensor,
batch_sizes: Tensor,
hx: Union[Tuple[Tensor, ...], List[Tensor]],
params: Union[Tuple[Tensor, ...], List[Tensor]],
has_biases: _bool,
num_layers: _int,
dropout: _float,
train: _bool,
bidirectional: _bool
) -> Tuple[Tensor, Tensor, Tensor]: ...
result = _VF.lstm(input, batch_sizes, hx, self._flat_weights, self.bias,
self.num_layers, self.dropout, self.training, self.bidirectional)
def lstm(
input: Tensor,
hx: Union[Tuple[Tensor, ...], List[Tensor]],
params: Union[Tuple[Tensor, ...], List[Tensor]],
has_biases: _bool,
num_layers: _int,
dropout: _float,
train: _bool,
bidirectional: _bool,
batch_first: _bool
) -> Tuple[Tensor, Tensor, Tensor]: ...
result = _VF.lstm(input, hx, self._flat_weights, self.bias, self.num_layers,
self.dropout, self.training, self.bidirectional, self.batch_first)
"""
input_size = input_data.shape[-1]
weight_ih = weight[:input_size, :]
weight_hh = weight[input_size:, :]
weight_ih = weight_ih.transpose(0, 1)
weight_hh = weight_hh.transpose(0, 1)
bias_ih = bias
bias_hh_shape = bias_ih.shape
_, bias_hh = create_common_tensor(["float16", 2, bias_hh_shape], 0, 0) # zeros
weights = (weight_ih, weight_hh, bias_ih, bias_hh)
ret = _VF.lstm(input_data, (h, c), weights, has_biases, num_layers,
dropout, train, bidirectional, batch_first)
output, hn, hc = ret[0], ret[1], ret[2]
return output, hn, hc
def npu_to_exec(self, input_data, weight, bias, seq_len, h, c, has_biases=True,
num_layers=1, dropout=0.0, train=True, bidirectional=False,
batch_first=False, flag_seq=False, direction=False):
"""
npu_lstm(
Tensor input,
Tensor weight,
Tensor bias,
Tensor seqMask,
Tensor h,
Tensor c,
bool has_biases,
int num_layers,
float dropout,
bool train,
bool bidirectional,
bool batch_first,
bool flagSeq,
bool direction)
-> Tensor[] # yOutput, hOutput, cOutput, iOutput, jOutput, fOutput, oOutput, tanhc
"""
result = torch_npu.npu_lstm(input_data, weight, bias, seq_len, h, c,
has_biases, num_layers, dropout, train,
bidirectional, batch_first, flag_seq, direction)
y, h, c = result[0], result[1], result[2]
return y, h, c
def test_lstm_single_direction(self):
input_size = 10
hidden_size = 5
num_layers = 1
batch_szie = 3
seq_length = 5
bidirectional = False
d = 2 if bidirectional else 1
seq_length_t = torch.Tensor((seq_length)).int().npu()
input_shape = (seq_length, batch_szie, input_size)
h0_shape = (d * num_layers, batch_szie, hidden_size)
c0_shape = (d * num_layers, batch_szie, hidden_size)
_, input_data = create_common_tensor(["float16", 29, input_shape], -1, 1)
_, h0_data = create_common_tensor(["float16", 29, h0_shape], -1, 1)
_, c0_data = create_common_tensor(["float16", 29, c0_shape], -1, 1)
_, weight_ih = create_common_tensor(["float16", 2, (input_size, 4 * hidden_size)], -1, 1)
_, weight_hh = create_common_tensor(["float16", 2, (hidden_size, 4 * hidden_size)], -1, 1)
_, bias_ih = create_common_tensor(["float16", 2, (4 * hidden_size)], 0, 1)
weight = torch.cat((weight_ih, weight_hh), dim=0)
bias = bias_ih
# cpu
cpu_out, cpu_hn, cpu_cn = self.cpu_to_exec(input_data, weight, bias, seq_length_t,
h0_data, c0_data, has_biases=True)
# npu
npu_out, npu_hn, npu_cn = self.npu_to_exec(input_data, weight, bias, seq_length_t,
h0_data, c0_data, has_biases=True)
cpu_out = cpu_out.cpu().detach().numpy()
cpu_hn = cpu_hn.cpu().detach().numpy()
cpu_cn = cpu_cn.cpu().detach().numpy()
npu_out = npu_out.cpu().detach().numpy()
npu_hn = npu_hn.cpu().detach().numpy()
npu_cn = npu_cn.cpu().detach().numpy()
self.assertRtolEqual(cpu_out, npu_out)
self.assertRtolEqual(cpu_hn[-1], npu_hn[-1])
self.assertRtolEqual(cpu_cn[-1], npu_cn[-1])
if __name__ == "__main__":
run_tests()
+52
View File
@@ -0,0 +1,52 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestMax(TestCase):
def supported_op_exec(self, input1, dim, keepdim):
if isinstance(dim, str):
input1.names = ('N', 'C', 'H', 'W')
dim = input1.names.index(dim)
values, indices = torch.max(input1, dim, keepdim)
indices = indices.to(torch.int32)
return values.cpu().detach(), indices.cpu().detach()
def custom_op_exec(self, input1, dim, keepdim):
values, indices = torch_npu.npu_max(input1, dim, keepdim)
return values.cpu().detach(), indices.cpu().detach()
def test_npu_max(self, device="npu"):
item = [np.float32, 0, (2, 2, 2, 2)]
_, npu_input = create_common_tensor(item, -1, 1)
dims = (2, 'H')
keepdim = False
for dim in dims:
supported_values, supported_indices = self.supported_op_exec(npu_input, dim, keepdim)
custom_values, custom_indices = self.custom_op_exec(npu_input, dim, keepdim)
self.assertRtolEqual(supported_values, custom_values)
self.assertRtolEqual(supported_indices, custom_indices)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,114 @@
# Copyright (c) 2023, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
import torch.nn.functional as F
from torch_npu.testing.common_utils import create_common_tensor
from torch_npu.testing.testcase import TestCase, run_tests
FORMAT_ND = 2
FORMAT_NZ = 29
class TestMultiHeadAttention(TestCase):
def matmul_transpose(self, tensor1, tensor2):
return torch.matmul(tensor1, tensor2.transpose(-2, -1))
def non_convergence_exec(self, query, key, value, query_weight, key_weight, value_weight, attn_mask,
out_proj_weight, query_bias, key_bias, value_bias, out_proj_bias, drop_mask, batch,
attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float):
embed_dim = query.size()[-1]
q = torch_npu.npu_linear(query, query_weight, query_bias)
k = torch_npu.npu_linear(key, key_weight, key_bias)
v = torch_npu.npu_linear(value, value_weight, value_bias)
q *= (attn_dim_per_head ** -0.5)
new_shape = (batch, tgt_len, attn_head_num, attn_dim_per_head)
perm = (0, 2, 1, 3)
if k is not None:
key_shape = (batch, src_len, attn_head_num, attn_dim_per_head)
q = q.npu_confusion_transpose(perm, new_shape, False)
if k is not None:
k = k.npu_confusion_transpose(perm, key_shape, False)
if v is not None:
v = v.npu_confusion_transpose(perm, key_shape, False)
attn_batch1 = self.matmul_transpose(q, k)
attn_weights = attn_batch1.view(batch, attn_head_num, tgt_len, src_len)
attn_adds = attn_weights + attn_mask
attn_weights_float = F.softmax(attn_adds, dim=-1, dtype=torch.float32)
attn_softmax = attn_weights_float.to(attn_weights.dtype)
attn_probs, dropout_mask = torch_npu._npu_dropout(
attn_softmax, p=dropout_prob)
attn_batch2 = torch.matmul(attn_probs, v)
context = attn_batch2.npu_confusion_transpose(perm, (attn_batch2.size()[0] * attn_batch2.size()[2], embed_dim),
True)
attn = torch_npu.npu_linear(context, out_proj_weight, out_proj_bias)
return attn, dropout_mask, q, k, v, attn_weights_float, attn_probs, context
def npu_exec(self, query, key, value, query_weight, key_weight, value_weight, attn_mask, out_proj_weight,
query_bias, key_bias, value_bias, out_proj_bias, drop_mask, batch,
attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float):
return torch_npu.npu_multi_head_attention(
query, key, value, query_weight, key_weight, value_weight, attn_mask, out_proj_weight,
query_bias, key_bias, value_bias, out_proj_bias, drop_mask,
attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float)
def test_npu_multi_head_attention(self):
batch = 8
attn_head_num = 16
attn_dim_per_head = 64
src_len = 64
tgt_len = 64
dropout_prob = 0.0
softmax_use_float = True
weight_col = attn_head_num * attn_dim_per_head
_, query = create_common_tensor(["float16", FORMAT_NZ, (batch * tgt_len, weight_col)], -1, 1)
_, key = create_common_tensor(["float16", FORMAT_NZ, (batch * src_len, weight_col)], -1, 1)
_, value = create_common_tensor(["float16", FORMAT_NZ, (batch * src_len, weight_col)], -1, 1)
_, query_weight = create_common_tensor(["float16", FORMAT_NZ, (weight_col, weight_col)], -1, 1)
_, key_weight = create_common_tensor(["float16", FORMAT_NZ, (weight_col, weight_col)], -1, 1)
_, value_weight = create_common_tensor(["float16", FORMAT_NZ, (weight_col, weight_col)], -1, 1)
_, out_proj_weight = create_common_tensor(["float16", FORMAT_NZ, (weight_col, weight_col)], -1, 1)
_, attn_mask = create_common_tensor(["float16", FORMAT_ND, (batch, attn_head_num, tgt_len, src_len)], -1, 1)
_, query_bias = create_common_tensor(["float16", FORMAT_ND, (weight_col,)], -1, 1)
_, key_bias = create_common_tensor(["float16", FORMAT_ND, (weight_col,)], -1, 1)
_, value_bias = create_common_tensor(["float16", FORMAT_ND, (weight_col,)], -1, 1)
_, out_proj_bias = create_common_tensor(["float16", FORMAT_ND, (weight_col,)], -1, 1)
# cpu
cpu_result, cpu_dropout_mask, cpu_query_res, cpu_key_res, cpu_value_res, cpu_attn_scores, \
cpu_attn_res, cpu_context = self.non_convergence_exec(
query, key, value, query_weight, key_weight, value_weight, attn_mask,
out_proj_weight, query_bias, key_bias, value_bias, out_proj_bias, None, batch,
attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float)
cpu_result = cpu_result.cpu().numpy()
# npu
npu_result, npu_dropout_mask, npu_query_res, npu_key_res, npu_value_res, npu_attn_scores, \
npu_attn_res, npu_context = self.npu_exec(
query, key, value, query_weight, key_weight, value_weight, attn_mask,
out_proj_weight, query_bias, key_bias, value_bias, out_proj_bias, cpu_dropout_mask, batch,
attn_head_num, attn_dim_per_head, src_len, tgt_len, dropout_prob, softmax_use_float)
npu_result = npu_result.cpu().numpy()
self.assertRtolEqual(cpu_result, npu_result)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,59 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestNpuNmsRotated(TestCase):
def npu_op_exec(self, det, score):
output1, output2 = torch_npu.npu_nms_rotated(det.npu(), score.npu(), 0.2, 0, -1, 1)
return output1, output2
def test_npu_nms_rotated_float32(self):
det = torch.tensor([[1.0382e+03, 3.1657e+02, 1.1556e+03, 4.4303e+02, 2.3674e+00],
[1.1503e+03, 3.0598e+02, 1.2602e+03, 4.3456e+02, 3.2729e-01],
[1.1508e+03, 3.0652e+02, 1.2607e+03, 4.3472e+02, 5.1713e-01],
[1.1518e+03, 3.0781e+02, 1.2622e+03, 4.3448e+02, 3.9718e-01],
[1.1748e+03, 3.0202e+02, 1.2859e+03, 4.3915e+02, 1.8112e+00],
[1.1711e+03, 3.0480e+02, 1.2868e+03, 4.3551e+02, 2.1171e+00],
[1.1673e+03, 3.0675e+02, 1.2889e+03, 4.3194e+02, 2.5968e+00],
[1.2741e+03, 3.0181e+02, 1.3823e+03, 4.3036e+02, 2.0379e+00],
[1.2741e+03, 3.0286e+02, 1.3836e+03, 4.2940e+02, 2.2072e+00],
[1.2733e+03, 3.0382e+02, 1.3855e+03, 4.2846e+02, 2.0921e+00],
[1.2935e+03, 3.0517e+02, 1.3961e+03, 4.3137e+02, 2.9583e+00],
[1.4076e+03, 3.2173e+02, 1.4930e+03, 4.2714e+02, 2.6099e+00],
[1.4097e+03, 3.2496e+02, 1.4934e+03, 4.2651e+02, 3.0967e+00],
[1.4097e+03, 3.2569e+02, 1.4935e+03, 4.2632e+02, 2.5553e+00],
[1.0279e+03, 3.1883e+02, 1.1412e+03, 4.4646e+02, 1.2030e+00],
[1.0275e+03, 3.1776e+02, 1.1408e+03, 4.4641e+02, 1.2732e+00],
[1.0289e+03, 3.1694e+02, 1.1407e+03, 4.4510e+02, 9.4897e-01],
[1.0372e+03, 3.1233e+02, 1.1477e+03, 4.4521e+02, 1.4125e+00],
[1.0370e+03, 3.1564e+02, 1.1487e+03, 4.4317e+02, 1.6109e+00],
[1.0367e+03, 3.1682e+02, 1.1510e+03, 4.4020e+02, 1.4112e+00]])
score = torch.tensor([0.9910, 0.9854, 0.9972, 0.9930, 0.4282, 0.5092, 0.6532, 0.9965, 0.9989,
0.9976, 0.3144, 0.9874, 0.9980, 0.9967, 0.9698, 0.9824, 0.9474, 0.9856, 0.9964, 0.9926])
expect_output1 = torch.tensor([8, 12, 2, 18], dtype=torch.int32)
expect_output2 = torch.tensor([4], dtype=torch.int32)
npu_output1, npu_output2 = self.npu_op_exec(det, score)
self.assertRtolEqual(expect_output1, npu_output1.cpu())
self.assertRtolEqual(expect_output2, npu_output2.cpu())
if __name__ == "__main__":
run_tests()
+48
View File
@@ -0,0 +1,48 @@
# Copyright (c) 2020, Huawei Technologies.All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch.nn.functional as F
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
class TestNpuPad(TestCase):
def custom_pad(self, input_data, pads):
new_pads = pads[2:] + pads[:2]
output = F.pad(input_data, new_pads, "constant", 0)
return output
def custom_op_exec(self, input_data, pads):
output = self.custom_pad(input_data, pads)
return output.cpu().numpy()
def npu_op_exec(self, input_data, pads):
output = torch_npu.npu_pad(input_data, pads)
return output.cpu().numpy()
def test_npu_pad(self):
npu_input = torch.randn(2, 3).npu()
pads_list = [(1, 1, 1, 1), (1, 2, 3, 4)]
for pads in pads_list:
custom_output = self.custom_op_exec(npu_input, pads)
npu_output = self.npu_op_exec(npu_input, pads)
self.assertRtolEqual(custom_output, npu_output)
if __name__ == "__main__":
run_tests()
@@ -0,0 +1,109 @@
# Copyright (c) 2023 Huawei Technologies Co., Ltd
# All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import numpy as np
import torch
import torch_npu
from torch_npu.testing.testcase import TestCase, run_tests
from torch_npu.testing.common_utils import create_common_tensor
class TestPSROIPooling(TestCase):
def cal_sum(self, hstart, hend, wstart, wend, image):
out_sum = 0.0
for row in range(hstart, hend):
for col in range(wstart, wend):
out_sum += image[row][col]
return out_sum
def supported_op_exec(self, input1, rois, spatial_scale, group_size, output_dim):
dst_type = input1.dtype
if dst_type != torch.float32:
input1 = input1.to(torch.float32)
rois = rois.to(torch.float32)
n, channels, height, width = input1.shape
tensor_height = torch.tensor([height]).npu()
tensor_width = torch.tensor([width]).npu()
tensor_zero = torch.tensor([0]).npu()
tensor_one_tenth = torch.tensor([0.1]).npu()
output_size = [rois.size(0) * rois.size(2), output_dim, group_size, group_size]
rois = rois.transpose(2, 1)
rois = torch.reshape(rois, (rois.shape[0] * rois.shape[1], rois.shape[2]))
output = torch.zeros(output_size).npu()
for out_n in range(output_size[0]):
for ctop in range(output_size[1]):
for ph in range(output_size[2]):
for pw in range(output_size[3]):
roi_batch_ind = rois[out_n][0].to(int)
roi_start_w = torch.round(rois[out_n][1]) * spatial_scale
roi_start_h = torch.round(rois[out_n][2]) * spatial_scale
roi_end_w = torch.round(rois[out_n][3] + 1.0) * spatial_scale
roi_end_h = torch.round(rois[out_n][4] + 1.0) * spatial_scale
# Force too small ROIs to be 1x1
roi_width = torch.max(roi_end_w - roi_start_w, tensor_one_tenth)
roi_height = torch.max(roi_end_h - roi_start_h, tensor_one_tenth)
# Compute w and h at bottom
bin_size_h = roi_height / group_size
bin_size_w = roi_width / group_size
# Add roi offsets and clip to input boundaries
hstart = (ph * bin_size_h + roi_start_h).to(int)
wstart = torch.floor(pw * bin_size_w + roi_start_w).to(int)
hend = torch.ceil((ph + 1) * bin_size_h + roi_start_h).to(int)
wend = torch.ceil((pw + 1) * bin_size_w + roi_start_w).to(int)
hstart = torch.min(torch.max(hstart, tensor_zero), tensor_height).to(int)
hend = torch.min(torch.max(hend, tensor_zero), tensor_height).to(int)
wstart = torch.min(torch.max(wstart, tensor_zero), tensor_width).to(int)
wend = torch.min(torch.max(wend, tensor_zero), tensor_width).to(int)
is_empty = ((hend <= hstart) or (wend <= wstart))
c = (ctop * group_size + ph) * group_size + pw
out_sum = self.cal_sum(hstart,
hend,
wstart,
wend,
image=input1[roi_batch_ind][c])
bin_area = (hend - hstart) * (wend - wstart)
if is_empty:
output[out_n][ctop][ph][pw] = 0.0
else:
output[out_n][ctop][ph][pw] = out_sum / bin_area
if dst_type != torch.float32:
output = output.to(dst_type)
return output.cpu().detach()
def custom_op_exec(self, input1, rois, spatial_scale, group_size, output_dim):
output = torch_npu.npu_ps_roi_pooling(input1, rois, spatial_scale, group_size, output_dim)
return output.cpu().detach()
def test_npu_ps_roi_pooling(self, device="npu"):
item = [np.float32, 0, (2, 961, 127, 127)]
_, npu_input = create_common_tensor(item, 0.1, 1)
rois = torch.tensor([[[0], [3], [2], [9], [9]], [[1], [1], [4], [9], [9]]], dtype=torch.float32).npu()
spatial_scale = 0.25
group_size = 31
output_dim = 1
supported_output = self.supported_op_exec(npu_input, rois, spatial_scale, group_size, output_dim)
custom_output = self.custom_op_exec(npu_input, rois, spatial_scale, group_size, output_dim)
self.assertRtolEqual(supported_output, custom_output)
if __name__ == "__main__":
run_tests()

Some files were not shown because too many files have changed in this diff Show More