Compare commits

...
393 Commits
Author SHA1 Message Date
sunxinlei 304b1c1920 Add shutdown_stats to prevent entering the insert_events 2023-07-06 12:38:41 +08:00
weili10 79dcefe940 回退 'Pull Request !3631 : [Feature]: add the supports of hostapi - 0528' 2023-05-31 06:20:58 +00:00
i-robot 01c4519698 !3643 [BugFix] Fix max_pool2d_with_indices to support 3D-input.
Merge pull request !3643 from 戢芳/pool1.11
2023-05-31 03:33:54 +00:00
i-robot 5146610dd5 !3595 [Fix] fix bug of event reuse by reset event.
Merge pull request !3595 from 王强/v1.11.0
2023-05-31 02:27:31 +00:00
weili10 e376f63184 回退 'Pull Request !3666 : [Fix] add Release for aclBoolArray' 2023-05-31 01:29:42 +00:00
i-robot 4bd5f972a6 !3662 [Fix] Use raw_delete instead of NPUCachingDeleter
Merge pull request !3662 from 刘嘉巍/1.11-load
2023-05-30 12:10:14 +00:00
i-robot 1662112d8f !3666 [Fix] add Release for aclBoolArray
Merge pull request !3666 from 周奇龙/v1.11.0
2023-05-30 08:42:59 +00:00
pipihugh ab02634268 Fix max_pool2d_with_indices to support 3D-input. 2023-05-30 14:47:28 +08:00
zhouqilong 9d3e2aca99 release for aclBoolArray 2023-05-30 13:56:44 +08:00
刘嘉巍 83305a9227 Use raw_delete instead of NPUCachingDeleter 2023-05-30 09:46:23 +08:00
i-robot da6314fe79 !3634 Remove fp16 cast of gather.
Merge pull request !3634 from 王晓/gather_1.11_1
2023-05-30 01:39:18 +00:00
i-robot f68a31faa9 !3611 add check for bmm ops
Merge pull request !3611 from chenzijian/czj111-t
2023-05-29 12:03:03 +00:00
wbigat dfc17957e3 [Fix] fix bug of event reuse by reset event. 2023-05-29 16:38:17 +08:00
i-robot 57b0a01a51 !3619 Unify variable naming.
Merge pull request !3619 from Leon/111_new
2023-05-29 07:57:25 +00:00
chenzijian affda5d278 add check for bmm ops 2023-05-29 15:51:57 +08:00
i-robot d01615a025 !3605 Fixed _DDPJoinHook undefined.
Merge pull request !3605 from 王夏夏/v1.11.0
2023-05-29 06:37:42 +00:00
wangxiao 35a9be8e91 Remove fp16 cast of gather. 2023-05-29 10:38:41 +08:00
i-robot 3c84835e76 !3631 【Feature】: add the supports of hostapi - 0528
Merge pull request !3631 from ckirchhoff/v1.11.0-0528
2023-05-28 05:54:04 +00:00
ckirchhoff cf4602d7fd [Feature]: add supports of hostapi 2023-05-28 09:41:00 +08:00
尤安升 af506edc50 update OWNERS. 2023-05-27 11:42:56 +00:00
i-robot 9e06a434b2 !3599 Instead TORCH_CHECK with runtime_error
Merge pull request !3599 from sunjiayang/v1.11.0-warningapi
2023-05-27 11:22:12 +00:00
liangyunfan 876dc47d51 unify variable naming. 2023-05-27 17:57:28 +08:00
i-robot 7b0939def6 !3609 fix calling geinit more than once when sympy pkg is not installed.
Merge pull request !3609 from Leon/111_
2023-05-27 09:25:33 +00:00
sunxinlei c5dcb2a484 [DFX] Instead TORCH_CHECK with runtime_error 2023-05-27 11:40:11 +08:00
liangyunfan 45ce39039b fix calling geinit more than once when sympy pkg is not installed. 2023-05-27 10:25:24 +08:00
i-robot 2bc3b3eb64 !3426 adapt is_pinned function
Merge pull request !3426 from 王广斌/adapt_is_pinned
2023-05-27 00:53:52 +00:00
i-robot 16e989e726 !3523 [PTA] Warning fix
Merge pull request !3523 from sunjiayang/v1.11.0-package
2023-05-26 09:30:44 +00:00
xiaxia3 577860d35c Fixed _DDPJoinHook undefined. 2023-05-26 17:02:32 +08:00
sunxinlei 1d5f5c256b [PTA] Warning fix 2023-05-26 16:46:13 +08:00
i-robot 29cf9f9731 !3602 [Feature] Support op api feature.
Merge pull request !3602 from will-devil/hostapi111
2023-05-26 03:51:07 +00:00
wangyicheng 5fa74ae2bf Support op api feature. 2023-05-26 09:59:02 +08:00
i-robot 6853bea62c !3580 fix gather element bug + fix index interrupt graph bug when index is int/long
Merge pull request !3580 from 詹隽/fix_gather_bug_v1.11.0
2023-05-25 15:21:04 +00:00
i-robot bf2e368e9e !3587 fix masked_fill ops when the inputs are placed on different devices.
Merge pull request !3587 from Leon/111
2023-05-25 12:20:41 +00:00
i-robot 97408652d2 !3560 [Feature] Add remaining generator file & Refactor fast_gelu
Merge pull request !3560 from 刘嘉巍/1.11-codegen
2023-05-25 11:42:31 +00:00
liangyunfan e46d1d858a fix masked_fill ops when the inputs are placed on different devices. 2023-05-25 11:22:00 +08:00
i-robot 136f595bff !3571 [Fix] Set HF32 default value of matmul to False in all version.
Merge pull request !3571 from 王强/v1.11.0
2023-05-25 01:13:19 +00:00
zhanjun ad98a6df3d fix gather element bug 2023-05-24 20:26:22 +08:00
zhanjun 84eafd7023 fix index interrupt graph bug when index is int/long 2023-05-24 20:25:55 +08:00
i-robot 7e588d48be !3547 [BugFix]Fix the output type of mul_out.
Merge pull request !3547 from 戢芳/mul1.11
2023-05-24 09:59:14 +00:00
wbigat 67fadc1559 [Fix] Set HF32 default value of matmul to False in all version. 2023-05-24 16:42:22 +08:00
刘嘉巍 c489360227 Add rest generator file & test with fast_gelu 2023-05-24 11:15:18 +08:00
i-robot 1bd634c092 !3563 [BugFix] Fix torch.all for supporting all dtypes.
Merge pull request !3563 from YUANCHUN/All_1.11
2023-05-23 13:07:46 +00:00
i-robot f030743edf !3484 [Refactor] ignore warning info when override operator for cpu implement
Merge pull request !3484 from 施博/fix_warning_v1.11
2023-05-23 12:05:46 +00:00
i-robot ccb53d7c16 !3425 [DFX] optimize the output of ut
Merge pull request !3425 from weili10/v1.11.0
2023-05-23 11:28:41 +00:00
i-robot 120b602ba8 !3538 [bugfix] Spelling error.
Merge pull request !3538 from will-devil/bf111
2023-05-23 11:07:10 +00:00
Rayyyy 18682df054 Fix torch.all for supporting all dtypes. 2023-05-23 19:04:23 +08:00
i-robot 03683b4d47 !3130 add test cases for xavier_uniform_.
Merge pull request !3130 from 王夏夏/v1.11.0
2023-05-23 08:59:34 +00:00
wangyicheng 6b9284c55e Bugfix. 2023-05-23 16:19:57 +08:00
pipihugh 139aebde18 Fix the output type of mul_out. 2023-05-23 14:29:08 +08:00
i-robot 7e19fd8b91 !3514 Delete the device index check ut for empty_with_format.
Merge pull request !3514 from Leon/111_fix
2023-05-23 06:21:16 +00:00
i-robot 323dd633d1 !3524 Add Operator::SetAttr for ListListInt type
Merge pull request !3524 from 陈瑛琰/v1.11.0
2023-05-23 00:52:59 +00:00
weili10 f7d8433f33 optimize ut output 2023-05-22 20:57:04 +08:00
c00659642 c1e9625f89 Add Operator::SetAttr for ListListInt type 2023-05-22 17:09:38 +08:00
i-robot d974ab78de !3448 add testcase for FusedColorJitter.
Merge pull request !3448 from 王夏夏/v1.11.0
2023-05-22 07:21:19 +00:00
liangyunfan 8a717bf965 delete index check UT of empty_with_format. 2023-05-22 15:12:21 +08:00
i-robot c5df068ed0 !3454 Add SetAttr for ListListInt type
Merge pull request !3454 from 陈瑛琰/v1.11.0
2023-05-22 07:02:57 +00:00
c00659642 77fcfabe1e Add SetAttr for ListListInt type 2023-05-22 11:36:32 +08:00
i-robot fd1b0557a3 !3392 [Fix] Fix attribute check of fused optimizers
Merge pull request !3392 from 郭鹏/v1.11.0
2023-05-22 01:48:17 +00:00
i-robot 65fe503c24 !3500 图模式增加选项指定topo排序选项,同时设置topo选项为逆DFS
Merge pull request !3500 from 詹隽/option_1.11.0
2023-05-20 10:34:49 +00:00
zhanjun 34404edd2e add topoSortingMode option for graph mode 2023-05-20 15:22:48 +08:00
shibo 26797f41a8 remove warning info when override operator for cpu 2023-05-20 11:40:27 +08:00
i-robot 0d0dcff1ab !3494 [Fix] Fix bug in warning decorator.
Merge pull request !3494 from 刘嘉巍/1.11-warn
2023-05-19 07:47:34 +00:00
刘嘉巍 f2b3dbb536 Fix bug in warning decorator 2023-05-19 15:17:10 +08:00
i-robot a3e9149254 !3491 [Fix] Warning once when using deprecated calling method
Merge pull request !3491 from 刘嘉巍/1.11-dev
2023-05-19 04:49:31 +00:00
刘嘉巍 ba24f74264 Warning once when using deprecated calling method 2023-05-19 12:20:37 +08:00
i-robot 4d84ffa349 !3475 【Graph mode】Avoid operator(MM\BMM) infershape error
Merge pull request !3475 from 詹隽/dev_1.11
2023-05-19 04:03:36 +00:00
i-robot 13d6d9d3fb !2825 [Bugfix] throw error when PAT version mismatch
Merge pull request !2825 from darin123/v1.11.0
2023-05-19 01:25:17 +00:00
i-robot d9f6c20251 !3450 Fix logger is null.
Merge pull request !3450 from shaoyf/fix/dev_logger
2023-05-18 13:50:37 +00:00
i-robot 793cfa0051 !3474 Revert 'Pull Request !3382 : delete pin_memory and is_pinned warning'
Merge pull request !3474 from weili10/revert-merge-3382-v1.11.0
2023-05-18 12:59:52 +00:00
zhanjun cc6eea5c82 Avoid operator(MM\BMM) infershape error 2023-05-18 20:43:53 +08:00
i-robot b0ac9888a7 !3462 [DFX]Add runtime check
Merge pull request !3462 from sunjiayang/v1.11.0-package
2023-05-18 12:41:35 +00:00
i-robot cb4e26deeb !3468 Fix bug of indexput
Merge pull request !3468 from chlme16/indexput11
2023-05-18 12:37:57 +00:00
weili10 926d82e7af Revert 'Pull Request !3382 : delete pin_memory and is_pinned warning' 2023-05-18 12:34:15 +00:00
i-robot 8c2ff96724 !3191 [Feature] Add warning for custom methods.
Merge pull request !3191 from 刘嘉巍/1.11-dev
2023-05-18 12:15:39 +00:00
chlme16 a9c484f1b1 Fix bug of indexput 2023-05-18 19:00:09 +08:00
i-robot 653b277b36 !3370 [Fix] Reduce redundant copy with optimized format_contiguous
Merge pull request !3370 from 郭鹏/v1.11.0-optim_copy
2023-05-18 10:54:56 +00:00
i-robot 7de0f7c5e2 !3347 [Feature] Support tuple outputs backward.
Merge pull request !3347 from will-devil/tupleback
2023-05-18 09:02:13 +00:00
sunxinlei b23060a9f4 [DFX]Add runtime check 2023-05-18 16:36:39 +08:00
wangyicheng ee173a114a Support tuple output backward. 2023-05-18 14:48:22 +08:00
xiaxia3 1a5da3ea49 add test cases for xavier_uniform_. 2023-05-18 11:41:32 +08:00
shaoyf 1be5186e1c Fix logger is null. 2023-05-18 10:48:34 +08:00
xiaxia3 8fea6aa4e4 add testcase for FusedColorJitter. 2023-05-18 10:32:15 +08:00
i-robot 2b87ec310b !3409 [BugFix] Add checkout and check_match in bmm_out、cosh_out、cumsum_out、cumprod_out、erfinv_out、expm1_out.
Merge pull request !3409 from YUANCHUN/add_checkout_v1.11
2023-05-18 01:56:03 +00:00
i-robot 975c77d466 !3110 [Feature] torch.std add correction
Merge pull request !3110 from 詹昊/std_correction
2023-05-17 09:36:21 +00:00
i-robot 0ebb907c62 !3085 [DFX] CANN package check
Merge pull request !3085 from sunjiayang/v1.11.0-package
2023-05-17 07:57:29 +00:00
i-robot ebbd7f4278 !3129 [Feature] Load and preprocess yaml for autograd.
Merge pull request !3129 from 刘嘉巍/1.11-codegen
2023-05-17 06:22:13 +00:00
i-robot 5d65ce5d0e !3395 Supports op Histogram
Merge pull request !3395 from 蒋鹏军/v1.11.0
2023-05-17 04:02:57 +00:00
sunxinlei bafb482c30 [DFX] CANN package check 2023-05-17 11:42:47 +08:00
wgb 04afaf8923 adapt is_pinned function 2023-05-17 11:39:47 +08:00
i-robot 68b58e7b99 !3382 delete pin_memory and is_pinned warning
Merge pull request !3382 from 王广斌/del_pin_memory_warning
2023-05-16 15:18:04 +00:00
i-robot 6f180ff325 !3319 Fix bug of of indexput
Merge pull request !3319 from chlme16/indexput11
2023-05-16 15:13:31 +00:00
i-robot 5039749a1a !3386 NPU_CHECK() naming change
Merge pull request !3386 from chenzijian/czj111
2023-05-16 14:58:10 +00:00
i-robot cdfe6142f4 !3174 Broadcast of index.
Merge pull request !3174 from 王晓/index_broadcast_only_1.11
2023-05-16 12:48:31 +00:00
jiangpengjun1 ec2d71534b Title: Supports op Histogram
Type: Feature
Team:PyTorch_Ops_Dev

InventoryUpdate: True
Issue: issue_no

Description:
适配算子Histogram
2023-05-16 20:36:05 +08:00
i-robot 877aa41236 !3331 Profiler Memory Analyze Code
Merge pull request !3331 from 188******92/v1.11.0
2023-05-16 12:32:36 +00:00
zhanhao ee36446b85 [Feature] torch.std add correction 2023-05-16 20:21:02 +08:00
i-robot 93438b05b5 !3412 fix the UT for error interception
Merge pull request !3412 from Leon/111
2023-05-16 10:48:08 +00:00
Rayyyy 711df330a0 Add checkout and check_match in bmm_out、cosh_out、cumsum_out、cumprod_out、erfinv_out、expm1_out. 2023-05-16 18:21:20 +08:00
i-robot 33d417b0c8 !3312 [feat] support inf/nan in overflow detect
Merge pull request !3312 from xudaohong/v1.11.0
2023-05-16 09:32:40 +00:00
chlme16 dc1e741543 Fix bug of of indexput 2023-05-16 15:20:33 +08:00
x00430237 a8f26113fe [feat] support inf/nan in overflow detect
# Conflicts:
#	torch_npu/npu/amp/grad_scaler.py
2023-05-16 14:55:58 +08:00
liangyunfan b8a9c8e502 fix the UT for error interception. 2023-05-16 14:42:20 +08:00
gp513 7c60eadeef Optimize async copy in inplace-add 2023-05-16 11:03:37 +08:00
刘嘉巍 953e85bb51 Add warning for custom torch & tensor methods 2023-05-16 10:50:40 +08:00
i-robot 1a8ac6f700 !3365 Optimize error message in device num check.
Merge pull request !3365 from Leon/111
2023-05-16 02:13:58 +00:00
i-robot d0ce417e74 !3345 Add judgment condition before running distributed ut files.
Merge pull request !3345 from jiangpengfei/v1.11.0
2023-05-16 02:04:24 +00:00
i-robot 74d442d71c !3116 [DFX] Unsupport API
Merge pull request !3116 from sunjiayang/v1.11.0-unsupport
2023-05-15 13:05:40 +00:00
i-robot ec5559c8d8 !3376 modify onnx export symbol of npu_sign_bits_unpack
Merge pull request !3376 from Zhang Yingxin/up_master
2023-05-15 12:51:31 +00:00
sunboquan 118cc0ceea profiler_memory_analyze_code 2023-05-15 19:22:42 +08:00
sunxinlei e7b0a9bfab [DFX] Unsupport API 2023-05-15 18:18:35 +08:00
chenzijian 78de784489 NPU_CHECK naming change 2023-05-15 17:59:14 +08:00
gp513 f1616ae3ea fix attribute check of fused optimizers 2023-05-15 17:10:11 +08:00
j00810217 cc50209e76 Add judgment condition before running distributed ut files. 2023-05-15 17:05:37 +08:00
liangyunfan 28b1c31a28 Optimize error message in check_is valid. 2023-05-15 15:10:19 +08:00
i-robot 08b19d4bcc !3245 add C10D_HCCL_CHECK() error msg details
Merge pull request !3245 from chenzijian/czj111
2023-05-15 03:09:20 +00:00
wgb d542633e9a delete pin_memory and is_pinned warning 2023-05-15 10:15:45 +08:00
i-robot ee19239a40 !3351 Npu Profiler UT Code
Merge pull request !3351 from 周先琪/v1.11.0_dev2
2023-05-15 02:15:12 +00:00
i-robot 54d69a20ca !3227 [DVPP adaptation] DP process set TE_PARALLEL_COMPILER=1 && decode_jpeg add parameter try_recover_truncated
Merge pull request !3227 from 陈瑛琰/v1.11.0
2023-05-15 01:08:35 +00:00
zhang-aurora 339dec4ba1 modify onnx export symbol of npu_sign_bits_unpack 2023-05-13 18:02:03 +08:00
i-robot 98d2546ad9 !3360 Fix NPU selection 0 card 'set_device' failure issue
Merge pull request !3360 from louyujing/v1.11.0
2023-05-12 12:50:12 +00:00
i-robot 67e8722811 !3318 [Fix]Fix security vulnerabilities in torch.jit.annotations.parse_type_line.
Merge pull request !3318 from huangyunlong/1.11safe
2023-05-12 09:52:51 +00:00
huangyunlong c5efbc0e89 [Fix]Fix security vulnerabilities in torch.jit.annotations.parse_type_line. 2023-05-12 16:56:42 +08:00
zhouxianqi b776210b0b npu_profiler_ut_code 2023-05-12 16:56:27 +08:00
i-robot 8083ce705c !3332 [Feature] Update replay graph and optimze memory usage.
Merge pull request !3332 from 王强/cherry-pick-1683795303
2023-05-12 08:45:48 +00:00
l30044004 cb0bbee678 Fix NPU selection 0 card set_device failure issue 2023-05-12 16:37:03 +08:00
chenzijian 073554ad2d add hcclresult err msg details and complement error code map 2023-05-12 15:32:47 +08:00
i-robot 5bbf0dd4d3 !3163 The operator "OneHot" supports int64 output
Merge pull request !3163 from 陈龙胜/one_hot_1.11
2023-05-12 06:50:03 +00:00
i-robot d49da19ab4 !3300 The modified content is: torch.device maintains its original semantics on NPU and can only be replaced when used as an input parameter in the function
Merge pull request !3300 from louyujing/v1.11.0
2023-05-12 04:02:18 +00:00
i-robot 023a258644 !3271 UT modification: skip custom ops onnx export test related to conv.
Merge pull request !3271 from Leon/111
2023-05-12 02:53:12 +00:00
i-robot ce8cf517cf !3327 [DFX] fix the bug that testcase doesn't run with testing.run_test
Merge pull request !3327 from weili10/v1.11.0
2023-05-12 00:57:47 +00:00
weili10 29f0e092fe fix the bug that testcase doesn't run with testing.run_test 2023-05-11 20:17:29 +08:00
liangyunfan a0b7b96b6a UT modification: skip custom ops onnx export test related to conv. 2023-05-11 20:09:15 +08:00
i-robot 691a2b73fd !3313 Add a conversion type from complex Aten dtype to acl dtype
Merge pull request !3313 from 关龙锋/cherry-pick-1683787391
2023-05-11 11:21:24 +00:00
wbigat 356a29da7c fixed e0e2e82 from https://gitee.com/wbigat/pytorch_master_wq_2/pulls/3321
update replay graph and optimze memory usage.
2023-05-11 08:55:08 +00:00
i-robot 55e34b5a63 !3272 Format NZ cast dose not support one-dimensional tensor.
Merge pull request !3272 from jiangpengfei/directory_mapping
2023-05-11 08:54:00 +00:00
cls214 d59451b678 Add a new branch to make the operator support int64 output 2023-05-11 15:42:23 +08:00
guanlongfeng 1fd4234919 fixed 725540a from https://gitee.com/guan-longfeng/pytorch/pulls/3304
Add a conversion type from complex Aten dtype to acl dtype
2023-05-11 06:43:13 +00:00
l30044004 ec6c4f621c The modified content is: torch.device maintains its original semantics on NPU and can only be replaced when used as an input parameter in the function 2023-05-11 14:13:28 +08:00
i-robot a1df360e92 !3267 Profiler Front End Code
Merge pull request !3267 from 周先琪/v1.11.0_dev2
2023-05-11 03:28:44 +00:00
zhouxianqi afbcd275fc profiler_front_end_code 2023-05-11 10:14:58 +08:00
j00810217 83ff2ca5a2 Fix the test case(test_c10d.py). Format NZ cast dose not support one dimensional tensor. Change the tensor to 2 dimensions to support the private format NZ. 2023-05-11 10:04:31 +08:00
i-robot cd3a32e96b !3260 NPU Profiler CMake&Adapter file.
Merge pull request !3260 from 裘凯达/npu_profiler_1.11.0
2023-05-10 10:55:40 +00:00
裘凯达 e6271e18af NPU Profiling CMake&Adapter. 2023-05-10 16:33:15 +08:00
i-robot 54915aaaa8 !3211 Profiler Analysis Parser Part
Merge pull request !3211 from 周先琪/v1.11.0_dev1
2023-05-10 07:21:27 +00:00
i-robot 9ee8f1bc41 !3182 Replace aclrtSynchronizeStream with aclrtSynchronizeStreamWithTimeout.
Merge pull request !3182 from Leon/111
2023-05-09 09:28:49 +00:00
zhouxianqi 903e87e05f profiler_analysis_parser_part 2023-05-09 16:01:39 +08:00
i-robot 189b64ca02 !3185 Add warning in wrap_acc_cmp_hook
Merge pull request !3185 from sunjiayang/v1.11.0-warningapi
2023-05-09 06:48:04 +00:00
i-robot c78d94a819 !3181 NPU profiler data processing module
Merge pull request !3181 from fanxiaotong/v1.11.0
2023-05-09 03:41:25 +00:00
i-robot 1d7c9c9e6b !3132 Add Event call log
Merge pull request !3132 from sunjiayang/v1.11.0-eventlog
2023-05-09 02:25:02 +00:00
sunxinlei 32020c4c15 Add warning in wrap_acc_cmp_hook 2023-05-09 09:40:03 +08:00
i-robot c745b9b922 !3194 add C10_NPU_CHECK error msg details
Merge pull request !3194 from chenzijian/czj111
2023-05-09 01:38:15 +00:00
liangyunfan 61927f5646 Replace aclrtSynchronizeStream with aclrtSynchronizeStreamWithTimeout. 2023-05-09 09:18:39 +08:00
i-robot 88f64d090c !3238 Fix bug of argmin.
Merge pull request !3238 from 王晓/argmin_1.11
2023-05-08 15:05:34 +00:00
wangxiao 7630784a30 Fix bug of argmin. 2023-05-08 22:26:09 +08:00
fxt d968332a17 NPU profiler data processing module. 2023-05-08 20:29:59 +08:00
i-robot 2e0426fa6c !3169 Add interface for host-api OP
Merge pull request !3169 from 曾益刚/v1.11.0
2023-05-08 09:44:28 +00:00
“gchenzijian 5766d8c37e add NPU_CHECK error msg details 2023-05-08 17:03:15 +08:00
wangtao43 207cbb926e Add host-api interface 2023-05-08 15:54:17 +08:00
i-robot 80c6a58048 !3152 Map the modified files to the corresponding test cases
Merge pull request !3152 from jiangpengfei/directory_mapping
2023-05-08 07:37:43 +00:00
c00659642 3ec0058635 set TE_PARALLEL_COMPILER=1 && decode_jpeg add parameter try_recover_truncated 2023-05-08 15:33:51 +08:00
j00810217 0d86f9fae0 Map the modified files to the corresponding test cases 2023-05-06 18:58:03 +08:00
i-robot 0ff8f74699 !3009 Add device num check.
Merge pull request !3009 from Leon/111
2023-05-06 08:27:34 +00:00
i-robot b3b6b7cfcc !3137 [DFX] save test results to xml file in ci environment
Merge pull request !3137 from weili10/v1.11.0
2023-05-06 07:42:53 +00:00
i-robot 102c9e9b5d !2936 [Fix] amp_foreach_non_finite_check supports 1980B
Merge pull request !2936 from 王夏夏/v1.11.0_overflow
2023-05-06 07:05:11 +00:00
sunxinlei 9aafa48f70 Add Event call log 2023-05-06 14:40:11 +08:00
i-robot e6a9901a2c !3204 [Fix]Using AICPU kernel at indexput non-binary scene.
Merge pull request !3204 from 王晓歆/indexput_1.11
2023-05-06 06:20:03 +00:00
i-robot 7fed3531ab !3162 Modify onnx export of npu_sign_bits_unpack
Merge pull request !3162 from Zhang Yingxin/up_master
2023-05-06 02:53:51 +00:00
i-robot f90b406b8d !3120 Profiler Analysis Common Module
Merge pull request !3120 from 周先琪/v1.11.0_dev1
2023-05-06 01:57:01 +00:00
wangxiaoxin_sherie 5beb22e635 Using AICPU at non-binary scene. 2023-05-06 09:46:07 +08:00
zhouxianqi 1efba9d60f profiler_analysis_common_module 2023-05-05 16:00:32 +08:00
wangxiao 45aa5eb61f Broadcast of index. 2023-05-05 10:23:03 +08:00
zhang-aurora dfb70dfe63 Modify onnx export of npu_sign_bits_unpack 2023-05-04 15:41:14 +08:00
i-robot d22e06c19c !3156 Refactor of indexput
Merge pull request !3156 from chlme16/indexput11_1
2023-05-04 06:42:48 +00:00
chenhongliang d7af7cf8e7 Refactor of indexput 2023-05-04 13:52:03 +08:00
i-robot 56ec12706b !3052 NPU Profiler Common Code.
Merge pull request !3052 from 裘凯达/npu_profiler_1.11.0
2023-05-04 03:30:27 +00:00
i-robot 66a0eabc02 !3068 Refactor of indexput
Merge pull request !3068 from chlme16/indexput11_1
2023-05-04 03:21:59 +00:00
刘嘉巍 aeb50c8de3 Add load_derivatives 2023-04-28 17:29:19 +08:00
i-robot bd7359f8db !3107 Replace the cuda string of the function parameter in the torch.cuda class with npu
Merge pull request !3107 from louyujing/v1.11.0
2023-04-28 08:12:55 +00:00
weili10 c08f59460c save test results to xml file in ci environment 2023-04-28 15:37:23 +08:00
l30044004 009f65d518 Replace the cuda string of function parameters in the torch. cuda class with npu 2023-04-28 15:02:16 +08:00
liangyunfan fc31aa86ca Add device num check. 2023-04-28 14:32:47 +08:00
i-robot 71cdfa507a !3061 Modify the output types of mul_ under different types
Merge pull request !3061 from Destiny/mul_111
2023-04-28 06:22:32 +00:00
chenhongliang 4bdb45e799 Refactor of indexput 2023-04-27 19:58:17 +08:00
i-robot 39acd478a4 !3123 ops add deterministicAlgorithms config
Merge pull request !3123 from 关龙锋/cherry-pick-1682560535
2023-04-27 11:25:47 +00:00
裘凯达 ea095827c4 NPU Profiler Common Code. 2023-04-27 17:28:20 +08:00
i-robot b73b7478a2 !3062 Fix bug for DDPJoinHook_init_.
Merge pull request !3062 from 王夏夏/v1.11.0
2023-04-27 03:26:33 +00:00
guanlongfeng d0dc162e94 fixed 7ef8d47 from https://gitee.com/guan-longfeng/pytorch/pulls/3094
ops add deterministicAlgorithms config

dd test\test_api\test_torch_deterministicalgorithms.py

dd test\test_api\test_torch_deterministicalgorithms.py

dd unpdate deterministicalgorithms.py

dd unpdate deterministicalgorithms.py
2023-04-27 01:55:38 +00:00
i-robot eb2abca8c3 !3096 [BugFix] Fix noncontiguous tensor serialization load error.
Merge pull request !3096 from 闫鹏全/v1.11.0
2023-04-26 07:58:02 +00:00
i-robot cb64e08167 !3072 Modify onnx export symbol of npu_scatter
Merge pull request !3072 from Zhang Yingxin/up_master
2023-04-26 06:41:33 +00:00
闫鹏全 af5a572abb Fix noncontiguous tensor serialization load error 2023-04-26 11:29:44 +08:00
i-robot 720208b752 !3091 [FIX] Modify CTC API.
Merge pull request !3091 from 刘哲续/cherry-pick-1682429373
2023-04-25 14:13:58 +00:00
liu_zhi_xu 64ec395b2f fixed 3ec2c0d from https://gitee.com/liu_zhi_xu/pytorch/pulls/3090
Type:Modify CTC.
Team:PyTorch_Ops_Dev

Description:
Add max_length info.
2023-04-25 13:29:33 +00:00
i-robot 17db8ee60e !2993 [Fix] Update version 5.0.RC1 ReleaseNote .
Merge pull request !2993 from 彭子荣/v1.11.0
2023-04-25 01:31:55 +00:00
i-robot f511e5f780 !3058 Add torch.npu.get_device_capability, torch.npu.aclnn.version new interface
Merge pull request !3058 from 关龙锋/cherry-pick-1682242669
2023-04-24 08:18:11 +00:00
pengzirong 48cc081d4d update releasenote version 5.0.rc1 2023-04-24 14:19:50 +08:00
zhang-aurora 3d690ae125 Modify onnx export symbol of npu_scatter 2023-04-24 11:24:07 +08:00
xiaxia3 41ab954562 Fix bug for DDPJoinHook_init_. 2023-04-23 17:46:52 +08:00
Destiny 06ddf258a5 Modify the output types of mul_ under different types 2023-04-23 17:45:06 +08:00
guanlongfeng 07bbcc1950 fixed 0a57755 from https://gitee.com/guan-longfeng/pytorch/pulls/2976
add torch.npu.get_device_capability, torch.npu.aclnn.version new
interface

dd clear code

dd npu:0处理

dd update testcase
2023-04-23 09:37:50 +00:00
i-robot 67ac790bfb !3049 [分支同步]:change Log format
Merge pull request !3049 from yangxiaorun/cherry-pick-1682232214
2023-04-23 09:17:20 +00:00
i-robot d823a6f633 !3013 [DFX] add run_test for dev test
Merge pull request !3013 from weili10/v1.11.0
2023-04-23 07:53:00 +00:00
yangxiaorun 950bf73356 fixed 6454d4a from https://gitee.com/yangxiaorun1/pytorch/pulls/3044
style:change Log format
2023-04-23 06:43:35 +00:00
i-robot 5617b3aba2 !2960 [Fix] Fix TORCH_CHECK in LogSpaceKernelNpu.
Merge pull request !2960 from 刘嘉巍/1.11
2023-04-23 02:44:47 +00:00
i-robot 76995073ef !3004 [Feature] support HF32
Merge pull request !3004 from 王强/v1.11.0
2023-04-21 13:33:57 +00:00
i-robot bc058f71d8 !3029 [FIX] Modify CTC API.
Merge pull request !3029 from 刘哲续/v1.11.0
2023-04-21 09:48:23 +00:00
weili10 48dc033838 add run_test for dt 2023-04-21 17:35:18 +08:00
liu_zhi_xu 875b7eaa92 Type:Modify CTC.
Team:PyTorch_Ops_Dev

Description:
move unexpected conversion
2023-04-21 16:34:03 +08:00
i-robot 585d6f9738 !2732 [Feature] Basic functions and tempaltes for autograd.
Merge pull request !2732 from 刘嘉巍/1.11-codegen
2023-04-21 01:42:16 +00:00
i-robot 68ce64599e !2972 Supports AICore operator ViewCopy when diff equals to 1.
Merge pull request !2972 from 於欣洁/v1.11.0_vc0417
2023-04-20 13:59:03 +00:00
i-robot a893e8c936 !2997 Update the data information recorded in the ascend memory log.
Merge pull request !2997 from 闫鹏全/v1.11.0
2023-04-20 13:08:26 +00:00
i-robot dbe1463001 !3002 [FIX] Modify CTC API.
Merge pull request !3002 from 刘哲续/v1.11.0
2023-04-20 11:18:03 +00:00
wbigat 2781cdcf25 [Feature] support HF32 2023-04-20 17:36:35 +08:00
闫鹏全 2f8e9370e6 Update the data information recorded in the ascend memory log 2023-04-20 16:37:56 +08:00
liu_zhi_xu c1ecb3943f Type:Modify CTC API.
Team:PyTorch_Ops_Dev

Description:
Remove Overadaptation
Adjusting Memory Request Size
Rectification of naming style
2023-04-20 15:37:35 +08:00
i-robot f6d2654ffb !2988 Add CountNonZeroKernelNpu
Merge pull request !2988 from 张喻翔/py11/zyx/countnz
2023-04-20 06:09:55 +00:00
zhang-yuxiang0119 409f00c0b5 add count_nonzero 2023-04-20 10:03:28 +08:00
weili10 2d7ed1b445 update OWNERS.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-04-20 01:55:50 +00:00
刘嘉巍 93ee72eaa9 Fix TORCH_CHECK in logSpace 2023-04-17 20:18:53 +08:00
yuxinjie 631bf8969b Supports AICore operator ViewCopy when diff equals to 1. 2023-04-17 17:11:56 +08:00
i-robot f40aa576eb !2963 [Fix] revert fix for the stop-on-error feature
Merge pull request !2963 from 王强/v1.11.0
2023-04-17 05:26:44 +00:00
wbigat bc3b0f6670 Revert "fixed c180c88 from https://gitee.com/wbigat/pytorch_master_wq_2/pulls/2905"
This reverts commit 30d6c720d3.
2023-04-17 11:56:06 +08:00
wbigat 9415c1dcf5 Revert "fixed 63d8ec5 from https://gitee.com/wbigat/pytorch_master_wq_2/pulls/2948"
This reverts commit f2613f58e8.
2023-04-17 11:55:13 +08:00
xiaxia3 8958aa5b81 _amp_foreach_non_finite_check_ supports 1980B 2023-04-17 11:22:16 +08:00
i-robot a2fd07f92a !2950 [Fix] fix core dump bug after npu shut down.
Merge pull request !2950 from 王强/cherry-pick-1681469540
2023-04-14 12:34:14 +00:00
wbigat f2613f58e8 fixed 63d8ec5 from https://gitee.com/wbigat/pytorch_master_wq_2/pulls/2948
[Fix] fix core dump bug after npu shut down.
2023-04-14 10:52:23 +00:00
i-robot e8da7eec6f !2933 Fix MakeSureQueueEmpty deadlock
Merge pull request !2933 from xqiangx1991/v1.11.0
2023-04-13 01:57:25 +00:00
i-robot 156fec16de !2898 Add pta_memory malloc log.
Merge pull request !2898 from 闫鹏全/v1.11.0
2023-04-13 01:27:59 +00:00
xuqiang d46d13162a fix MakeSureQueueEmpty deadlock 2023-04-13 09:10:52 +08:00
i-robot 226254c107 !2916 add ND/NZ choose for mm/bmm for performance
Merge pull request !2916 from 赵颖超/v1.11.0
2023-04-12 12:38:45 +00:00
闫鹏全 1cfb73709b Add pta_memory malloc log 2023-04-12 10:38:55 +08:00
anping 177dfbdab2 [Bugfix] throw error when PAT version mismatch 2023-04-12 09:17:27 +08:00
zhaoyingchao 7b7f9e1ca6 add ND/NZ choose for mm/bmm for performance 2023-04-11 17:05:30 +08:00
i-robot 087d93b0fd !2918 Removing operations for device resources such as events and stream, during shutdown
Merge pull request !2918 from 王强/cherry-pick-1681194595
2023-04-11 08:10:13 +00:00
wbigat 30d6c720d3 fixed c180c88 from https://gitee.com/wbigat/pytorch_master_wq_2/pulls/2905
[Fix] During shutdown, removing operations for device resources such as events and stream.
2023-04-11 06:29:57 +00:00
i-robot 48d7320ba7 !2913 [Feature] Support structured ops tocpu.
Merge pull request !2913 from will-devil/stocpu111
2023-04-11 06:09:08 +00:00
i-robot 7245355c0e !2910 [Fix]Parse the size argument of new_ones from int to tuple.
Merge pull request !2910 from 杜金航/v1.11.0
2023-04-11 03:24:45 +00:00
wangyicheng a6f28107cc Support structured ops tocpu. 2023-04-11 10:53:30 +08:00
dujinhang 2ba6708135 [Fix]Parse the size argument of new_ones from int to tuple. 2023-04-10 17:18:48 +08:00
i-robot 3d636ec2bc !2853 Fix bug of torch.median API when input is empty tensor
Merge pull request !2853 from 李德钊/per_520113
2023-04-10 01:58:21 +00:00
i-robot 6bd29a2bc5 !2887 [FIX] Modify Index op api.
Merge pull request !2887 from 刘哲续/v1.11.0
2023-04-08 10:35:51 +00:00
刘哲续 6cce587de3 Type:BugFix Index op
Team:PyTorch_Ops_Dev

Description:
1、not to transpose at all scene.
2、turn uint8/bool to int32 when go aicore.
3、delete unuseful bool logic.
2023-04-08 09:38:13 +08:00
i-robot 17135c3bbc !2841 Delete onnx export for one_ and npu_silu_
Merge pull request !2841 from Zhang Yingxin/up_master
2023-04-07 12:33:52 +00:00
尤安升 4b6fcc67b3 update .gitignore. 2023-04-07 08:13:54 +00:00
尤安升 e3ab8ba3c2 Disable abnormal patches to torch module. 2023-04-07 02:32:09 +00:00
l00520113 c909295e5c Fix the bug of torch.median API not support empty input parameters 2023-04-07 10:06:48 +08:00
i-robot 068e2d53ed !2800 TaskQueue optimization
Merge pull request !2800 from 裘凯达/opt1.11.0
2023-04-06 15:18:27 +00:00
i-robot fa50733e19 !2863 fix: overflow should enable in stream init
Merge pull request !2863 from yangxiaorun/cherry-pick-1680776008
2023-04-06 15:10:16 +00:00
i-robot f10429494c !2869 Fix bug of clear_npu_overflow_flag.
Merge pull request !2869 from 王夏夏/v1.11.0
2023-04-06 14:43:49 +00:00
i-robot 66b8848bf2 !2866 feat: change jit_compile default value from ACL
Merge pull request !2866 from yangxiaorun/cherry-pick-1680782843
2023-04-06 14:39:05 +00:00
i-robot 01fe2cd138 !2813 Fix the bug of mul_ when input is bool.
Merge pull request !2813 from 叶钊/v1.11.0
2023-04-06 13:39:12 +00:00
xiaxia3 cedde8a215 Fix bug of clear_npu_overflow_flag 2023-04-06 20:38:09 +08:00
i-robot 95f40a18f2 !2837 get_npu_overflow_flag supports the overflow detection of Ascend910B1.
Merge pull request !2837 from 王夏夏/v1.11.0
2023-04-06 12:16:06 +00:00
yangxiaorun 0968bc3e1d fixed 2d4c60d from https://gitee.com/yangxiaorun1/pytorch_1/pulls/2856
feat: change jit_compile default value from ACL
2023-04-06 12:07:24 +00:00
yangxiaorun a258b284a5 fixed e783f0a from https://gitee.com/yangxiaorun1/pytorch_1/pulls/2862
fix: overflow should enable in stream init
2023-04-06 10:13:29 +00:00
i-robot bc20a15bd3 !2808 Solve multithreading problem of OpCommandImpls
Merge pull request !2808 from sunjiayang/thread-v1.11.0
2023-04-06 07:58:28 +00:00
i-robot 961b8d9425 !2852 [Fix] Syncbatchnorm precision overflow problem.
Merge pull request !2852 from 杜金航/v1.11.0_syncbatchnorm
2023-04-06 07:37:56 +00:00
yezhao dd90ae9230 [Fix]Fix the bug of mul_ when input is bool.
[Fix]Fix the bug of mul_ when input is bool.
2023-04-06 13:20:23 +08:00
i-robot 7a2f796020 !2832 [Fix]add new_ones and new_tensor for npu device initialization.
Merge pull request !2832 from 杜金航/v1.11.0
2023-04-06 03:50:24 +00:00
i-robot 9e9cc9fd8d !2830 fix the test of vsplit
Merge pull request !2830 from Leon/111_new
2023-04-06 01:20:14 +00:00
dujinhang 6edc2cf973 [Fix] Syncbatchnorm precision overflow problem. 2023-04-05 15:00:33 +08:00
i-robot 52dae67830 !2807 Perf optimization of rrelu_with_noise when training is true
Merge pull request !2807 from WANGQI/torch_v11
2023-04-04 09:59:55 +00:00
dujinhang 83649ad545 [Fix]add new_ones and new_tensor for npu device initialization. 2023-04-04 17:23:57 +08:00
zhang-aurora 9b51e8d77f delete onnx export for one_ and npu_silu_ 2023-04-04 16:58:49 +08:00
xiaxia3 09a24d592e get_npu_overflow_flag supports the overflow detection of Ascend910B1. 2023-04-04 15:59:48 +08:00
liangyunfan 1da5004433 fix vsplit test 2023-04-04 12:01:51 +08:00
i-robot 2b083bbf82 !2820 [Fix]Not to transpose at index non-binary scene.
Merge pull request !2820 from 王晓/index_jit_1.11
2023-04-04 03:22:03 +00:00
cudi f758f47678 Optimize the method to report Pipeline data. 2023-04-04 10:33:51 +08:00
i-robot d045333ff1 !2814 [Feature] Add new ops to tocpu whitelist.
Merge pull request !2814 from will-devil/11tocpu
2023-04-03 13:05:59 +00:00
wangyicheng fb14e43a30 Add new ops to tocpu whitelist. 2023-04-03 19:55:43 +08:00
wangxiao b3a3d7d415 Not to transpose at index non-binary scene. 2023-04-03 16:46:11 +08:00
w_a_n_g_q_i 876cf6238e perf optimization of rrelu_with_noise when training is true. 2023-04-01 17:36:22 +08:00
i-robot d207a5b26a !2809 Add trapezoid test.
Merge pull request !2809 from Leon/111
2023-04-01 08:39:04 +00:00
weili10 f444acf8b0 update OWNERS.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-04-01 08:10:20 +00:00
liangyunfan 9d15c4561c Add trapezoid test. 2023-04-01 14:26:21 +08:00
sunxinlei ff81613a74 Solve multithreading problem of OpCommandImpls 2023-04-01 11:44:25 +08:00
i-robot 6fe1803baa !2771 Add vsplit test.
Merge pull request !2771 from Leon/111
2023-03-31 13:12:49 +00:00
i-robot 091eee882f !2793 [Fix]Make npu_deformable_conv2d running with fp32.
Merge pull request !2793 from 王晓/deformable_to_fp32_1.11
2023-03-31 13:10:29 +00:00
i-robot 330c191227 !2778 Modify Ascend profiling to improve ease of use
Merge pull request !2778 from hanjun/v1.11.0
2023-03-31 08:28:56 +00:00
i-robot df5b8d32c1 !2765 Add gaussian_nll_loss test.
Merge pull request !2765 from Leon/111
2023-03-31 08:21:50 +00:00
i-robot 74b850aba2 !2749 [BugFix] Correct apply-tensor-with object for RotatedNMS‘s output selectedBox.
Merge pull request !2749 from 叶灵煜/cherry-pick-1679670477
2023-03-30 12:32:52 +00:00
h00558267 9bf987e171 Fix ascend profiler bug
Fix some bug

Fix some bug
2023-03-30 19:21:24 +08:00
叶灵煜 711c8bd404 fixed 61cfa41 from https://gitee.com/lingyu-ye/pytorch/pulls/2747
Correct apply-tensor-with object for the output selectedBox.

Signed-off-by: 叶灵煜 <yelingyu@huawei.com>
2023-03-30 17:06:29 +08:00
刘嘉巍 b98710bbcf Basic functions and tempaltes for autograd. 2023-03-30 16:31:20 +08:00
i-robot 21b5f2cff1 !2785 [Fix] Register _to_copy in adapter.
Merge pull request !2785 from 刘嘉巍/1.11
2023-03-30 07:19:17 +00:00
i-robot 0f837d6e55 !2763 [Cleancode] Clean code for all.
Merge pull request !2763 from huangyunlong/1.11code
2023-03-30 06:07:05 +00:00
刘嘉巍 4b66ee744e Register _to_copy 2023-03-30 11:28:18 +08:00
huangyunlong 48e2562807 [Cleancode] Clean code for all. 2023-03-29 16:35:05 +08:00
liangyunfan 58aba4a39d Add vsplit test. 2023-03-29 16:22:08 +08:00
liangyunfan f7e0a56db8 Add gaussian_nll_loss test. 2023-03-29 15:09:15 +08:00
i-robot b79b6666e2 !2553 [BugFix] Optimize nllloss to support 0D-target scenarios.
Merge pull request !2553 from 戢芳/nllloss1.11
2023-03-29 04:03:44 +00:00
i-robot 906460c323 !2767 [Fix] Modify onnx export for npu_mish
Merge pull request !2767 from Zhang Yingxin/up_master
2023-03-29 03:39:02 +00:00
i-robot d019e71aaf !2742 PyTorch Adapter of Mish and MishGrad
Merge pull request !2742 from 汪琰/mish_v1.11.0_2
2023-03-28 13:18:04 +00:00
i-robot 827160731b !2746 Modify method to get Monotonic RAW time.
Merge pull request !2746 from 裘凯达/task_queue1.11.0
2023-03-28 12:54:26 +00:00
weili10 a21569f658 update OWNERS.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-03-28 12:45:27 +00:00
wangyan f830fc680b Pytorch Adapter of Mish and MishGrad
Type: Feature
Team: PyTorch_Ops_Dev
InventoryUpdate: False
Issue: Issue_no
Description: As mish is supported in PyTorch 1.11, the related Pytorch
adapter is developed here.
2023-03-28 19:54:25 +08:00
zhang-aurora b264619b87 Modify onnx export for npu_mish 2023-03-28 15:30:44 +08:00
i-robot 85d33a150a !2760 Fix the bug of mm when input is empty tensor.
Merge pull request !2760 from 戴瑜文/mm
2023-03-28 06:36:32 +00:00
weili10 bab025553e update OWNERS.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-03-28 06:30:29 +00:00
daiyuwen 5450f86271 [Fix] Fix the bug of mm when input is empty tensor. 2023-03-28 09:49:59 +08:00
weili10 5068f89805 !2762 Revert 'Pull Request !2695 : [Fix] add _lazy_init in torch_device_guard.'
Merge pull request !2762 from weili10/revert-merge-2695-v1.11.0
2023-03-27 12:21:20 +00:00
weili10 561a19dd1d Revert 'Pull Request !2695 : [Fix] add _lazy_init in torch_device_guard.' 2023-03-27 11:27:14 +00:00
i-robot 21415a613a !2666 [BugFix] Fix the outputpadding of conv_transpose2d.
Merge pull request !2666 from 戢芳/conv1.11
2023-03-27 07:24:22 +00:00
尤安升 756ab48356 update OWNERS. 2023-03-27 01:20:17 +00:00
i-robot bdc135936b !2695 [Fix] add _lazy_init in torch_device_guard.
Merge pull request !2695 from 杜金航/v1.11.0
2023-03-26 01:16:46 +00:00
i-robot 25aa5e28af !2751 Fix the bug of the SigmoidCrossEntropyWithLogitsV2 and SigmoidCrossEntropyWithLogitsGradV2.
Merge pull request !2751 from 郑亚金/v1.11.0_zyj_sig_0325
2023-03-25 13:14:56 +00:00
i-robot f2a393e7ed !2697 Optimizing data type conversions when create scalar tensor
Merge pull request !2697 from sunjiayang/scalar_input_v1.11.0
2023-03-25 10:12:34 +00:00
郑亚金 04b70e70a3 Fix the bug of the SigmoidCrossEntropyWithLogitsV2 and SigmoidCrossEntropyWithLogitsGradV2. 2023-03-25 17:47:59 +08:00
sunxinlei 359a5a8a20 Optimizing data type conversions when create scalar tensor 2023-03-25 11:32:40 +08:00
i-robot 7686ec2f33 !2739 [Bugfix] modify event timeout.
Merge pull request !2739 from darin123/v1.11.0
2023-03-25 03:19:00 +00:00
i-robot da2a51c833 !2618 [Fix] Fix bug when printing npu native format tensor.
Merge pull request !2618 from 刘嘉巍/1.11-dev
2023-03-25 02:44:42 +00:00
cudi f102c343b6 modify method to get time. 2023-03-24 20:29:54 +08:00
i-robot d197f6d249 !2686 [Feature] Add test file for npu_fused_attention_score_fwd.
Merge pull request !2686 from 叶灵煜/cherry-pick-1679319046
2023-03-24 09:09:04 +00:00
i-robot b38cf3b172 !2664 Report task queue trace message to MsProfiler.
Merge pull request !2664 from 裘凯达/task_queue1.11.0
2023-03-24 08:35:46 +00:00
i-robot 2148cb28d3 !2617 [Feature] add ci for libtorch_npu.
Merge pull request !2617 from huangyunlong/libtorch_ci
2023-03-24 08:32:39 +00:00
anping b081ddfc8b [Bugfix] modify event timeout. 2023-03-24 15:12:00 +08:00
i-robot 0800d3a5d9 !2649 [Feature] Modify codegen & add cpp file for autograd.
Merge pull request !2649 from 刘嘉巍/1.11-codegen
2023-03-24 01:35:15 +00:00
刘嘉巍 dec4263ecd Modify codegen & add cpp file for autograd 2023-03-23 22:37:53 +08:00
i-robot 30f96b53c0 !2708 Fix format change bug when using asycn dist op
Merge pull request !2708 from Jializheng/master
2023-03-23 14:28:16 +00:00
i-robot cba8c77812 !2681 [Feature] Add op to tocpu whitelist.
Merge pull request !2681 from will-devil/111cpu
2023-03-23 13:40:08 +00:00
i-robot 080316b457 !2700 Make reciprocal support Integer.
Merge pull request !2700 from 郑亚金/v1.11.0_zyj_reciprocal_0321
2023-03-23 13:03:38 +00:00
i-robot c8d951553b !2717 [Fix] fix AclGetErrMsg and do not return nullptr.
Merge pull request !2717 from 王强/v1.11.0
2023-03-23 12:48:46 +00:00
i-robot 3ff156d300 !2626 Update BiShengCPP examples.
Merge pull request !2626 from shaoyf/cherry-pick-1678943910
2023-03-23 12:36:38 +00:00
will-devil b1ca653ba2 Merge branch 'v1.11.0' of gitee.com:ascend/pytorch into 111cpu
Signed-off-by: will-devil <wangyicheng13@huawei.com>
2023-03-23 12:07:06 +00:00
i-robot fa900c0525 !2718 [BugFix] Optimize normal to support std=0.
Merge pull request !2718 from 戢芳/normal1.11
2023-03-23 12:02:27 +00:00
i-robot dd5c25aaf5 !2721 Add auxiliary functions of profiler
Merge pull request !2721 from hanjun/v1.11.0
2023-03-23 10:36:43 +00:00
wangxiao b8093c410e Make npu_deformable_conv2d running with fp32. 2023-03-23 16:37:40 +08:00
郑亚金 641ace894a Make reciprocal support integer. 2023-03-23 16:26:40 +08:00
h00558267 a5b628e4e0 Add ascend profiler
Add ascend profiler
2023-03-23 15:13:47 +08:00
wangyicheng 2dcb73ad27 Add op to tocpu whitelist. 2023-03-23 14:33:52 +08:00
i-robot e489caa877 !2669 [Fix] update op list for AOE.
Merge pull request !2669 from 施博/up_master_v1.11
2023-03-23 06:06:45 +00:00
pipihugh 5327ca8b38 Optimize normal to support std=0. 2023-03-23 13:42:56 +08:00
i-robot 920f00ddff !2690 [Fix] Fix memory_summary api.
Merge pull request !2690 from 闫鹏全/v1.11.0
2023-03-22 13:53:52 +00:00
wq160 ae42d2cd5d [Fix] fix AclGetErrMsg and do not return nullptr. 2023-03-22 21:09:05 +08:00
i-robot a863ac8674 !2696 [BugFix] Delete the check about async of reduce.
Merge pull request !2696 from 戢芳/reduce1.11
2023-03-22 11:50:22 +00:00
dujinhang 8ab3983917 [Fix] add _lazy_init in torch_device_guard. 2023-03-22 17:42:25 +08:00
i-robot 7c0a68670d !2675 Support selu_backward.
Merge pull request !2675 from 王晓/selu_backward_1.11
2023-03-22 08:32:37 +00:00
cudi fce48cc674 Report TaskQueue Pipeline Data to MsProfiler. 2023-03-22 10:43:52 +08:00
wangxiao 35390757ad Support selu_backward. 2023-03-22 10:06:44 +08:00
pipihugh cd4d58d1a1 Delete the check about async of reduce. 2023-03-21 20:03:12 +08:00
i-robot 8107a527d1 !2678 [fix] fix binary_cross_entropy_with_logits_backward bug.
Merge pull request !2678 from 王夏夏/v1.11.0
2023-03-21 11:54:41 +00:00
闫鹏全 ddda05b1b4 Fixed memory_summary function call errors. 2023-03-21 16:46:29 +08:00
huangyunlong 7cfc9a4cf6 [Feature] add ci for libtorch_npu. 2023-03-21 15:09:34 +08:00
叶灵煜 81451d727c fixed c529aee from https://gitee.com/lingyu-ye/pytorch/pulls/2683
Add testcases for custom torch_npu ops.
2023-03-20 13:30:48 +00:00
shaoyf 52790f0c60 Update BiShengCPP examples. Fixed afd4fdf from https://gitee.com/shaoyf/pytorch/pulls/2549. 2023-03-20 20:50:08 +08:00
i-robot e7b584e574 !2625 Add support for npu format in dist.send and dist.recv
Merge pull request !2625 from lj_new/v1.11.0
2023-03-20 12:31:44 +00:00
i-robot 35d70249e5 !2638 [BugFix]Fix the dtype bug of min and support minimum.out.
Merge pull request !2638 from 郑亚金/v1.11.0_zyj_minimum_0316
2023-03-20 12:28:16 +00:00
shibo19 6bcbba14df update op list for AOE 2023-03-20 19:08:58 +08:00
xiaxia3 104170bf29 [fix] fix binary_cross_entropy_with_logits_backward bug. 2023-03-20 18:01:25 +08:00
pipihugh fd9cb4c8b1 Optimize nllloss to support 0D-target scenarios. 2023-03-20 15:33:37 +08:00
lijing e1228d0d4c Use NPUNativeFunctions for performance 2023-03-20 15:06:26 +08:00
i-robot cce09a2b2a !2597 [Feature] Libtorch: add device init API && libtorch_npu example
Merge pull request !2597 from huangyunlong/libtorch1.11
2023-03-20 06:33:12 +00:00
i-robot 13f0520808 !2659 [BugFix] Add var.correction and delete var.
Merge pull request !2659 from Rayyyy/var1.11_new
2023-03-20 03:23:41 +00:00
Rayyyy 93a5ac327c Add var.correction and delete var. 2023-03-20 09:20:36 +08:00
i-robot 32e66d08fc !2588 [BugFix] Change unique_consecutive's output[1] to dynamic output.
Merge pull request !2588 from 戢芳/unique1.11
2023-03-19 02:29:14 +00:00
i-robot e2c213d3d5 !2563 Adaptation of torch.fx with PyTorch1.11.
Merge pull request !2563 from Leon/v1.11.0
2023-03-18 10:58:48 +00:00
i-robot 7a3d4c895b !2608 [profiling] Add npu/cpu mem usage stat.
Merge pull request !2608 from 杨明海/v1.11.0
2023-03-18 02:40:06 +00:00
i-robot 7befd2158e !2635 Modification of ge op to handle tensors form different devices.
Merge pull request !2635 from Leon/111
2023-03-18 02:26:30 +00:00
i-robot e01d923111 !2645 [Feature] Add onnx export for npu_format_cast
Merge pull request !2645 from Zhang Yingxin/up_master
2023-03-18 01:42:49 +00:00
huangyunlong d71fe03d67 [Feature] Libtorch: add device init API && libtorch_npu example 2023-03-17 18:51:38 +08:00
郑亚金 2974d71e48 Enable the minimum operator to support the scenario where two parameter data type are inconsistent and provide the out interface. 2023-03-17 17:22:39 +08:00
yang-minghai22 f5bb61eaff Add npu/cpu mem usage stat. 2023-03-17 16:45:35 +08:00
liangyunfan 978dd0324e Modification of ge op to handle tensors from different devices. 2023-03-17 15:08:06 +08:00
zhang-aurora 1231d057cc Add onnx export for npu_format_cast 2023-03-17 10:25:17 +08:00
i-robot e672154215 !2592 [Fix] Modify onnx export for npu_scaled_masked_softmax
Merge pull request !2592 from Zhang Yingxin/up_master
2023-03-17 01:25:24 +00:00
i-robot f8661b84df !2574 [BugFix] Fix gru_backward when batch_size==1.
Merge pull request !2574 from 戢芳/gru1.11
2023-03-16 13:51:29 +00:00
i-robot c7e3d7db8c !2591 [Feature]Add adapter of celu_backward.
Merge pull request !2591 from chlme16/celu_11
2023-03-16 13:49:06 +00:00
chenhongliang 25fb08a037 Add adapter of celu_backward. 2023-03-16 20:36:17 +08:00
i-robot 4d4c86e4fc !2606 [Feature] Delete TASK_QUEUE_ENABLE in env.sh
Merge pull request !2606 from 詹昊/v1.11.0
2023-03-16 06:58:21 +00:00
i-robot d9b18855e9 !2578 Refactor of index.
Merge pull request !2578 from 王晓/refactor_index_1.11_4
2023-03-16 06:43:25 +00:00
刘嘉巍 b0601ff8e6 Fix bug when print tensor with npu native format 2023-03-16 11:46:41 +08:00
zhang-aurora ad163a3120 Modify ONNX export for npu_scaled_masked_softmax 2023-03-16 11:27:13 +08:00
i-robot e2fdd668ee !2585 [Cleancode]Clean code for equal and eval.
Merge pull request !2585 from huangyunlong/feature_hyl
2023-03-16 02:38:10 +00:00
i-robot 3aa1549def !2559 [Fix] Delete docs without releasenote .
Merge pull request !2559 from 彭子荣/v1.11.0
2023-03-16 02:36:22 +00:00
pipihugh 03f752fa58 Change unique_consecutive's output[1] to dynamic output. 2023-03-16 10:09:05 +08:00
lijing 5de17d8416 Add support for npu format in dist.send and dist.recv 2023-03-15 20:16:38 +08:00
i-robot 0ffe4f56a8 !2595 the operator "onehot" supports empty tensor input
Merge pull request !2595 from 陈龙胜/onehot1.11
2023-03-15 11:19:31 +00:00
i-robot 7ee6ef246f !2550 [Task] Add Adaptation of clamp.Tensor.
Merge pull request !2550 from 戢芳/clamp_tensor1.11
2023-03-15 10:47:53 +00:00
i-robot 12816facc1 !2564 Delete Fills.
Merge pull request !2564 from 戢芳/fill1.11
2023-03-15 10:47:16 +00:00
weili10 d5a12c14fd update OWNERS.
Signed-off-by: weili10 <liwei386@huawei.com>
2023-03-15 07:12:28 +00:00
zhanhao d0a96f0629 Delete TASK_QUEUE_ENABLE in env.sh 2023-03-15 14:17:15 +08:00
cls214 583bb87fba Modify the adaptation code of the operator "onehot" to support empty tensor input
Type: feature
Team: Pytorch_Ops_Dev
Issue: NA
Description:
1.Remove redundancy check
2.When null tensors are input, normal results are returned without error
2023-03-15 11:29:13 +08:00
huangyunlong e2fe0753e8 [Cleancode]Clean code for equal and eval 2023-03-14 20:38:24 +08:00
i-robot 88a88f5519 !2555 [Bugfix] set attr is_fused_optimizer in base for NPU fused optimizers
Merge pull request !2555 from 郭鹏/feature/v1.11.0-fusedoptims-all
2023-03-14 12:03:11 +00:00
i-robot d5109355cc !2565 [bugfix] Sync with origin torch, modify the patch func to support the dim of input tensor is 2 in lstm.
Merge pull request !2565 from 郭夏/lstm-v1.11.0
2023-03-14 10:40:35 +00:00
wangxiao 9cc8ddb24c Refactor of index. 2023-03-14 15:41:26 +08:00
pipihugh b6ac1263b3 Fix gru_backward when batch_size==1. 2023-03-14 15:02:21 +08:00
郭夏 6663f93b41 [bugfix] Sync with origin torch, modify the patch func to support the dim of input tensor is 2 in lstm.
Signed-off-by: 郭夏 <guoxia2@huawei.com>
2023-03-13 15:32:46 +08:00
liangyunfan aa8e2dc3e2 Adaptation of torch.fx with PyTorch1.11. 2023-03-13 11:41:23 +08:00
pengzirong ebba6c7a5c delete docs (except releasenote) 2023-03-13 09:24:42 +08:00
gp513 ac7df74e40 bugfix: set attr is_fused_optimizer in base 2023-03-11 11:39:10 +08:00
pipihugh e1c945930a Add Adaptation of clamp.Tensor. 2023-03-10 16:36:13 +08:00
j00648035 b6abad5e57 dist async op fix 2023-03-09 15:43:03 +08:00
pipihugh 6eb4723c8a Delete Fills. 2023-03-07 21:03:52 +08:00
654 changed files with 16738 additions and 26435 deletions
+8
View File
@@ -193,3 +193,11 @@ TAGS
# bazel symlinks
bazel-*
# Generated files
torch_npu/version.py
torch_npu/csrc/aten/NPUNativeFunctions.h
torch_npu/csrc/aten/RegisterAutogradNPU.cpp
torch_npu/csrc/aten/RegisterCPU.cpp
torch_npu/csrc/aten/RegisterNPU.cpp
torch_npu/csrc/aten/python_custom_functions.cpp
+17 -1
View File
@@ -7,6 +7,10 @@ set(CMAKE_INSTALL_MESSAGE NEVER)
# set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
if(DEFINED TORCH_VERSION)
add_definitions(-DPYTORCH_NPU_VERSION="${TORCH_VERSION}")
endif()
set(PLUGIN_NAME torch_npu)
set(RPATH_VALUE $ORIGIN)
@@ -178,6 +182,9 @@ if (NOT DEFINED BUILD_LIBTORCH)
set(UTILS_SRCS)
endif()
if (DEFINED BUILD_LIBTORCH)
set(NPU_CPP_LIBS_SRCS)
endif()
add_subdirectory(${TORCHNPU_ROOT}/aten)
add_subdirectory(${TORCHNPU_ROOT}/core)
@@ -191,7 +198,11 @@ if (NOT DEFINED BUILD_LIBTORCH)
endif()
if (DEFINED BUILD_LIBTORCH)
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS})
add_subdirectory(${TORCHNPU_ROOT}/libs)
endif()
if (DEFINED BUILD_LIBTORCH)
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${FRAMEWORK_SRCS} ${NPU_CPP_LIBS_SRCS})
else()
# Compile code with pybind11
set(CPP_SRCS ${ATEN_SRCS} ${CORE_SRCS} ${DIST_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${UTILS_SRCS})
@@ -242,3 +253,8 @@ if (NOT DEFINED BUILD_LIBTORCH)
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/toolkit)
target_link_libraries(${PLUGIN_NAME} PUBLIC npu_profiler)
endif()
+28 -9
View File
@@ -3,23 +3,20 @@ approvers:
- weili10
- you-ansheng
- yskhhh
- clinglai
- lvpeiyuan
- xiepeng20
- xiong05
- guang-jun-zhang2
reviewers:
- shibo19
- Ronnie_zheng
- xiaxia3
- petissue
- td__lihan
- ascendzyj
- wudingyuan
- yskhhh
- matrixplayer
- li_jing_hw
- wangjiangben_hw
- qingfenxiaochong
- goodjobwubai
- fairwarning
- you-ansheng
- yinzijun
- weili10
- granpad7
- clinglai
@@ -31,4 +28,26 @@ reviewers:
- brightlyking
- chenhao_1209
- wbigat
- will-devil
- will-devil
- ckirchhoff
- liu-tianlong
- jayshu
- lvpeiyuan
- luyoubing
- dai-yuwen
- jia8liang
- w_a_n_g_q_i
- simonzhouchun
- luo-hui46
- yang-renfeihuawei
- y00580292
- AllenYaWang
- lidezhao1
- ma-dongfang
- wangchao285
- dilililiwhy
- sunjiayang
- huangyunlong2022
- misty-rain-typhoid
- du-jin-hang
- xqiangx1991
+45 -15
View File
@@ -44,7 +44,42 @@
</th>
</tr>
</thead>
<tbody><tr id="row1452975217222"><td class="cellrowborder" rowspan="3" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>3.0.0</p>
<tbody><tr id="row1452975217222"><td class="cellrowborder" rowspan="2" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>5.0.RC1</p>
</td>
<td class="cellrowborder" rowspan="2" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.3.RC1</p>
</td>
<td class="cellrowborder" valign="top" width="17.080000000000002%" headers="mcps1.2.6.1.3 "><p id="p197571831182710"><a name="p197571831182710"></a><a name="p197571831182710"></a>1.8.1.post1</p>
</td>
<td class="cellrowborder" valign="top" width="17.05%" headers="mcps1.2.6.1.4 "><p id="p18655452182620"><a name="p18655452182620"></a><a name="p18655452182620"></a>v1.8.1-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" width="31.929999999999996%" headers="mcps1.2.6.1.5 "><p id="p2087128165411"><a name="p2087128165411"></a><a name="p2087128165411"></a>-</p>
</td>
</tr>
<tr id="row16995654102215"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p48506347263"><a name="p48506347263"></a><a name="p48506347263"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p10655452142612"><a name="p10655452142612"></a><a name="p10655452142612"></a>v1.11.0-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p2087118825410"><a name="p2087118825410"></a><a name="p2087118825410"></a>-</p>
</td>
<tr id="row1452975217222"><td class="cellrowborder" rowspan="2" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>5.0.RC1(适用于昇腾910B处理器)</p>
</td>
<td class="cellrowborder" rowspan="2" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.1.RC1</p>
</td>
<td class="cellrowborder" valign="top" width="17.080000000000002%" headers="mcps1.2.6.1.3 "><p id="p197571831182710"><a name="p197571831182710"></a><a name="p197571831182710"></a>1.8.1.post1</p>
</td>
<td class="cellrowborder" valign="top" width="17.05%" headers="mcps1.2.6.1.4 "><p id="p18655452182620"><a name="p18655452182620"></a><a name="p18655452182620"></a>v1.8.1-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" width="31.929999999999996%" headers="mcps1.2.6.1.5 "><p id="p2087128165411"><a name="p2087128165411"></a><a name="p2087128165411"></a>-</p>
</td>
</tr>
<tr id="row16995654102215"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p48506347263"><a name="p48506347263"></a><a name="p48506347263"></a>1.11.0</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.2 "><p id="p10655452142612"><a name="p10655452142612"></a><a name="p10655452142612"></a>v1.11.0-5.0.rc1</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.6.1.3 "><p id="p2087118825410"><a name="p2087118825410"></a><a name="p2087118825410"></a>-</p>
</td>
</tr>
<tr id="row1452975217222"><td class="cellrowborder" rowspan="3" valign="top" width="18.16%" headers="mcps1.2.6.1.1 "><p id="p1849173117229"><a name="p1849173117229"></a><a name="p1849173117229"></a>3.0.0</p>
</td>
<td class="cellrowborder" rowspan="3" valign="top" width="15.78%" headers="mcps1.2.6.1.2 "><p id="p13849183142218"><a name="p13849183142218"></a><a name="p13849183142218"></a>CANN 6.0.1</p>
</td>
@@ -212,21 +247,21 @@ pip3 install wheel
```
# 若用户在x86架构下安装插件,请将命令中文件包名中的“aarch64”改为“x86_64”。
wget https://gitee.com/ascend/pytorch/releases/download/v3.0.0-pytorch1.11.0/torch_npu-1.11.0rc2-cp37-cp37m-linux_aarch64.whl
wget https://gitee.com/ascend/pytorch/releases/download/v5.0.rc1-pytorch1.11.0/torch_npu-1.11.0-cp37-cp37m-linux_aarch64.whl
```
2. 执行如下命令安装。如果使用非root用户安装,需要在命令后加**--user。**
```
# 若用户在x86架构下安装插件,请将命令中文件包名中的“aarch64”改为“x86_64”。
pip3 install torch_npu-1.11.0rc2-cp37-cp37m-linux_aarch64.whl
pip3 install torch_npu-1.11.0-cp37-cp37m-linux_aarch64.whl
```
3. 安装对应框架版本的torchvision。
```
#PyTorch 1.11.0需安装0.12.0版本
pip3 install torchvision==0.9.1
pip3 install torchvision==0.12.0
```
**安装APEX混合精度模块<a name="section154215015416"></a>**
@@ -257,11 +292,12 @@ Ascend PyTorch的版本分支有以下几种维护阶段:
| ------------ | ------------ | ------------ | -------------------------------------- | ------------ |
| **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 | |
| **v2.0.4** | EOL | 2022-01-15 | N/A | |
| **v3.0.rc1** | UnMaintained | 2022-04-10 | EOL <br> 2023-07-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 | |
| **v5.0.rc1** | Maintained | 2023-4-19 | Unmaintained <br/> 2024-4-19 estimated | |
# FAQ
@@ -348,8 +384,8 @@ Debian、UOS20、UOS20 SP1、Linx系统可参考Ubuntu进行安装。
1. 编译生成PyTorch插件的二进制安装包。
```
# 下载对应PyTorch版本分支代码,进入插件根目录,以v1.11.0-3.0.0为例
git clone -b v1.11.0-3.0.0 https://gitee.com/ascend/pytorch.git
# 下载对应PyTorch版本分支代码,进入插件根目录,以v1.11.0为例
git clone -b v1.11.0 https://gitee.com/ascend/pytorch.git
cd pytorch
# 指定Python版本编包方式,以Python3.7为例,其他Python版本请使用 --python=3.8或--python3.9
bash ci/build.sh --python=3.7
@@ -366,7 +402,7 @@ Debian、UOS20、UOS20 SP1、Linx系统可参考Ubuntu进行安装。
```
#PyTorch 1.11.0需安装0.12.0版本
pip3 install torchvision==0.9.1
pip3 install torchvision==0.12.0
```
4. 配置环境变量,验证是否安装成功。
@@ -414,9 +450,6 @@ pip3 install typing_extensions
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 #{arch}为架构名称
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
@@ -424,9 +457,6 @@ pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 #{arch}为架构名称
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
+13 -4
View File
@@ -120,7 +120,7 @@ def clean_generated_files():
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']
'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))
@@ -163,6 +163,14 @@ def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, lev
"""
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
def move_special_hpp(ret):
hpp_name = "library_npu.h"
for _, dst in ret:
if dst.endswith(hpp_name):
dir_name = os.path.join(os.path.dirname(dst), "../../" + hpp_name)
copy_file(dst, dir_name)
return
def copy_hpp():
def get_src_py_and_dst():
@@ -174,6 +182,7 @@ def copy_hpp():
"torch_npu/csrc/aten/*/*/*.h",
"torch_npu/csrc/core/*.h",
"torch_npu/csrc/core/*/*.h",
"torch_npu/csrc/libs/*.h",
"torch_npu/csrc/core/*/*/*.h",
"torch_npu/csrc/framework/*.h",
"torch_npu/csrc/framework/*/*.h",
@@ -187,7 +196,7 @@ def copy_hpp():
for src in glob_header_files:
dst = os.path.join(
os.path.join(BASE_DIR, f"libtorch/include/torch_npu"),
os.path.join(BASE_DIR, "libtorch_npu/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))
@@ -196,7 +205,7 @@ def copy_hpp():
ret = get_src_py_and_dst()
for src, dst in ret:
copy_file(src, dst)
move_special_hpp(ret)
def copy_lib():
lib_file = [f"build/{get_build_type()}/packages/torch_npu/lib/*.*"]
@@ -204,7 +213,7 @@ def copy_lib():
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")
dst_path = os.path.join(BASE_DIR, "libtorch_npu/lib")
os.makedirs(dst_path, exist_ok=True)
for src in glob_lib_files:
+71 -37
View File
@@ -19,10 +19,11 @@ import re
import sys
import subprocess
from abc import ABCMeta, abstractmethod
from pathlib import Path
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_DIR = os.path.join(BASE_DIR, 'test')
TEST_OPS = os.path.join(BASE_DIR, 'test/test_ops.py')
@@ -75,8 +76,9 @@ class DirectoryStrategy(AccurateTest):
通过识别测试文件的目录确认需要进行UT的文件
"""
def identify(self, modify_file):
second_dir = modify_file.split("/")[0]
return [os.path.join(BASE_DIR, modify_file)] if second_dir == 'test' else []
is_test_file = modify_file.split("/")[0] == "test" \
and re.match("test_(.+).py", os.path.basename(modify_file))
return [os.path.join(BASE_DIR, modify_file)] if is_test_file else []
class CopyOptStrategy(AccurateTest):
@@ -89,6 +91,43 @@ class CopyOptStrategy(AccurateTest):
return AccurateTest.find_ut_by_regex(regex)
return []
class DirectoryMappingStrategy(AccurateTest):
"""
Map the modified files to the corresponding test cases
"""
mapping_list = {
'contrib': 'test/test_contrib',
'cpp_extension': 'test/test_cpp_extension',
'distributed': 'test/test_distributed',
'fx': 'test/test_fx',
'hooks': 'test/test_hooks',
'optim': 'test/test_optim',
'profiler': 'test/test_profiler',
'onnx': 'test/test_onnx',
'utils': 'test/test_utils',
'testing': 'test/test_testing.py',
}
def identify(self, modify_file):
current_all_ut_path = []
if str(Path(modify_file).parts[0]) == 'torch_npu':
CORE_TEST_LIST = [str(i) for i in (Path(BASE_DIR) / 'test/test_npu').rglob('test_*.py')]
current_all_ut_path = CORE_TEST_LIST
mapped_ut_path = []
module_name = str(Path(modify_file).parts[1])
if module_name in self.mapping_list:
mapped_ut_path.append(self.mapping_list[module_name])
file_name = str(Path(modify_file).stem)
if file_name in self.mapping_list:
mapped_ut_path.append(self.mapping_list[file_name])
for mapped_path in mapped_ut_path:
if Path.is_file(Path(BASE_DIR) / mapped_path):
current_all_ut_path.append(str(Path(BASE_DIR) / mapped_path))
else:
current_all_ut_path += [str(i) for i in (Path(BASE_DIR) / mapped_path).rglob('test_*.py')]
return current_all_ut_path
class TestMgr():
def __init__(self):
@@ -106,10 +145,11 @@ class TestMgr():
def analyze(self):
for modify_file in self.modify_files:
self.test_files['ut_files'] += DirectoryStrategy().identify(modify_file)
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)
self.test_files['ut_files'] += DirectoryMappingStrategy().identify(modify_file)
unique_files = set(self.test_files['ut_files'])
exist_ut_file = [
@@ -118,7 +158,6 @@ class TestMgr():
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_test_files(self):
return self.test_files
@@ -143,20 +182,21 @@ def exec_ut(files):
"""
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
"""
def get_ut_name(ut_file):
def get_op_name(ut_file):
return ut_file.split('/')[-1].split('.')[0].lstrip('test_')
def get_ut_name(ut_file):
return os.path.relpath(ut_file, TEST_DIR)[:-3]
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}'
def get_ut_cmd(ut_type, ut_file):
cmd = [sys.executable, "run_test.py", "-v", "-i"]
if ut_type == "op_ut_files":
return cmd + ["test_ops", "--", "-k", get_op_name(ut_file)]
return cmd + [get_ut_name(ut_file)]
os.chdir(ut_dir)
p = subprocess.Popen(cmd.split(' '), stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
def run_cmd_with_timeout(cmd):
os.chdir(TEST_DIR)
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
try:
msg = p.communicate(timeout=2000)
@@ -175,28 +215,22 @@ def exec_ut(files):
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)
def run_tests(files):
exec_infos = []
has_failed = 0
for ut_type, ut_files in files.items():
for ut_file in ut_files:
cmd = get_ut_cmd(ut_type, ut_file)
ut_info = " ".join(cmd[4:]).replace(" -- -k", "")
ret = run_cmd_with_timeout(cmd)
if ret:
has_failed = ret
exec_infos.append("exec ut {} failed.".format(ut_info))
else:
exec_infos.append("exec ut {} success.".format(ut_info))
return has_failed, exec_infos
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))
ret_status, exec_infos = run_tests(files)
print("***** Total result:")
for exec_info in exec_infos:
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
# 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.
CUR_DIR=$(dirname $(readlink -f $0))
cd ${CUR_DIR}/../examples/libtorch_resnet
if [ -f ./resnet_model.pt ]; then
rm ./resnet_model.pt
fi
python3 resnet_trace.py
if [ $? != 0 ]; then
echo "Failed to trace resnet model."
exit 1
fi
if [ -d "build" ]; then
rm -rf ./build
fi
mkdir build && cd build && \
cmake -DCMAKE_PREFIX_PATH=`python3 -c 'import torch;print(torch.utils.cmake_prefix_path)'` .. && \
make && ./libtorch_resnet ../resnet_model.pt
+11 -3
View File
@@ -23,6 +23,7 @@ from codegen.api import cpp
from codegen.model import (Argument, BaseTy, BaseType, ListType,
NativeFunction, OptionalType, Return, Type,
Variant)
from codegen.autograd.utils import type_wrapper_name
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #
#
@@ -992,13 +993,20 @@ def cpp_record_func(f: NativeFunction, custom=False) -> str:
return record_func
raise RuntimeError(f'could not dispatch, neither function nor method: {f.func}')
def cpp_dispatch_target(f: NativeFunction, custom=False) -> str:
name = cpp.name(f.func)
def cpp_dispatch_target(f: NativeFunction, custom=False, is_npu_autograd=False) -> str:
if is_npu_autograd:
name = type_wrapper_name(f)
else:
name = cpp.name(f.func)
if Variant.method in f.variants and not custom:
return f'self.{name}'
if Variant.function in f.variants:
if custom:
namespace = 'at_npu::native::NPUNativeFunctions'
if is_npu_autograd:
namespace = 'at_npu::autograd::VariableType'
else:
namespace = 'at_npu::native::NPUNativeFunctions'
elif has_tensor_options(f) or f.func.name.name.base.endswith('_like'):
namespace = 'torch'
else:
+1
View File
@@ -49,6 +49,7 @@ intT = BaseCppType('', 'int64_t')
doubleT = BaseCppType('', 'double')
boolT = BaseCppType('', 'bool')
voidT = BaseCppType('', 'void')
longT = BaseCppType('', 'int64_t')
stringT = BaseCppType('c10', 'string_view')
generatorT = BaseCppType('at', 'Generator')
scalarTypeT = BaseCppType('at', 'ScalarType')
View File
+32
View File
@@ -0,0 +1,32 @@
# Copyright (c) 2023 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 functools
from typing import Callable
from codegen.api.autograd import NativeFunctionWithDifferentiabilityInfo as NFWDI
from codegen.context import native_function_manager
from codegen.utils import T
# Like tools.api.context.with_native_function, but for
# NativeFunctionWithDifferentiabilityInfo.
def with_native_function_with_differentiability_info(func: Callable[[NFWDI], T]) -> Callable[[NFWDI], T]:
@functools.wraps(func)
def wrapper(f: NFWDI) -> T:
with native_function_manager(f.func):
return func(f)
return wrapper
+6
View File
@@ -0,0 +1,6 @@
# Defines derivative formulas and Python signatures of methods on Variable
#
#If you need any guidance, please refer to the comments in derivatives.yaml in PyTorch.
- name: fast_gelu(Tensor self) -> Tensor
self: fast_gelu_backward(grad, self)
+139
View File
@@ -0,0 +1,139 @@
# Copyright (c) 2023 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.
"""
To run this file by hand from the root of the PyTorch
repository, run:
python -m codegen.autograd.gen_autograd \
--native_functions_dir="./codegen/native_functions.yaml" \
--npu_native_function_dir="./torch_npu/csrc/aten/npu_native_functions.yaml" \
--out_dir=$OUTPUT_DIR \
--autograd_dir="./codegen/autograd/"
Where $OUTPUT_DIR is where you would like the files to be
generated. In the full build system, OUTPUT_DIR is
torch_npu/csrc/aten/
"""
# gen_autograd.py generates C++ autograd functions and Python bindings.
#
# It delegates to the following scripts:
#
# gen_autograd_functions.py: generates subclasses of torch::autograd::Node
# gen_variable_type.py: generates VariableType.h which contains all tensor methods
# gen_python_functions.py: generates Python bindings to THPVariable
#
import argparse
import os
from typing import List, Sequence
from codegen.api.autograd import (
match_differentiability_info, NativeFunctionWithDifferentiabilityInfo,
DifferentiabilityInfo
)
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
from codegen.model import NativeFunction
from .gen_autograd_functions import gen_autograd_functions_lib
from .gen_variable_type import (
gen_variable_type, gen_npu_variable_type,
NPU_AUTOGRAD_FUNCTION, gen_variable_type_head
)
from .gen_inplace_or_view_type import gen_inplace_or_view_type
from .gen_variable_factories import gen_variable_factories
from .load_derivatives import load_derivatives
def gen_autograd(
native_functions_path: str,
out: str,
autograd_dir: str,
npu_native_functions_path: str
) -> None:
differentiability_infos = load_derivatives(
os.path.join(autograd_dir, 'derivatives.yaml'), native_functions_path, npu_native_functions_path)
template_path = os.path.join(autograd_dir, 'templates')
native_funcs = parse_native_and_custom_yaml(native_functions_path, npu_native_functions_path).native_functions
funcs = filte_out_native_autograd_function(native_funcs, differentiability_infos)
funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
funcs_with_diff_infos = match_differentiability_info(funcs, differentiability_infos)
torch_funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
npu_funcs_with_diff_infos: List[NativeFunctionWithDifferentiabilityInfo] = []
for func in funcs_with_diff_infos:
f = func.func
name = str(f.func.name)
if name in NPU_AUTOGRAD_FUNCTION:
npu_funcs_with_diff_infos.append(func)
else:
torch_funcs_with_diff_infos.append(func)
# Generate VariableType.h/cpp
gen_variable_type(out, torch_funcs_with_diff_infos, template_path)
gen_npu_variable_type(out, npu_funcs_with_diff_infos, template_path)
gen_variable_type_head(out, funcs_with_diff_infos, template_path)
gen_inplace_or_view_type(out, funcs_with_diff_infos, template_path)
# Generate Functions.h/cpp
gen_autograd_functions_lib(out, differentiability_infos, template_path)
# Generate variable_factories.h
gen_variable_factories(out, native_functions_path, npu_native_functions_path, template_path)
def filte_out_native_autograd_function(
native_funcs: List[NativeFunction],
differentiability_infos: Sequence[DifferentiabilityInfo],
):
result: List[NativeFunction] = []
derivatives_name_list: List[str] = []
for info in differentiability_infos:
derivatives_name_list.append(str(info.func.func.name))
for funcs in native_funcs:
func_name = str(funcs.func.name)
func_base_name = str(funcs.func.name.name.base)
if (func_name in derivatives_name_list) or (func_base_name in derivatives_name_list):
result.append(funcs)
return result
def main() -> None:
parser = argparse.ArgumentParser(
description='Generate autograd C++ files')
parser.add_argument('--native_functions_dir', metavar='NATIVE',
help='path to native_functions.yaml')
parser.add_argument('--out_dir', metavar='OUT',
help='path to output directory')
parser.add_argument('--autograd_dir', metavar='AUTOGRAD',
help='path to autograd directory')
parser.add_argument('--npu_native_function_dir',
help='path to npu_native_functions.yaml')
args = parser.parse_args()
gen_autograd(args.native_functions_dir,
args.out_dir,
args.autograd_dir,
args.npu_native_function_dir)
if __name__ == '__main__':
main()
+583
View File
@@ -0,0 +1,583 @@
# Copyright (c) 2023 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.
# Generates C++ autograd functions for the derivatives of ATen operations
#
# This writes two files:
# Functions.h/cpp: subclasses of autograd::Node
# python_functions.h/cpp: Python bindings for the above classes
#
from typing import List, Sequence, Tuple
from codegen.api.autograd import (
Derivative, DifferentiabilityInfo,
SavedAttribute, uses_retain_variables,
uses_single_grad
)
from codegen.api.types import (
Binding, BaseCType, OptionalCType, tensorT, longT,
doubleT, scalarT, stringT, boolT, intArrayRefT,
tensorListT, MutRefCType, ListCType, ArrayRefCType
)
from codegen.code_template import CodeTemplate
from codegen.gen import FileManager
from codegen.model import Argument
from .gen_inplace_or_view_type import VIEW_FUNCTIONS
FUNCTION_DECLARATION = CodeTemplate("""\
struct TORCH_API ${op} : public ${superclass} {
using ${superclass}::${superclass};
variable_list apply(variable_list&& grads) override;
std::string name() const override { return "${op}"; }
void release_variables() override {
${thread_lock}
${release_variables}
}
${will_release_variables}
${saved_variables}
${saved_list_sizes}
};
""")
WILL_RELEASE_VARIABLES = CodeTemplate("""\
bool retain_variables = true;
void will_release_variables() override {
retain_variables = false;
}
""")
FUNCTION_DEFINITION = CodeTemplate("""\
variable_list ${op}::apply(variable_list&& grads) {
${thread_lock}
${asserts}
IndexRangeGenerator gen;
${compute_index_ranges}
variable_list grad_inputs(gen.size());
${body}
return grad_inputs;
}
""")
GRAD_INPUT_MASK = CodeTemplate("""\
auto grad_input_mask = std::array<bool, ${n}>{
${masks}
};\
""")
DERIVATIVE_SINGLE = CodeTemplate("""\
if (should_compute_output({ ${name}_ix })) {
auto grad_result = ${derivative};
copy_range(grad_inputs, ${name}_ix, grad_result);
}
""")
DERIVATIVE_MULTI_COPY_RANGE = CodeTemplate("""\
if (should_compute_output({ ${name}_ix })) {
copy_range(grad_inputs, ${name}_ix, std::get<${i}>(grad_result));
}
""")
DERIVATIVE_MULTI = CodeTemplate("""\
if (should_compute_output({ ${idx_ranges} })) {
${grad_input_mask}
auto grad_result = ${derivative};
${copy_ranges}
}
""")
# Generates python bindings
#
# This generates the definitions for:
# (1) The PyTypeObject for each backward grad_fn subclassing Node
# (2) The entry for PyTypeObject's tp_getset slot (an array of PyGetSetDef structs)
# We generate one PyGetSetDef struct for each of grad_fn's saved inputs and outputs
# Each PyGetSetDef has a function ptr to a getter, also defined here (3).
# (3) Getters for each of grad_fn's saved inputs and outputs.
#
PY_FUNCTION_DEFINITION = CodeTemplate("""\
static PyTypeObject ${op}Class;
addClass<${op}>(${op}Class, "${op}", ${op}_properties);
""")
PY_FUNCTION_PROPS_AND_GETTERS = CodeTemplate("""\
${all_getter_definitions}
static struct PyGetSetDef ${op}_properties[] = {
THP_FUNCTION_DEFAULT_PROPERTIES,
${all_getsetdef_structs}
{nullptr} /* sentinel */
};
""")
PY_GETSETDEF_STRUCT = CodeTemplate("""\
{(char*)"_saved_${name}", (getter)THP${op}_${name}_getter, nullptr, nullptr, nullptr}""")
PY_RAW_GETSETDEF_STRUCT = CodeTemplate("""\
{(char*)"_raw_saved_${name}", (getter)THP${op}_${name}_raw_getter, nullptr, nullptr, nullptr}""")
# Getter templates
GETTER_DEFINITION = CodeTemplate("""\
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
auto prop = static_cast<${op}*>(self->cdata.get())->${name};
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_SAVEDVAR = CodeTemplate("""\
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_RAW_SAVEDVAR = CodeTemplate("""\
PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
const auto& prop = static_cast<${op}*>(self->cdata.get())->${name}_;
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_VEC_SAVEDVAR = CodeTemplate("""\
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
const auto *node = static_cast<${op}*>(self->cdata.get());
const auto& prop = node->${name}_;
if (node->${name}_released_) {
PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
return nullptr;
}
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_RAW_VEC_SAVEDVAR = CodeTemplate("""\
PyObject* THP${op}_${name}_raw_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
const auto *node = static_cast<${op}*>(self->cdata.get());
const auto& prop = node->${name}_;
if (node->${name}_released_) {
PyErr_SetString(PyExc_RuntimeError, ERR_BACKWARD_TWICE);
return nullptr;
}
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_OPT = CodeTemplate("""\
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
if (!opt_prop.has_value()) {
Py_RETURN_NONE;
}
auto prop = opt_prop.value();
${body}
END_HANDLE_TH_ERRORS
}
""")
GETTER_DEFINITION_OPT_ARRAYREF = CodeTemplate("""\
PyObject* THP${op}_${name}_getter(THPCppFunction *self, void *_unused) {
HANDLE_TH_ERRORS
auto opt_prop = static_cast<${op}*>(self->cdata.get())->${name};
if (!opt_prop.list.has_value()) {
Py_RETURN_NONE;
}
auto prop = opt_prop.list.value();
${body}
END_HANDLE_TH_ERRORS
}
""")
# Getter body
GETTER_BODY_SAVEDVAR = """\
return THPVariable_Wrap(prop.unpack(self->cdata));
"""
GETTER_BODY_RAW_SAVEDVAR = """\
pybind11::object obj = pybind11::cast(prop, pybind11::return_value_policy::reference);
return obj.release().ptr();
"""
GETTER_BODY_VEC_SAVEDVAR = """\
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
for (int i = 0; i < prop.size(); i++) {
PyTuple_SetItem(tup, (Py_ssize_t) i, THPVariable_Wrap(prop[i].unpack(self->cdata)));
}
return tup;
"""
GETTER_BODY_RAW_VEC_SAVEDVAR = """\
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
for (int i = 0; i < prop.size(); i++) {
pybind11::object obj = pybind11::cast(prop[i], pybind11::return_value_policy::reference);
PyTuple_SetItem(tup, (Py_ssize_t) i, obj.release().ptr());
}
return tup;
"""
GETTER_BODY_ARRAYREF_LONG = """\
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
for (int i = 0; i < prop.size(); i++) {
PyTuple_SetItem(tup, (Py_ssize_t) i, PyLong_FromUnsignedLong((uint64_t) prop[i]));
}
return tup;
"""
GETTER_BODY_ARRAYREF_DOUBLE = """\
PyObject* tup = PyTuple_New((Py_ssize_t) prop.size());
for (int i = 0; i < prop.size(); i++) {
PyTuple_SetItem(tup, (Py_ssize_t) i, PyFloat_FromDouble((double) prop[i]));
}
return tup;
"""
GETTER_BODY_INT64_T = """\
return PyLong_FromUnsignedLong((int64_t) prop);
"""
GETTER_BODY_DOUBLE = """\
return PyFloat_FromDouble((double) prop);
"""
GETTER_BODY_BOOL = """\
if (prop) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
"""
GETTER_BODY_STRING = """\
return PyUnicode_FromStringAndSize(prop.data(), prop.size());
"""
GETTER_BODY_SCALAR = """\
if (prop.isComplex()) {
auto cprop = prop.to<c10::complex<double>>();
return PyComplex_FromDoubles(cprop.real(), cprop.imag());
} else if (prop.isFloatingPoint()) {
return PyFloat_FromDouble(prop.to<double>());
} else if (prop.isIntegral(/*includeBool=*/false)) {
return PyLong_FromLong(prop.to<int64_t>());
} else if (prop.isBoolean()) {
if (prop.to<bool>()) {
Py_RETURN_TRUE;
} else {
Py_RETURN_FALSE;
}
} else {
PyErr_SetString(PyExc_RuntimeError, "Unknown scalar type");
return nullptr;
}
"""
MISC_GETTER_DEFS = {
OptionalCType(BaseCType(longT)): (GETTER_DEFINITION_OPT, GETTER_BODY_INT64_T),
BaseCType(doubleT): (GETTER_DEFINITION, GETTER_BODY_DOUBLE),
OptionalCType(BaseCType(doubleT)): (GETTER_DEFINITION_OPT, GETTER_BODY_DOUBLE),
BaseCType(boolT): (GETTER_DEFINITION, GETTER_BODY_BOOL),
BaseCType(scalarT): (GETTER_DEFINITION, GETTER_BODY_SCALAR),
OptionalCType(BaseCType(scalarT)): (GETTER_DEFINITION_OPT, GETTER_BODY_SCALAR),
}
# These functions have backwards which cannot be traced, and so must have
# their backward functions traced opaquely.
# VIEW_FUNCTIONS are not traceable because they use as_strided, which
# has an untraceable backwards, see
# https://github.com/pytorch/pytorch/issues/4250
# TODO: This is probably not exhaustive, but it's a start
UNTRACEABLE_FUNCTIONS = VIEW_FUNCTIONS
def gen_autograd_functions_lib(
out: str,
differentiability_infos: Sequence[DifferentiabilityInfo],
template_path: str,
) -> None:
"""Functions.h and Functions.cpp body
These contain the auto-generated subclasses of torch::autograd::Node
for each every differentiable torch function.
"""
# only create an autograd function if we are actually going to calculate a derivative
infos = list(filter(lambda info: info.args_with_derivatives, differentiability_infos))
declarations = list(map(lambda f: process_function(f, FUNCTION_DECLARATION), infos))
definitions = list(map(lambda f: process_function(f, FUNCTION_DEFINITION), infos))
file_basename = 'Functions'
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
for suffix in ['.h', '.cpp']:
fname = file_basename + suffix
fm.write_with_template(fname, fname, lambda: {
'generated_comment': '@' + f'generated from {fm.template_dir}/' + fname,
'autograd_function_declarations': declarations,
'autograd_function_definitions': definitions,
})
def gen_autograd_functions_python(
out: str,
differentiability_infos: Sequence[DifferentiabilityInfo],
template_path: str,
) -> None:
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
num_shards = 5
fm.write('python_functions.h', lambda: {
'generated_comment': f'@generated from {fm.template_dir}/python_functions.h',
'shard_forward_declare': [
f"void initialize_autogenerated_functions_{i}();"
for i in range(num_shards)
],
'shard_call': [
f"initialize_autogenerated_functions_{i}();"
for i in range(num_shards)
]
})
infos = list(filter(lambda info: info.args_with_derivatives, differentiability_infos))
fm.write_sharded(
'python_functions.cpp',
infos,
key_fn=lambda info: info.name,
base_env={
'generated_comment': f'@generated from {fm.template_dir}/python_functions.cpp',
},
env_callable=lambda info: {
'py_function_initializers': [process_function(info, PY_FUNCTION_DEFINITION)],
'py_function_props_and_getters': [process_function(info, PY_FUNCTION_PROPS_AND_GETTERS)],
},
num_shards=num_shards,
sharded_keys={'py_function_initializers', 'py_function_props_and_getters'}
)
def process_function(info: DifferentiabilityInfo, template: CodeTemplate) -> str:
saved_variables: List[str] = []
release_variables: List[str] = []
saved_list_sizes: List[str] = []
unpack: List[str] = []
asserts: List[str] = []
compute_index_ranges: List[str] = []
getter_definitions: List[str] = []
py_getsetdef_structs: List[str] = []
for arg in info.args_with_derivatives:
if arg.type == 'at::TensorList' or arg.type == 'const c10::List<c10::optional<at::Tensor>> &':
size = f'{arg.name}_size_'
saved_list_sizes.append(f'size_t {arg.name}_size_;')
else:
size = '1'
compute_index_ranges.append(f'auto {arg.name}_ix = gen.range({size});')
def save_var(var: SavedAttribute, is_output: bool) -> None:
name = var.nctype.name
func_type = var.nctype.type
should_append_getsetdef = True
should_append_raw_getsetdef = False
if func_type == BaseCType(tensorT) or func_type == OptionalCType(BaseCType(tensorT)) or \
func_type == MutRefCType(OptionalCType(BaseCType(tensorT))) or \
(func_type == BaseCType(scalarT) and is_output):
saved_variables.append(f'SavedVariable {name}_;')
release_variables.append(f'{name}_.reset_data();')
ptr = 'shared_from_this()' if is_output else ''
unpack.append(f'auto {name} = {name}_.unpack({ptr});')
getter_definitions.append(GETTER_DEFINITION_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_SAVEDVAR))
getter_definitions.append(GETTER_DEFINITION_RAW_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_RAW_SAVEDVAR))
should_append_raw_getsetdef = True
elif func_type == BaseCType(tensorListT):
saved_variables.append(f'std::vector<SavedVariable> {name}_;')
saved_variables.append(f'bool {name}_released_ = false;')
# Just clear() is sufficient, we don't need to loop and clear each variable.
# Because the SavedVariable owns a tensor and a grad_fn,
# removing the SavedVariable makes them go away as well.
release_variables.append(f'{name}_.clear();')
release_variables.append(f'{name}_released_ = true;')
unpack.append(f'auto {name} = unpack_list({name}_);')
asserts.append(f'TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);')
getter_definitions.append(GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR))
getter_definitions.append(GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR))
should_append_raw_getsetdef = True
elif func_type == ListCType(OptionalCType(BaseCType(tensorT))):
saved_variables.append(f'std::vector<SavedVariable> {name}_;')
saved_variables.append(f'bool {name}_released_ = false;')
# Just clear() is sufficient, we don't need to loop and clear each variable.
# Because the SavedVariable owns a tensor and a grad_fn,
# removing the SavedVariable makes them go away as well.
release_variables.append(f'{name}_.clear();')
release_variables.append(f'{name}_released_ = true;')
unpack.append(f'auto {name} = unpack_opt_list({name}_);')
asserts.append(f'TORCH_CHECK(!{name}_released_, ERR_BACKWARD_TWICE);')
getter_definitions.append(GETTER_DEFINITION_VEC_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_VEC_SAVEDVAR))
getter_definitions.append(GETTER_DEFINITION_RAW_VEC_SAVEDVAR.substitute(
op=info.op, name=name, body=GETTER_BODY_RAW_VEC_SAVEDVAR))
should_append_raw_getsetdef = True
elif func_type == BaseCType(intArrayRefT):
saved_variables.append(f'std::vector<int64_t> {name};')
getter_definitions.append(GETTER_DEFINITION.substitute(
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG))
elif func_type == OptionalCType(BaseCType(intArrayRefT)):
saved_variables.append(f'c10::OptionalArray<int64_t> {name};')
getter_definitions.append(GETTER_DEFINITION_OPT_ARRAYREF.substitute(
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_LONG))
elif func_type == OptionalCType(ArrayRefCType(BaseCType(doubleT))):
saved_variables.append(f'c10::OptionalArray<double> {name};')
getter_definitions.append(GETTER_DEFINITION_OPT_ARRAYREF.substitute(
op=info.op, name=name, body=GETTER_BODY_ARRAYREF_DOUBLE))
elif func_type == BaseCType(longT):
saved_variables.append(f'{func_type.cpp_type()} {name} = 0;')
getter_definitions.append(GETTER_DEFINITION.substitute(
op=info.op, name=name, body=GETTER_BODY_INT64_T))
elif func_type == BaseCType(stringT):
saved_variables.append(f'std::string {name};')
getter_definitions.append(GETTER_DEFINITION.substitute(
op=info.op, name=name, body=GETTER_BODY_STRING))
elif func_type == OptionalCType(BaseCType(stringT)):
saved_variables.append(f'c10::optional<std::string> {name};')
getter_definitions.append(GETTER_DEFINITION_OPT.substitute(
op=info.op, name=name, body=GETTER_BODY_STRING))
else:
saved_variables.append(f'{func_type.cpp_type()} {name};')
if func_type in MISC_GETTER_DEFS:
getter_def, body = MISC_GETTER_DEFS[func_type]
getter_definitions.append(getter_def.substitute(op=info.op, name=name, body=body))
else:
# Types we don't expose python bindings to yet:
# TypeAndSize, at::ScalarType, TensorOptions, TensorGeometry,
# std::vector<std::vector<int64_t>>, std::vector<at::ScalarType>
should_append_getsetdef = False
if should_append_getsetdef:
py_getsetdef_structs.append(PY_GETSETDEF_STRUCT.substitute(op=info.op, name=name))
if should_append_raw_getsetdef:
py_getsetdef_structs.append(PY_RAW_GETSETDEF_STRUCT.substitute(op=info.op, name=name))
for var in info.all_saved_inputs:
save_var(var, is_output=False)
for var in info.all_saved_outputs:
save_var(var, is_output=True)
# lock the mutex when we release variables and in Node::apply to protect thread safety
# see Note [Thread Safety on Autograd Node]
if len(release_variables) > 0:
thread_lock = 'std::lock_guard<std::mutex> lock(mutex_);'
else:
thread_lock = ''
if uses_retain_variables(info):
will_release_variables = WILL_RELEASE_VARIABLES.substitute()
else:
will_release_variables = ''
body: List[str] = []
if uses_single_grad(info):
body.append('const auto& grad = grads[0];')
else:
# Generate aliases for gradients named for returned values.
body.extend(
f'const auto& {name} = grads[{info.available_named_gradients.index(name)}];'
for name in info.used_named_gradients)
def emit_derivative(
derivative: Derivative,
args_with_derivatives: Sequence[Binding],
) -> Tuple[bool, str]:
formula = derivative.formula
var_names = derivative.var_names
if len(var_names) == 1:
checks_any_grad_defined = False
if 'not_implemented' not in formula:
matching_args = [
arg for arg in args_with_derivatives
if arg.name == var_names[0]]
if len(matching_args) == 1:
# We can add undefined grad support if the input variable is a Tensor
arg = matching_args[0]
if isinstance(arg.argument, Argument) and str(arg.argument.type) in ('Tensor', 'Tensor?'):
formula = 'any_grad_defined ? (' + formula + ') : Tensor()'
checks_any_grad_defined = True
return (checks_any_grad_defined,
DERIVATIVE_SINGLE.substitute(name=var_names[0], derivative=formula))
else:
if 'grad_input_mask' in formula:
masks = [f'should_compute_output({{ {n}_ix }}),' for n in var_names]
grad_input_mask = GRAD_INPUT_MASK.substitute(masks=masks, n=len(var_names))
else:
grad_input_mask = ''
idx_ranges = ', '.join(f'{n}_ix' for n in var_names)
copy_ranges: List[str] = []
for i, n in enumerate(var_names):
copy_ranges.append(DERIVATIVE_MULTI_COPY_RANGE.substitute(name=n, i=i))
return False, DERIVATIVE_MULTI.substitute(
idx_ranges=idx_ranges, copy_ranges=copy_ranges,
derivative=formula,
grad_input_mask=grad_input_mask)
body.extend(unpack)
need_any_grad_defined_var = False
for derivative in info.derivatives:
checks_any_grad_defined, derivative_text = emit_derivative(derivative, info.args_with_derivatives)
body.append(derivative_text)
need_any_grad_defined_var |= checks_any_grad_defined
# Since single-output derivative formulas need to check if grads are
# defined, only perform the check once, before all the formulas
if need_any_grad_defined_var:
body.insert(-len(info.derivatives),
'bool any_grad_defined = any_variable_defined(grads);')
if info.name in UNTRACEABLE_FUNCTIONS:
superclass = 'Node'
else:
superclass = 'TraceableFunction'
all_getsetdef_structs = ",\n".join(py_getsetdef_structs) + "," if len(py_getsetdef_structs) != 0 else ""
all_getter_definitions = "\n".join(getter_definitions)
return template.substitute(
op=info.op,
compute_index_ranges=compute_index_ranges,
saved_variables=saved_variables,
release_variables=release_variables,
saved_list_sizes=saved_list_sizes,
asserts=asserts,
thread_lock=thread_lock,
will_release_variables=will_release_variables,
body=body,
superclass=superclass,
all_getter_definitions=all_getter_definitions,
all_getsetdef_structs=all_getsetdef_structs
)
@@ -0,0 +1,486 @@
# Copyright (c) 2023 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.
# Generates ADInplaceOrViewType.h/cpp
#
from typing import List, Optional, Sequence, Tuple, Dict
from codegen.api import cpp
from codegen.api.autograd import (
NativeFunctionWithDifferentiabilityInfo,
gen_differentiable_outputs,
dispatch_strategy,
)
from codegen.api.types import (
Binding, CType, BaseCType,
OptionalCType, longT, boolT, intArrayRefT
)
from codegen.api.signature import DispatcherSignature
from codegen.code_template import CodeTemplate
from codegen.context import with_native_function
from codegen.model import (
Type, NativeFunction, SelfArgument,
TensorOptionsArguments, SchemaKind, is_foreach_op,
)
from codegen.gen import FileManager
from .context import with_native_function_with_differentiability_info
from .utils import (
MANUAL_BACKEND, MANUAL_AUTOGRAD_AND_TRACER, type_wrapper_name,
tie_return_values, get_return_value
)
# See NOTE [ Autograd View Variables ] in variable.h for details.
# If you update list VIEW_FUNCTIONS or RETURNS_VIEWS_OF_INPUT,
# you **MUST** also update the public list of view ops accordingly in
# docs/source/tensor_view.rst. Note not all ATen functions are exposed to public,
# e.g alias & sparse_coo_tensor_with_dims_and_tensors.
#
# A map: function name => name of the argument that all outputs are view of
VIEW_FUNCTIONS_WITH_METADATA_CHANGE = [
'view_as_complex',
'view_as_real',
'_conj',
'_neg_view'
]
VIEW_FUNCTIONS = {
'numpy_T': 'self',
'alias': 'self',
'as_strided': 'self',
'diagonal': 'self',
'expand': 'self',
'permute': 'self',
'select': 'self',
'slice': 'self',
'split': 'self',
'split_with_sizes': 'self',
'squeeze': 'self',
't': 'self',
'transpose': 'self',
'unfold': 'self',
'unsqueeze': 'self',
'flatten': 'self',
'view': 'self',
'unbind': 'self',
'_indices': 'self',
'_values': 'self',
'indices': 'self',
'values': 'self',
'crow_indices': 'self',
'col_indices': 'self',
# sparse_coo ctor output should really be views of both indices and values,
# but we only supports making as view of a single variable, and indices is
# discrete anyways.
# FIXME: clone indices on construction.
'sparse_coo_tensor_with_dims_and_tensors': 'values',
'_reshape_alias': 'self',
}
for key in VIEW_FUNCTIONS_WITH_METADATA_CHANGE:
VIEW_FUNCTIONS[key] = 'self'
MANUAL_AUTOGRAD = MANUAL_BACKEND | MANUAL_AUTOGRAD_AND_TRACER
# note: some VIEW_FUNCTIONS are just compositions of the view functions above
# this list contains both the root view functions and any that are purely composed
# of viewing functions, and is used by the JIT to determine when an operator
# may return a view of its inputs; however they may sometimes return a copy.
# (e.g. `contiguous`)
RETURNS_VIEWS_OF_INPUT = set(VIEW_FUNCTIONS.keys()).union({
'chunk', 'detach', 'contiguous', 'reshape', 'reshape_as',
'expand_as', 'view_as', 'real', 'imag', 'narrow', 'movedim',
'tensor_split', 'swapdims', 'swapaxes', 'mT', 'mH', 'adjoint', 'matrix_H'
})
# These are the functions we consider views for the purposes of validating
# StorageImpl and TensorImpl in gen_variable_type.
# `_unsafe_view` is not included in VIEW_FUNCTIONS above because it is not a
# view for the purposes of ADInplaceOrView kernel, we do not want to call as_view
# See NOTE [Unsafe View] for more info.
ALL_VIEW_FUNCTIONS = {
**VIEW_FUNCTIONS,
'_unsafe_view': 'self',
}
ARRAYREF_TO_VEC = CodeTemplate("""\
auto ${vec} = ${arg}.vec();
""")
OPTIONAL_TO_VAL = CodeTemplate("""\
auto ${val} = ${arg}.value_or(${default});
""")
CALL_DISPATCH = CodeTemplate("""\
at::_ops::${unambiguous_name}::call(${unpacked_args})""")
SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE = CodeTemplate("""\
std::function<at::Tensor(const at::Tensor&)> func=nullptr;
if (${is_view_with_metadata_change} || !self.unsafeGetTensorImpl()->support_as_strided()) {
${replay_view_func}
}
""")
REPLAY_VIEW_LAMBDA_FUNC = CodeTemplate("""\
func = [=](const at::Tensor& ${input_base}) {
return ${replay_view_call};
};
""")
METHOD_DEFINITION = CodeTemplate("""\
${return_type} ${type_wrapper_name}(${formals}) {
${type_definition_body}
}
""")
WRAPPER_REGISTRATION = CodeTemplate("""\
m.impl("${unqual_operator_name_with_overload}",
TORCH_FN(${class_type}::${type_wrapper_name})
);
""")
AUTOGRAD_NOT_IMPLEMENTED_REGISTRATION = CodeTemplate("""\
m.impl("${unqual_operator_name_with_overload}", torch::autograd::autogradNotImplementedFallback());
""")
INPLACE_REDISPATCH = CodeTemplate("""\
{
at::AutoDispatchBelowADInplaceOrView guard;
at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
}
""")
ASSIGN_RETURN_VALUE = CodeTemplate("""\
${return_values} = ${rhs_value};
""")
VIEW_REDISPATCH = CodeTemplate("""\
${assign_return_values} ([&]() {
at::AutoDispatchBelowADInplaceOrView guard;
return at::_ops::${unambiguous_name}::redispatch(${unpacked_args});
})();
""")
TMP_VAR = '_tmp'
# FIXME: Ideally these functions should be methods on Type class, but we have a
# comment in codegen/model.py there saying these concepts are not well defined.
# Thus we put a version that commonly used by autograd codegen here.
def is_tensor_type(t: Type) -> bool:
# TODO: Should handle optional here?
return t.is_tensor_like() and t.is_list_like() is None
def is_tensor_list_type(t: Type) -> bool:
# TODO: Should handle optional here?
return t.is_tensor_like() and t.is_list_like() is not None
UNPACK_TENSOR = CodeTemplate("""\
auto${ref} ${arg_name}_ = unpack${suffix}(${arg_name}, "${arg_name}", ${arg_pos});""")
def unpacked_name(arg_name: str) -> str:
return arg_name + '_'
@with_native_function
def unpack_args(f: NativeFunction) -> Tuple[List[str], List[Binding]]:
body: List[str] = []
unpacked_bindings: List[Binding] = []
bindings = [r for a in f.func.schema_order_arguments()
for r in cpp.argument(a,
method=False,
cpp_no_default_args=set(),
faithful=False,
has_tensor_options=False)]
for i, binding in enumerate(bindings):
assert not isinstance(binding.argument, SelfArgument)
if isinstance(binding.argument, TensorOptionsArguments):
raise RuntimeError("VariableKernel shouldn't take TensorOptions")
is_nullable = binding.argument.type.is_nullable()
if not binding.argument.type.is_tensor_like() or is_nullable:
unpacked_bindings.append(binding)
continue
is_tensor_list = is_tensor_list_type(binding.argument.type)
ref = (not is_nullable) and not is_tensor_list
suffix = '_opt' if is_nullable and not is_tensor_list else ''
body.append(UNPACK_TENSOR.substitute(
arg_name=binding.name,
arg_pos=i,
suffix=suffix,
ref='&' if ref else '',
))
unpacked_bindings.append(Binding(
name=unpacked_name(binding.name),
nctype=binding.nctype,
argument=binding.argument,
default=binding.default,
))
return body, unpacked_bindings
def get_base_name(f: NativeFunction) -> str:
return f.func.name.name.base # TODO: should be str(f.func.name.name)?
def get_view_info(f: NativeFunction) -> Optional[str]:
base_name = get_base_name(f)
view_info = VIEW_FUNCTIONS.get(base_name, None)
if view_info is None and base_name in RETURNS_VIEWS_OF_INPUT:
view_info = "self"
return view_info
# For view replay calls, we generate an ordinary Dispatcher::call() instead, because:
# - We want to replay the entire call into the op, including any previously-set dispatch keys (including autograd!).
# - The view replay call also is not part of the hot path.
def emit_view_call(f: NativeFunction, input_base: str, unpacked_args: Sequence[str]) -> str:
# View replay functions use the standard Dispatcher::call API.
return CALL_DISPATCH.substitute(
unambiguous_name=f.func.name.unambiguous_name(),
unpacked_args=unpacked_args)
def emit_view_lambda(f: NativeFunction, unpacked_bindings: List[Binding]) -> str:
"""
Generate an additional lambda function to recover views in backward when as_strided is not supported.
See Note [View + Inplace update for base tensor] and [View + Inplace update for view tensor] for more details.
"""
input_base = 'input_base'
replay_view_func = ''
updated_unpacked_args: List[str] = []
known_view_arg_simple_types: List[CType] = [
BaseCType(longT),
OptionalCType(BaseCType(longT)),
BaseCType(boolT),
BaseCType(intArrayRefT)]
for unpacked_binding in unpacked_bindings:
arg, arg_type = unpacked_binding.name, unpacked_binding.nctype.type
if arg == 'self_':
updated_unpacked_args.append(input_base)
continue
if arg_type not in known_view_arg_simple_types:
known_types_str = ', '.join([str(t) for t in known_view_arg_simple_types])
raise TypeError(f'You are adding an {arg_type} {arg} argument to '
f'op {cpp.name(f.func)} in addition to known types: '
f'{known_types_str}. Please update the list or materialize it so that it can be closed '
'over by value, also add a test in pytorch/xla/test/test_operations.py where this code '
'is exercised.')
if arg_type == BaseCType(intArrayRefT):
# It's not safe to close over IntArrayRef by value, since this is a
# reference type, so materialize a vector to close over by value
arg_vec = arg + '_vec'
replay_view_func += ARRAYREF_TO_VEC.substitute(arg=arg, vec=arg_vec)
updated_unpacked_args.append(arg_vec)
elif arg_type == OptionalCType(BaseCType(longT)):
# Materialize int64_t? to int64_t
arg_value = arg + '_val'
replay_view_func += OPTIONAL_TO_VAL.substitute(arg=arg, val=arg_value, default='0')
updated_unpacked_args.append(arg_value)
else:
updated_unpacked_args.append(arg)
replay_view_call = emit_view_call(f, input_base, updated_unpacked_args)
replay_view_func += REPLAY_VIEW_LAMBDA_FUNC.substitute(
input_base=input_base,
replay_view_call=replay_view_call)
is_view_with_metadata_change = 'true' if cpp.name(f.func) in VIEW_FUNCTIONS_WITH_METADATA_CHANGE else 'false'
return SETUP_REPLAY_VIEW_IF_NOT_SUPPORT_AS_STRIDED_OR_VIEW_WITH_METADATA_CHANGE.substitute(
is_view_with_metadata_change=is_view_with_metadata_change,
replay_view_func=replay_view_func)
def emit_view_body(fn: NativeFunctionWithDifferentiabilityInfo, var: str) -> Tuple[str, str]:
# See NOTE [ Autograd View Variables ] in variable.h for details.
f = fn.func
base_name = get_base_name(f)
view_info = get_view_info(f)
call = ''
differentiable_outputs = gen_differentiable_outputs(fn)
differentiable_output_vars = {r.name for r in differentiable_outputs}
if not isinstance(view_info, str):
raise TypeError(f'The view info should be a string for {base_name}, but it is: {view_info}')
if len(differentiable_output_vars) == 0:
# no output is differentiable (.indices() for SparseTensors for example)
rhs_value = (f'as_view({view_info}, {var}, '
f'/* is_bw_differentiable */ false, /* is_fw_differentiable */ false)')
elif len(differentiable_output_vars) == 1:
# Single differentiable output (Tensor or Tensor[])
return_info = differentiable_outputs[0]
# We only support simple Tensor or a TensorList for functions that return views
if not is_tensor_type(return_info.type) and not is_tensor_list_type(return_info.type):
raise RuntimeError(f'{base_name} that return differentiable views can only return Tensor or Tensor[]')
# See Note [ View + Inplace detection]
def get_creation_meta_in_mode(original: str) -> str:
creation_meta_with_grad_mode = f'(at::GradMode::is_enabled() ? {original} : CreationMeta::NO_GRAD_MODE)'
return f'InferenceMode::is_enabled() ? CreationMeta::INFERENCE_MODE : {creation_meta_with_grad_mode}'
# Only allow rebasing of the history if we return a single Tensor
# If we are in a no grad block, raise a warning
# See NOTE [ View + Inplace detection ] for more details about this logic
if is_tensor_list_type(return_info.type):
creation_meta = get_creation_meta_in_mode('CreationMeta::MULTI_OUTPUT_NODE')
call += (f'as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, '
'/* is_fw_differentiable */ true, '
f'/* creation_meta */ {creation_meta});')
rhs_value = f'std::move({var})'
else:
_, unpacked_bindings = unpack_args(f)
call += emit_view_lambda(f, unpacked_bindings)
creation_meta = get_creation_meta_in_mode('CreationMeta::DEFAULT')
rhs_value = (f'as_view(/* base */ {view_info}, /* output */ {var}, /* is_bw_differentiable */ true, '
'/* is_fw_differentiable */ true, '
f'/* view_func */ func, /* creation_meta */ {creation_meta})')
else:
# This could be supported but we don't need it at the moment, so keeping things simple.
raise RuntimeError('Function that return multiple differentiable output '
'when at least one of them is view is not supported.')
return call, rhs_value
def modifies_arguments(f: NativeFunction) -> bool:
return f.func.kind() in [SchemaKind.inplace, SchemaKind.out]
@with_native_function_with_differentiability_info
def emit_inplace_or_view_body(fn: NativeFunctionWithDifferentiabilityInfo) -> List[str]:
f = fn.func
inplace_view_body: List[str] = []
dispatcher_sig = DispatcherSignature.from_schema(f.func)
dispatcher_exprs = dispatcher_sig.exprs()
# code-generated ADInplaceOrView kernels plumb and
# recompute dispatch keys directly through the kernel for performance.
# See Note [Plumbing Keys Through The Dispatcher] for details.
dispatch_key_set = 'ks & c10::after_ADInplaceOrView_keyset'
redispatch_args = ', '.join([dispatch_key_set] + [a.expr for a in dispatcher_exprs])
# Note that this calls the slow, dispatching variants of manual_cpp_binding ops.
# We could probably work harder to ensure that the fast variants are called instead,
# but the perf benefit would be minimal.
if modifies_arguments(f): # inplace op
inplace_view_body.append(INPLACE_REDISPATCH.substitute(
unambiguous_name=f.func.name.unambiguous_name(),
unpacked_args=redispatch_args,
))
for r in cpp.return_names(f):
inplace_view_body.append(f'increment_version({r});')
else:
assert(get_view_info(f) is not None)
inplace_view_body.append(VIEW_REDISPATCH.substitute(
assign_return_values='auto ' + TMP_VAR + ' = ',
unambiguous_name=f.func.name.unambiguous_name(),
unpacked_args=redispatch_args,
))
call, rhs_value = emit_view_body(fn, TMP_VAR)
inplace_view_body.append(call)
assert rhs_value is not None
inplace_view_body.append(
ASSIGN_RETURN_VALUE.substitute(return_values=tie_return_values(f), rhs_value=rhs_value))
if f.func.returns:
inplace_view_body.append(f'return {get_return_value(f)};')
return inplace_view_body
@with_native_function
def gen_formals(f: NativeFunction) -> str:
return ', '.join(
# code-generated autograd kernels plumb and recompute dispatch keys directly through the kernel for performance.
# See Note [Plumbing Keys Through The Dispatcher] for details.
['c10::DispatchKeySet ks'] +
[f'{cpp.argument_type(a, binds="__placeholder__").cpp_type()} {a.name}'
for a in f.func.schema_order_arguments()]
)
@with_native_function_with_differentiability_info
def inplace_or_view_method_definition(fn: NativeFunctionWithDifferentiabilityInfo) -> Optional[str]:
f = fn.func
if get_view_info(f) is None and (not modifies_arguments(f) or is_foreach_op(str(f.func.name))):
return None
return METHOD_DEFINITION.substitute(
return_type=cpp.returns_type(f.func.returns).cpp_type(),
type_wrapper_name=type_wrapper_name(f),
formals=gen_formals(f),
type_definition_body=emit_inplace_or_view_body(fn),
)
@with_native_function_with_differentiability_info
def inplace_or_view_method_registration(fn: NativeFunctionWithDifferentiabilityInfo) -> Optional[str]:
f = fn.func
if get_view_info(f) is None and (not modifies_arguments(f) or is_foreach_op(str(f.func.name))):
return None
return WRAPPER_REGISTRATION.substitute(
unqual_operator_name_with_overload=f.func.name,
type_wrapper_name=type_wrapper_name(f),
class_type='ADInplaceOrView',
)
def use_derived(fn: NativeFunctionWithDifferentiabilityInfo) -> bool:
f = fn.func
name = cpp.name(f.func)
return name not in MANUAL_AUTOGRAD and dispatch_strategy(fn) == 'use_derived'
def gen_inplace_or_view_type_env(fn: NativeFunctionWithDifferentiabilityInfo) -> Dict[str, List[str]]:
definition = inplace_or_view_method_definition(fn)
registration = inplace_or_view_method_registration(fn)
return {
'ops_headers': ([f'#include <ATen/ops/{fn.func.root_name}_ops.h>']
if definition is not None else []),
'inplace_or_view_method_definitions': [definition] if definition is not None else [],
'inplace_or_view_wrapper_registrations': [registration] if registration is not None else [],
}
def gen_inplace_or_view_type(
out: str,
fns_with_infos: List[NativeFunctionWithDifferentiabilityInfo],
template_path: str
) -> None:
# NOTE: see Note [Sharded File] at the top of the VariableType.cpp
# template regarding sharding of the generated files.
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
fm.write_sharded(
'ADInplaceOrViewType.cpp',
[fn for fn in fns_with_infos if use_derived(fn)],
key_fn=lambda fn: fn.func.root_name,
base_env={
'generated_comment':
f'@generated from {template_path}/ADInplaceOrViewType.cpp',
},
env_callable=gen_inplace_or_view_type_env,
num_shards=1,
sharded_keys={'ops_headers', 'inplace_or_view_method_definitions',
'inplace_or_view_wrapper_registrations'}
)
+120
View File
@@ -0,0 +1,120 @@
# Copyright (c) 2023 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.
# Generates C++ functions that wrap ATen tensor factory methods to turn them into Variables.
#
# This writes one file: variable_factories.h
import re
from typing import Optional, List
import codegen.api.python as python
from codegen.api.signature import CppSignatureGroup
from codegen.api import cpp
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
from codegen.context import with_native_function
from codegen.gen import FileManager
from codegen.utils import map_maybe
from codegen.model import NativeFunction, TensorOptionsArguments, Variant
from .gen_variable_type import NPU_AUTOGRAD_FUNCTION
OPTIONAL_TYPE_PATTERN = re.compile(r"c10::optional<(.+)>")
TYPE_PATTERN = re.compile(r"(?:const\s+)?([A-Z]\w+)")
# Add 'at::' to types defined in ATen namespace, e.g. Tensor, TensorList, IntArrayRef and etc.
# TODO: maybe update the cpp argument API to take optional namespace argument?
def fully_qualified_type(argument_type: str) -> str:
def maybe_optional_type(input_type: str, is_opt: bool) -> str:
return f'c10::optional<{input_type}>' if is_opt else input_type
opt_match = OPTIONAL_TYPE_PATTERN.match(argument_type)
is_opt = opt_match is not None
if opt_match:
argument_type = argument_type[opt_match.start(1):opt_match.end(1)]
match = TYPE_PATTERN.match(argument_type)
if match is None:
return maybe_optional_type(argument_type, is_opt)
index = match.start(1)
qualified_type = f'{argument_type[:index]}at::{argument_type[index:]}'
return maybe_optional_type(qualified_type, is_opt)
def gen_variable_factories(
out: str,
native_yaml_path: str,
npu_native_yaml_path: str,
template_path: str
) -> None:
native_functions = parse_native_and_custom_yaml(native_yaml_path,
npu_native_yaml_path).native_functions
factory_functions = [fn for fn in native_functions if
(is_factory_function(fn) and fn.func.name.name.base in NPU_AUTOGRAD_FUNCTION)]
fm = FileManager(install_dir=out, template_dir=template_path, dry_run=False)
fm.write_with_template('variable_factories.h', 'variable_factories.h', lambda: {
'generated_comment': '@' + f'generated from {fm.template_dir}/variable_factories.h',
'ops_headers': [f'#include <ATen/ops/{fn.root_name}.h>' for fn in factory_functions],
'function_definitions': list(map_maybe(process_function, factory_functions)),
})
@with_native_function
def is_factory_function(f: NativeFunction) -> bool:
if Variant.function not in f.variants:
return False
name = cpp.name(f.func)
has_tensor_options = python.has_tensor_options(f)
return has_tensor_options or name.endswith("_like")
@with_native_function
def process_function(f: NativeFunction) -> Optional[str]:
name = cpp.name(f.func)
has_tensor_options = python.has_tensor_options(f)
is_factory = has_tensor_options or name.endswith("_like")
if Variant.function not in f.variants or not is_factory:
return None
sig = CppSignatureGroup.from_native_function(f, method=False).signature
formals: List[str] = []
exprs: List[str] = []
requires_grad = 'false'
for arg in sig.arguments():
qualified_type = fully_qualified_type(arg.type)
if arg.default:
formals.append(f'{qualified_type} {arg.name} = {arg.default}')
else:
formals.append(f'{qualified_type} {arg.name}')
if isinstance(arg.argument, TensorOptionsArguments):
# note: we remove the requires_grad setting from the TensorOptions because
# it is ignored anyways (and we actually have an assertion that it isn't set
# which would fail otherwise). We handle requires_grad explicitly here
# instead of passing it through to the kernel.
exprs.append(f'at::TensorOptions({arg.name}).requires_grad(c10::nullopt)')
# Manually set the requires_grad bit on the result tensor.
requires_grad = f'{arg.name}.requires_grad()'
else:
exprs.append(arg.name)
return f"""\
inline at::Tensor {name}({', '.join(formals)}) {{
at::AutoDispatchBelowADInplaceOrView guard;
return autograd::make_variable(at::{name}({', '.join(exprs)}), /*requires_grad=*/{requires_grad});
}}
"""
File diff suppressed because it is too large Load Diff
+674
View File
@@ -0,0 +1,674 @@
# 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.
# Parses derivatives.yaml into autograd functions
#
# Each autograd function is represented by `DifferentiabilityInfo` containing
# a list of `Derivative`. See `tools.codegen.api.autograd` for the data models.
from collections import defaultdict
import re
from typing import Counter, Sequence, Any, Tuple, List, Set, Dict, Match, Optional
import yaml
from codegen.api.autograd import (
Derivative, DifferentiabilityInfo,
SavedAttribute, ForwardDerivative
)
from codegen.api.types import (
Binding, NamedCType, BaseCType, VectorCType,
intArrayRefT, tensorOptionsT, typeAndSizeT, longT, boolT,
tensorGeometryT, scalarTypeT, SpecialArgName,
OptionalCType, stringT
)
from codegen.api.signature import CppSignatureGroup
from codegen.api import cpp
from codegen.gen_backend_stubs import parse_native_and_custom_yaml
from codegen.context import with_native_function
from codegen.model import FunctionSchema, NativeFunction, Variant, Type
from codegen.utils import IDENT_REGEX, split_name_params, YamlLoader
_GLOBAL_LOAD_DERIVATIVE_CACHE = {}
def load_derivatives(
derivatives_yaml_path: str,
native_yaml_path: str,
npu_native_yaml_path: str
) -> Sequence[DifferentiabilityInfo]:
# Do some caching as this is a deterministic function
global _GLOBAL_LOAD_DERIVATIVE_CACHE
key = (derivatives_yaml_path, native_yaml_path)
if key not in _GLOBAL_LOAD_DERIVATIVE_CACHE:
with open(derivatives_yaml_path, 'r') as f:
definitions = yaml.load(f, Loader=YamlLoader)
functions = parse_native_and_custom_yaml(native_yaml_path, npu_native_yaml_path).native_functions
# What's the difference between function schema v.s. signature?
# function schema is the complete declaration including mutability annotation / default value and etc.
# signature is the canonical schema for a group of functions (in-place/out/functional variants)
# that are semantically related.
functions_by_signature: Dict[FunctionSchema, List[NativeFunction]] = defaultdict(list)
functions_by_schema: Dict[str, NativeFunction] = dict()
for function in functions:
functions_by_signature[function.func.signature()].append(function)
assert str(function.func) not in functions_by_schema
functions_by_schema[str(function.func)] = function
# Keep track of how many of which ops we've seen so we can
# disambiguate them with a numeric suffix.
op_counter = Counter[str]()
infos = [
create_differentiability_info(defn, functions_by_signature, functions_by_schema, op_counter)
for defn in definitions]
_GLOBAL_LOAD_DERIVATIVE_CACHE[key] = infos
return _GLOBAL_LOAD_DERIVATIVE_CACHE[key]
@with_native_function
def cpp_arguments(f: NativeFunction) -> Sequence[Binding]:
return CppSignatureGroup.from_native_function(f, method=False).signature.arguments()
def create_derivative(f: NativeFunction, formula: str, var_names: Tuple[str, ...],
available_named_gradients: Sequence[str]) -> Derivative:
original_formula = formula
arguments: List[NamedCType] = [a.nctype.remove_const_ref() for a in cpp_arguments(f)]
return_names = tuple(n if n != 'self' else 'result' for n in cpp.return_names(f))
return_types = tuple(cpp.return_type(r).remove_const_ref() for r in f.func.returns)
named_returns = [NamedCType(name, type) for name, type in zip(return_names, return_types)]
formula, saved_inputs = saved_variables(formula, arguments, var_names)
formula, saved_outputs = saved_variables(formula, named_returns, var_names)
used_named_gradients = {name for name in available_named_gradients if re.search(IDENT_REGEX.format(name), formula)}
# Check that the referenced derivatives in the formula are in bounds
for i in used_gradient_indices(formula):
if i >= len(f.func.returns):
raise RuntimeError(
f'Out of bounds grads access: derivative formula for {cpp.name(f.func)} '
f'used grads[{i}], but the forward only returns {len(f.func.returns)} outputs.'
)
return Derivative(
formula=formula,
original_formula=original_formula,
var_names=var_names,
saved_inputs=saved_inputs,
saved_outputs=saved_outputs,
named_gradients=used_named_gradients,
)
def create_forward_derivative(f: NativeFunction, formula: str, names: Tuple[str, ...]) -> ForwardDerivative:
assert len(names) == 1, "Forward derivatives can define gradients for only one output at a time"
var_name = names[0]
var_type: Optional[Type] = None
for r in f.func.returns:
if r.name == var_name:
var_type = r.type
break
# Handle default return names
if var_type is None:
if var_name == "result":
assert len(f.func.returns) == 1
var_type = f.func.returns[0].type
else:
res = re.findall(r"^result(\d+)$", var_name)
if len(res) == 1:
arg_idx = int(res[0])
var_type = f.func.returns[arg_idx].type
assert var_type is not None, "No matching output for forward derivative definition"
return ForwardDerivative(
formula=formula,
var_name=var_name,
var_type=var_type,
required_inputs_fw_grad=None,
required_inputs_primal=None,
required_original_self_value=False,
is_reusing_outplace_formula=False)
def postprocess_forward_derivatives(
f: NativeFunction,
defn_name: str,
all_arg_names: List[str],
derivatives: List[Derivative],
forward_derivatives: List[ForwardDerivative],
args_with_derivatives: Sequence[Binding]
) -> List[ForwardDerivative]:
def find_required_inputs(formula: str, postfix: str) -> Tuple[str, ...]:
required_inputs = set()
for arg in args_with_derivatives:
if arg.type == 'at::TensorList':
# The functions taking TensorList handle everything internally
continue
arg_name = arg.name
found = re.search(IDENT_REGEX.format(arg_name), formula)
if found:
raise RuntimeError(f"The forward formula for {defn_name} is using the base name of the {arg_name} "
f"argument which is ambiguous. You should use {arg_name}_p to access the primal "
f"value and {arg_name}_t to access the tangent.")
found = re.search(IDENT_REGEX.format(arg_name + postfix), formula)
if found:
required_inputs.add(arg_name)
return tuple(required_inputs)
updated_derivatives: List[ForwardDerivative] = []
for defn in forward_derivatives:
formula = defn.formula
required_inputs_tangent = find_required_inputs(formula, "_t")
if formula == "auto_element_wise":
if (not len(args_with_derivatives) == 1) or len(forward_derivatives) > 1:
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
"forward definition of gradient as element_wise but this only "
"works for functions with a single differentiable input and a "
"single differentiable output.")
if not len(derivatives) == 1:
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
"forward definition of gradient as element_wise but it does not "
"defines the gradient formula for its argument which is required.")
# This transformation is based on the observation that for element-wise functions,
# the Jacobian matrix is diagonal and thus doing J * v
# is the same as(v^T J)^T (in practice, we ignore the transpositions)
# For the complex case, we use hermitian transpose and get (v.conj() J).conj()
# So here we are going to re-use the backward formula and replace two things:
# 1) all occurrences of "grad" with "foo_t.conj()",
# where foo is the name of the unique differentiable input.
# 2) all usage of an original input "foo" with its primal value "foo_p".
# 3) conjugate the final result
# For example, for abs, the backward formula is:
# grad * self.sgn()
# And this function generates a forward formula that is:
# (self_t.conj() * self_p.sgn()).conj()
backward_formula = derivatives[0].original_formula
input_name = args_with_derivatives[0].name
# Do replacement 1) of the grad
def repl(m: Any) -> str:
return f"{m.group(1)}{input_name}_t.conj(){m.group(2)}"
fw_formula = re.sub(IDENT_REGEX.format("grad"), repl, backward_formula)
# Do replacement 2) of the input variables
for arg in args_with_derivatives:
arg_name = arg.name
def repl(m: Any) -> str:
return f"{m.group(1)}{arg_name}_p{m.group(2)}"
fw_formula = re.sub(IDENT_REGEX.format(arg_name), repl, fw_formula)
# Do the final conjugate 3)
fw_formula = f"({fw_formula}).conj()"
# Since there is a single differentiable inputs and we necessarily need its tangent we can
# simply require all differentiable input's tangent.
required_inputs_tangent = tuple(all_arg_names)
formula = fw_formula
elif formula == "auto_linear":
if len(forward_derivatives) > 1:
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml defines the "
"forward definition of gradient as linear but this only works "
"for functions with a single differentiable output.")
# This transformation is based on the observation that linear functions can be written as:
# y = f(x) = A * x
# For some matrix A and the Jacobian of the function f is also A.
# So doing J * v = A * v = f(v).
# Hence to do the jvp, we simply need to evaluate the function at the point v instead of x.
# We do this by calling the forward again by replacing any occurrence of the differentiable
# input "foo" by it's tangent "foo_t".
# Note that multiple inputs are not a problem as long as the function is truly linear wrt to
# the vector where all the differentiable inputs are stacked.
diff_arg_names = [arg.name for arg in args_with_derivatives]
assert len(diff_arg_names) > 0
# Do replacement of input variables
new_args = []
for arg_name in all_arg_names:
if arg_name in diff_arg_names:
arg_name = arg_name + "_t"
new_args.append(arg_name)
# Call into the forward again. We need two cases here to handle both Tensor methods and at:: functions.
if Variant.function in f.variants:
fw_formula = "at::{}({})".format(defn_name, ", ".join(new_args))
else:
assert Variant.method in f.variants
fw_formula = "{}.{}({})".format(new_args[0], defn_name, ", ".join(new_args[1:]))
# All of the input tangents are always used so all of them are required here.
required_inputs_tangent = tuple(diff_arg_names)
formula = fw_formula
# At this point, the formula is final and is not modified anymore.
# During forward formula, we use the primal instead of the input Tensors.
# This call inspects the formula to find for which input's primal are used.
required_inputs_primal = find_required_inputs(formula, "_p")
updated_derivatives.append(ForwardDerivative(
formula=formula,
var_name=defn.var_name,
var_type=defn.var_type,
required_inputs_fw_grad=required_inputs_tangent,
required_inputs_primal=required_inputs_primal,
required_original_self_value=False,
is_reusing_outplace_formula=False))
return updated_derivatives
def is_forward_derivative_definition(all_arg_names: List[str], names: Tuple[str, ...]) -> bool:
if len(names) > 1:
# Forward definition are always for a single output at a time
return False
name = names[0]
if name not in all_arg_names:
return True
else:
return False
def create_differentiability_info(
defn: Dict[Any, Any],
functions_by_signature: Dict[FunctionSchema, List[NativeFunction]],
functions_by_schema: Dict[str, NativeFunction],
op_counter: Counter[str],
) -> DifferentiabilityInfo:
"""Processes a single entry `defn` in derivatives.yaml"""
def canonical_function(functions: Sequence[NativeFunction], name: str) -> NativeFunction:
for f in functions:
if cpp.name(f.func) == name:
return f
# some functions only have in-place variants
assert name + '_' == cpp.name(functions[0].func)
return functions[0]
def split_names(raw_names: str) -> Tuple[str, ...]:
"""Given "foo, bar", return ["foo", "bar"]."""
return tuple(x.strip() for x in raw_names.split(','))
def check_grad_usage(defn_name: str, derivatives: Sequence[Derivative]) -> None:
"""
Check for some subtle mistakes one might make when writing derivatives.
These mistakes will compile, but will be latent until a function is
used with double backwards.
"""
uses_grad = False # true if any derivative uses "grad"
num_grads_uses = 0 # count of uses of "grads" or "grads[INDEX]"
uses_named_grads = False # true if any derivative uses "grad_{name}"
used_grads_indices: List[int] = [] # which indices of grads are used
for d in derivatives:
formula = d.formula
uses_grad = uses_grad or bool(re.findall(IDENT_REGEX.format('grad'), formula))
num_grads_uses += len(re.findall(IDENT_REGEX.format('grads'), formula))
uses_named_grads = uses_named_grads or bool(d.named_gradients)
used_grads_indices.extend(used_gradient_indices(formula))
# This is a basic sanity check: the number of places we see
# "grads" should be no fewer than the number of indices we see
# inside "grads". They may not be equal because we may use
# "grads" without an index.
assert num_grads_uses >= len(used_grads_indices)
# Thus if the number is equal, every use of grads is also
# indexed.
only_used_grads_indices = num_grads_uses == len(used_grads_indices)
if uses_grad and num_grads_uses > 0:
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml illegally "
"mixes use of 'grad' and 'grads'. Consider replacing "
"occurrences of 'grad' with 'grads[0]'")
if only_used_grads_indices and set(used_grads_indices) == {0}:
raise RuntimeError(f"Derivative definition of {defn_name} in derivatives.yaml solely "
"refers to 'grads[0]'. If the first output is indeed the "
"only differentiable output, replace 'grads[0]' with 'grad'; "
"otherwise, there is a likely error in your derivatives "
"declaration.")
if uses_named_grads and (uses_grad or num_grads_uses > 0):
raise RuntimeError(
f'Derivative definition of {defn_name} in derivatives.yaml illegally '
'mixes use of "grad_RETURN_NAME" and "grad" or "grads[x]". Use '
'only one method for identifying gradients.')
@with_native_function
def set_up_derivatives(f: NativeFunction) -> Tuple[
Sequence[Derivative],
Sequence[ForwardDerivative],
Sequence[Binding],
Sequence[str],
Sequence[str],
]:
# Set up the derivative information
derivatives: List[Derivative] = []
forward_derivatives: List[ForwardDerivative] = []
non_differentiable_arg_names: List[str] = []
args_with_derivatives_set: Set[str] = set()
all_arg_names = [a.name for a in cpp_arguments(f)]
# output_differentiability is captured from the enclosed
# scope. Don't modify it.
#
# If it is not present, then no output is explicitly
# undifferentiable.
#
# It may be present and shorter than the length of return
# values. If that's the case, any return value that does not
# have a corresponding entry is considered not differentiable.
differentiability = output_differentiability or [True] * len(f.func.returns)
# A return is available as a named gradient ...
available_named_gradients = [
f'grad_{ret.name}' for ret, differentiable in zip(f.func.returns, differentiability)
# if it has not been explicitly made undifferentiable
if differentiable
# and if it has a name
and ret.name is not None
# and if its type is differentiable
and ret.type.is_tensor_like()]
for raw_names in sorted(defn.keys()):
formula = defn[raw_names]
names = split_names(raw_names)
if is_forward_derivative_definition(all_arg_names, names):
forward_derivatives.append(create_forward_derivative(f, formula, names))
else:
if formula.lower().strip() == 'non_differentiable':
non_differentiable_arg_names += names
else:
derivative = create_derivative(f, formula, names,
available_named_gradients)
derivatives.append(derivative)
args_with_derivatives_set |= set(names)
overlap = args_with_derivatives_set.intersection(non_differentiable_arg_names)
if overlap:
raise RuntimeError(f'derivatives definition for {defn} have overlapped non_differentiable '
f'and differentiable variables: {overlap}')
# Next, let us determine the list of inputs in order.
# TODO: do we need eagerly calculate and save it here? Can it be derived
# from NativeFunction and `derivatives` on callsites instead?
args_with_derivatives = [a for a in cpp_arguments(f) if a.name in args_with_derivatives_set]
# Postprocess forward derivatives definitions now that we know the differentiable arguments
forward_derivatives = postprocess_forward_derivatives(f, defn_name, all_arg_names, derivatives,
forward_derivatives, args_with_derivatives)
# Test to see if the use of 'grads' makes sense.
check_grad_usage(defn_name, derivatives)
return (derivatives, forward_derivatives, args_with_derivatives,
non_differentiable_arg_names, available_named_gradients)
# NB: Removes 'name' from defn dictionary
specification = defn.pop('name')
defn_name, _ = split_name_params(specification)
# NB: Removes 'output_differentiability' from defn dictionary
# `None` means all differentiable.
output_differentiability = defn.pop('output_differentiability', None)
output_differentiability_conditions = None
if output_differentiability and any([isinstance(diff, str) for diff in output_differentiability]):
if len(output_differentiability) != 1:
raise RuntimeError(f'Not supported: for {specification},'
f'output_differentiability must either be '
f'List[bool] or a List[str] where each str is a '
f'condition. In the case where it is a condition, '
f'we only support single-output functions. '
f'Please file us an issue. ')
output_differentiability_conditions = output_differentiability
output_differentiability = [True]
schema_function = functions_by_schema.get(specification)
if not schema_function:
avail = '\n'.join(k for k, v in functions_by_schema.items() if cpp.name(v.func) == defn_name)
raise RuntimeError(f'could not find ATen function for schema: {specification} '
f'. Available signatures:\n{avail}')
# now map this to the legacy schema; this isn't technically necessary, but we'd need some logic here
# to map in-place schemas to the out-of-place variants.
# TODO: maybe the logic to handle the legacy schema is no longer necessary?
signature = schema_function.func.signature()
functions = functions_by_signature[signature]
if len(functions) == 0:
avail = '\n'.join(str(k) for k, v in functions_by_signature.items() if cpp.name(k) == defn_name)
raise RuntimeError(f'could not find ATen function for legacy signature: {signature} '
f'corresponding to schema {specification}. Please report a bug to PyTorch. '
f'Available signatures:\n{avail}')
canonical = canonical_function(functions, defn_name)
if 'grad_input_mask' in (a.name for a in cpp_arguments(canonical)):
raise RuntimeError(f"Schema for {defn_name} has an argument named grad_input_mask, "
"but this name would be shadowed by our codegen. "
"Please use a different name in native_functions.yaml.")
if 'result' in (a.name for a in cpp_arguments(canonical)):
raise RuntimeError(f"Schema for {defn_name} has an argument named result, "
"but this is only allowed for outputs."
"Please use a different name in native_functions.yaml.")
(derivatives, forward_derivatives, args_with_derivatives,
non_differentiable_arg_names, available_named_gradients) = set_up_derivatives(canonical)
used_named_gradients: Set[str] = set()
for d in derivatives:
used_named_gradients |= d.named_gradients
# only assign an op name if we are actually going to calculate a derivative
op = None
if args_with_derivatives:
op_prefix = _create_op_prefix(defn_name)
op = f'{op_prefix}{op_counter[op_prefix]}'
op_counter[op_prefix] += 1
return DifferentiabilityInfo(
name=defn_name,
func=canonical,
op=op,
derivatives=derivatives,
forward_derivatives=forward_derivatives,
all_saved_inputs=dedup_vars([v for d in derivatives for v in d.saved_inputs]),
all_saved_outputs=dedup_vars([v for d in derivatives for v in d.saved_outputs]),
available_named_gradients=available_named_gradients,
used_named_gradients=used_named_gradients,
args_with_derivatives=args_with_derivatives,
non_differentiable_arg_names=non_differentiable_arg_names,
output_differentiability=output_differentiability,
output_differentiability_conditions=output_differentiability_conditions,
)
GRAD_INDEX_REGEX = r'(?:^|\W)grads\[(\d+)\]'
def used_gradient_indices(formula: str) -> List[int]:
"""Determine a list of gradient indices (the i in grads[i]) that
are used by the formula.
>>> used_gradient_indices("foo(grads[0], grads[1])")
[0, 1]
"""
return [int(i) for i in re.findall(GRAD_INDEX_REGEX, formula)]
def saved_variables(
formula: str,
nctypes: List[NamedCType],
var_names: Tuple[str, ...],
) -> Tuple[str, Tuple[SavedAttribute, ...]]:
def stride_expr(name: str) -> str:
assert var_names == (name,), (
'Replacement for ".strides()" is currently only supported for single derivatives of the same tensor '
'that ".strides()" is being called on.')
return f'strides_or_error({name}, "{name}")'
REPLACEMENTS: List[Tuple[str, Dict[str, Any]]] = [
# replace self.sizes() with self_sizes
(r'{}.sizes\(\)', {
'suffix': '_sizes',
'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)),
}),
# replace self->sizes() with self_sizes_opt
(r'{}->sizes\(\)', {
'suffix': '_sizes_opt',
'nctype': lambda name: NamedCType(name, OptionalCType(BaseCType(intArrayRefT))),
'expr': lambda name: f'{name}.has_value() ? c10::optional<IntArrayRef>({name}->sizes()) : c10::nullopt',
}),
# replace self.options() with self_options
(r'{}.options\(\)', {
'suffix': '_options',
'nctype': lambda name: NamedCType(name, BaseCType(tensorOptionsT)),
}),
# replace zeros_like(self) with self_info
(r'zeros_like\({}\)', {
'suffix': '_info',
'nctype': lambda name: NamedCType(name, BaseCType(typeAndSizeT)),
'expr': lambda name: name, # at save-time
'res': lambda name: name + '_info.zeros()', # at eval-time
}),
# replace self.size(2) with self_size_2
(r'{}.size\((\w+)\)', {
'suffix': lambda m: '_argsize_{}'.format(*m.groups()),
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
}),
# replace self.numel() with self_numel
(r'{}.numel\(\)', {
'suffix': '_numel',
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
}),
# replace to_args_sizes(self) with self_args_sizes
(r'to_args_sizes\({}\)', {
'suffix': '_args_sizes',
'nctype': lambda name: NamedCType(name, VectorCType(VectorCType(BaseCType(longT)))),
}),
# replace to_args_scalartypes(self) with self_args_scalartypes
(r'to_args_scalartypes\({}\)', {
'suffix': '_args_scalartypes',
'nctype': lambda name: NamedCType(name, VectorCType(BaseCType(scalarTypeT))),
}),
# replace TensorGeometry(self) with self_geometry
(r'TensorGeometry\({}\)', {
'suffix': '_geometry',
'nctype': lambda name: NamedCType(name, BaseCType(tensorGeometryT)),
}),
(r'{}.scalar_type\(\)', {
'suffix': '_scalar_type',
'nctype': lambda name: NamedCType(name, BaseCType(scalarTypeT)),
}),
# replace self.dim() with self_dim
(r'{}.dim\(\)', {
'suffix': '_dim',
'nctype': lambda name: NamedCType(name, BaseCType(longT)),
}),
# replace self.strides() with self_strides
(r'{}.strides\(\)', {
'suffix': '_strides',
'nctype': lambda name: NamedCType(name, BaseCType(intArrayRefT)),
'expr': stride_expr,
}),
# replace self.is_conj() with self_conjugate
(r'{}.is_conj\(\)', {
'suffix': '_conjugate',
'nctype': lambda name: NamedCType(name, BaseCType(boolT)),
})
]
# find which arguments need to be saved
saved: List[SavedAttribute] = []
for nctype in nctypes:
name = nctype.name.name if isinstance(nctype.name, SpecialArgName) else nctype.name
# First search the formula for expressions which can be evaluated
# when the autograd Function is created to avoid saving variables
for regex, info in REPLACEMENTS:
def repl(m: Match[str]) -> str:
suffix: str = info['suffix'](m) if callable(info['suffix']) else info['suffix']
expr: str = info['expr'](name) if 'expr' in info else m.group(0)
saved.append(SavedAttribute(
nctype=info['nctype'](name + suffix),
expr=expr,
))
if 'res' in info:
replacement: str = info['res'](name)
return replacement
return name + suffix
formula = re.sub(regex.format(name), repl, formula)
# c10::optional<std::string> types stored in Backward nodes must be
# converted to c10::optional<c10::string_view> before being passed into
# the backward function
if nctype.type == OptionalCType(BaseCType(stringT)):
formula = re.sub(
rf'\b{name}\b',
f'{name}.has_value() ? c10::optional<c10::string_view>({name}.value()) : c10::nullopt',
formula)
# Find any variables which remain in the formula and save them
if re.search(IDENT_REGEX.format(name), formula):
saved.append(SavedAttribute(
nctype=nctype,
expr=name,
))
return formula, tuple(saved)
def _create_op_prefix(name: str) -> str:
"""Takes a native function name converts to a op prefix name.
Note that the "name" parameter must be the native function name
without the optional variant suffix, so "add" instead of
"add.out".
OP names correspond to classes, hence the change to title case.
Example::
>>> _create_op_prefix('add')
'AddBackward'
"""
camel_case = ''.join([p.title() for p in name.split('_')])
return (camel_case + 'Backward').replace('ForwardBackward', 'Backward')
def dedup_vars(variables: Sequence[SavedAttribute]) -> Sequence[SavedAttribute]:
seen: Set[str] = set()
saved: List[SavedAttribute] = []
for var in variables:
name = var.nctype.name.name if isinstance(var.nctype.name, SpecialArgName) else var.nctype.name
if name in seen:
continue
seen.add(name)
saved.append(var)
return saved
@@ -0,0 +1,51 @@
// 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.
#define TORCH_ASSERT_ONLY_METHOD_OPERATORS
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <torch/library.h>
// ${generated_comment}
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Operators.h>
#else
$ops_headers
#endif
using namespace at;
using torch::autograd::CreationMeta;
using torch::autograd::as_view;
using torch::autograd::increment_version;
namespace at_npu {
namespace ADInplaceOrView {
namespace {
${inplace_or_view_method_definitions}
} // namespace
} // namespace ADInplaceOrView
namespace {
TORCH_LIBRARY_IMPL(aten, ADInplaceOrView, m) {
${inplace_or_view_wrapper_registrations}
}
} // namespace
} // namespace at_npu
+35
View File
@@ -0,0 +1,35 @@
// 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.
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
// ${generated_comment}
// The manual function definitions that used to be here are now in torch/csrc/autograd/FunctionsManual.cpp
// This speeds up re-compilation and allow to share these implementations so that they can be
// used for forward mode AD formulas as well.
using namespace at_npu::autograd::generated::details;
using at::Tensor;
using at::Scalar;
using at::IntArrayRef;
using at::TensorList;
namespace at_npu { namespace autograd { namespace generated {
${autograd_function_definitions}
}}} // namespace at_npu::autograd::generated
+77
View File
@@ -0,0 +1,77 @@
// 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
// ${generated_comment}
#include <ATen/ATen.h>
#include <ATen/core/functional.h>
#include <ATen/TensorGeometry.h>
#include <torch/csrc/autograd/function.h>
#include <torch/csrc/autograd/variable.h>
#include <torch/csrc/autograd/saved_variable.h>
#include <torch/csrc/Export.h>
using namespace torch::autograd;
namespace at_npu { namespace autograd { namespace generated {
using at::Scalar;
using at::Tensor;
using at::IntArrayRef;
using at::ArrayRef;
using at::Type;
using at::TensorGeometry;
using at::ScalarType;
using c10::optional;
using c10::fmap;
inline std::vector<Tensor> unpack_list(at::ArrayRef<SavedVariable> xs) {
// NB: we must explicitly do the conversion in the lambda, otherwise template
// deduction will give a Tensor of Variable which is not convertible
return fmap(xs, [](const SavedVariable& x) {
return static_cast<Tensor>(x.unpack());
});
}
inline c10::List<c10::optional<Tensor>> unpack_opt_list(at::ArrayRef<SavedVariable> xs) {
torch::List<c10::optional<Tensor>> result;
result.reserve(xs.size());
for (const SavedVariable& v : xs) {
result.push_back(v.unpack());
}
return result;
}
struct TypeAndSize {
TypeAndSize() : options(at::TensorOptions()) {}
/* implicit */
TypeAndSize(const Tensor & t)
: sizes(t.sizes().vec())
, options(t.options()) {}
Tensor zeros() { return at::zeros(sizes, options); }
private:
std::vector<int64_t> sizes;
at::TensorOptions options;
};
${autograd_function_declarations}
}}} // namespace at_npu::autograd::generated
@@ -0,0 +1,78 @@
// 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.
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <ATen/RedispatchFunctions.h>
#include <torch/library.h>
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/aten/VariableType.h"
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
// ${generated_comment}
// NOTE [Sharded File]: on this file's split-into-shards state
//
// Back in the good old days, VariableType.cpp was generated as one
// file with every function in it, and everything was great and
// simple.
//
// However, this file was also very large (over 36,000 lines), and
// compiling it was very slow, and in fact was a significant
// bottleneck for incremental rebuilds. To address this, we now
// generate the file split across multiple shards, named
// VariableType_0.cpp and so on, which can be compiled in parallel.
//
// For ease of inspection and debugging, so that it's not necessary to
// go rooting around in multiple files, we also generate all the
// functions together in VariableTypeEverything.cpp. This generated
// file is only for convenience; it's not actually used in the
// build. If the file you're looking at now is one of the shards, you
// may want to switch over to the Everything variant to make you
// grepping smoother.
using namespace at;
using namespace at_npu::autograd::generated;
using namespace at_npu::autograd::generated::details;
namespace at_npu { namespace autograd {
namespace VariableType {
namespace{
C10_UNUSED void reset_grad_accumulator(Variable & self) {
AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
if (meta != nullptr) {
meta->grad_accumulator_.reset();
}
}
}
namespace {
${type_derived_method_definitions}
}
} // namespace VariableType
namespace {
TORCH_LIBRARY_IMPL(aten, AutogradXLA, m) {
${wrapper_registrations}
}
}
}} // namespace at_npu::autograd
+74
View File
@@ -0,0 +1,74 @@
// 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
// ${generated_comment}
#include <cstdint> // for size_t
#include <functional> // for function
#include <memory> // for unique_ptr
#include <string>
#include <vector>
#include <ATen/core/Tensor.h>
#include <ATen/Context.h>
#include <c10/util/intrusive_ptr.h>
#include <torch/csrc/Export.h>
#include <torch/csrc/autograd/autograd_not_implemented_fallback.h>
namespace at {
struct Quantizer;
};
namespace at_npu { namespace autograd {
using Variable = at::Tensor;
using at::Context;
using at::Device;
using at::Dimname;
using at::DimnameList;
using at::Generator;
using at::IntArrayRef;
using at::MemoryFormat;
using at::QScheme;
using at::Scalar;
using at::ScalarType;
using at::Storage;
using at::Tensor;
using at::TensorList;
using at::TensorOptions;
using at::Quantizer;
// This is temporary typedef to enable Quantizer in aten native function API
// we'll remove them when we are actually exposing Quantizer class
// to frontend
using ConstQuantizerPtr = const c10::intrusive_ptr<Quantizer>&;
using c10::optional;
namespace VariableType {
TORCH_API std::vector<at::DeprecatedTypeProperties*> allCPUTypes();
at::Tensor & unpack(Tensor & t, const char * name, int pos);
const at::Tensor & unpack(const Tensor & t, const char * name, int pos);
at::Tensor unpack_opt(const Tensor & t, const char * name, int pos);
std::vector<at::Tensor> unpack(at::TensorList tl, const char *name, int pos);
${npu_variable_type}
};
}} // namespace at_npu::autograd
@@ -0,0 +1,76 @@
// 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.
#include <torch/csrc/autograd/VariableTypeUtils.h>
#include <ATen/RedispatchFunctions.h>
#include <torch/library.h>
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/aten/VariableType.h"
#include "torch_npu/csrc/framework/autograd/FunctionsManual.h"
// ${generated_comment}
// NOTE [Sharded File]: on this file's split-into-shards state
//
// Back in the good old days, VariableType.cpp was generated as one
// file with every function in it, and everything was great and
// simple.
//
// However, this file was also very large (over 36,000 lines), and
// compiling it was very slow, and in fact was a significant
// bottleneck for incremental rebuilds. To address this, we now
// generate the file split across multiple shards, named
// VariableType_0.cpp and so on, which can be compiled in parallel.
//
// For ease of inspection and debugging, so that it's not necessary to
// go rooting around in multiple files, we also generate all the
// functions together in VariableTypeEverything.cpp. This generated
// file is only for convenience; it's not actually used in the
// build. If the file you're looking at now is one of the shards, you
// may want to switch over to the Everything variant to make you
// grepping smoother.
using namespace at;
using namespace at_npu::autograd::generated;
using namespace at_npu::autograd::generated::details;
namespace at_npu { namespace autograd {
namespace VariableType {
namespace{
C10_UNUSED void reset_grad_accumulator(Variable & self) {
AutogradMeta* meta = torch::autograd::impl::get_autograd_meta(self);
if (meta != nullptr) {
meta->grad_accumulator_.reset();
}
}
}
${npu_method_definitions}
} // namespace VariableType
namespace {
TORCH_LIBRARY_IMPL(aten, AutogradXLA, m) {
${wrapper_registrations}
}
}
}} // namespace at_npu::autograd
@@ -0,0 +1,150 @@
// 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
// ${generated_comment}
#include <functional>
#include <initializer_list>
#include <utility>
#include <ATen/core/Tensor.h>
#include <ATen/TracerMode.h>
#include <ATen/core/grad_mode.h>
#include <c10/util/ArrayRef.h>
#include <c10/core/MemoryFormat.h>
#include <torch/csrc/api/include/torch/detail/TensorDataContainer.h>
#include <torch/csrc/autograd/variable.h>
#ifndef AT_PER_OPERATOR_HEADERS
#include <ATen/Functions.h>
#else
#include <ATen/ops/from_blob.h>
$ops_headers
#endif
using namespace torch;
namespace at_npu {
/// NOTE: Currently `torch::tensor(...)` doesn't support mixed data types
/// (i.e. `torch::tensor({{bool, 2.0}})` doesn't work). We might be able to
/// support it in the future by iterating over all sub-lists to find
/// the largest data type that can represent all of the elements, or by using
/// variadic templates.
/// NOTE: C++ `torch::tensor` with a floating-point type or an `at::ArrayRef` / `std::vector` /
/// (nested) braced-init-list of floating-point types always produces a tensor of dtype
/// `torch::get_default_dtype()`, matching Python `torch.tensor` behavior.
/// NOTE: C++ `torch::tensor` with an integer type or an `at::ArrayRef` / `std::vector` /
/// (nested) braced-init-list of integer types always produces a tensor of dtype `at::kLong`
/// (aka. int64_t), matching Python `torch.tensor` behavior.
/// NOTE: The following dtypes are not supported by `torch::tensor` currently:
/// - `unsigned int`
/// - `unsigned long int`
/// - `unsigned long long int`
/// - `long long int`
inline at::Tensor tensor(detail::TensorDataContainer tensor_data_container, const at::TensorOptions& options = {}) {
return autograd::make_variable(
// note: we remove the requires_grad setting from the TensorOptions because
// it is ignored anyways (and we actually have an assertion that it isn't set
// which would fail otherwise). We handle requires_grad explicitly here
// instead of passing it through to the kernel.
tensor_data_container.convert_to_tensor(options.requires_grad(c10::nullopt)),
options.requires_grad());
}
/// A generic deleter function.
using Deleter = std::function<void(void*)>;
using at::MemoryFormat;
/// Exposes the given `data` as a `Tensor` without taking ownership of the
/// original data. `sizes` should specify the shape of the tensor, `strides` the
/// stride in each dimension. The `deleter` function (a
/// `std::function<void(void*)>`) will be called on the `data` when the Tensor
/// data would normally be deallocated. The `TensorOptions` specify additional
/// configuration options for the returned tensor, such as what type to
/// interpret the `data` as.
inline at::Tensor from_blob(
void* data,
at::IntArrayRef sizes,
at::IntArrayRef strides,
const Deleter& deleter,
const at::TensorOptions& options = at::TensorOptions()) {
at::Tensor tensor = ([&]() {
at::AutoDispatchBelowAutograd guard;
at::tracer::impl::NoTracerDispatchMode tracer_guard;
return at::from_blob(data, sizes, strides, deleter, options.requires_grad(c10::nullopt));
})();
return autograd::make_variable(tensor, options.requires_grad());
}
/// Exposes the given `data` as a `Tensor` without taking ownership of the
/// original data. `sizes` should specify the shape of the tensor, `strides` the
/// stride in each dimension. The `TensorOptions`
/// specify additional configuration options for the returned tensor, such as
/// what type to interpret the `data` as.
inline at::Tensor from_blob(
void* data,
at::IntArrayRef sizes,
at::IntArrayRef strides,
const at::TensorOptions& options = at::TensorOptions()) {
at::Tensor tensor = ([&]() {
at::AutoDispatchBelowAutograd guard;
at::tracer::impl::NoTracerDispatchMode tracer_guard;
return at::from_blob(data, sizes, strides, options.requires_grad(c10::nullopt));
})();
return autograd::make_variable(tensor, options.requires_grad());
}
/// Exposes the given `data` as a `Tensor` without taking ownership of the
/// original data. `sizes` should specify the shape of the tensor. The `deleter`
/// (a `std::function<void(void*)>`) function will be called on the `data` when
/// the Tensor data would normally be deallocated. The `TensorOptions` specify
/// additional configuration options for the returned tensor, such as what type
/// to interpret the `data` as.
inline at::Tensor from_blob(
void* data,
at::IntArrayRef sizes,
const Deleter& deleter,
const at::TensorOptions& options = at::TensorOptions()) {
at::Tensor tensor = ([&]() {
at::AutoDispatchBelowAutograd guard;
at::tracer::impl::NoTracerDispatchMode tracer_guard;
return at::from_blob(data, sizes, deleter, options.requires_grad(c10::nullopt));
})();
return autograd::make_variable(tensor, options.requires_grad());
}
/// Exposes the given `data` as a `Tensor` without taking ownership of the
/// original data. `sizes` should specify the shape of the tensor. The
/// `TensorOptions` specify additional configuration options for the returned
/// tensor, such as what type to interpret the `data` as.
inline at::Tensor from_blob(
void* data,
at::IntArrayRef sizes,
const at::TensorOptions& options = at::TensorOptions()) {
at::Tensor tensor = ([&]() {
at::AutoDispatchBelowAutograd guard;
at::tracer::impl::NoTracerDispatchMode tracer_guard;
return at::from_blob(data, sizes, options.requires_grad(c10::nullopt));
})();
return autograd::make_variable(tensor, options.requires_grad());
}
${function_definitions}
} // namespace at_npu
+61
View File
@@ -0,0 +1,61 @@
# Copyright (c) 2023 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.
from codegen.api import cpp
from codegen.model import NativeFunction, SchemaKind
'''
Functions in this file come from gen_trace_type.py, and will be deleted once
we have gen_trace_type.py in torch_npu.
'''
# Note: we still register to dispatch key Profiler for these ops, keeping it untouched for now.
# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
MANUAL_BACKEND = set([
'options', 'data', 'set_data', 'is_leaf', 'output_nr', '_version', 'retain_grad',
'_backward', 'requires_grad_',
])
# For these ops we want to skip the codegen-ed registration to both Autograd and Tracer keys.
# You can find the manual registration in torch/csrc/autograd/VariableTypeManual.cpp
MANUAL_AUTOGRAD_AND_TRACER = set([
'resize_', 'resize_as_', 'detach', 'detach_', 'copy_', '_fw_primal', '_make_dual',
])
def type_wrapper_name(f: NativeFunction) -> str:
if f.func.name.overload_name:
return f'{cpp.name(f.func)}_{f.func.name.overload_name}'
else:
return cpp.name(f.func)
def get_return_value(f: NativeFunction) -> str:
names = cpp.return_names(f)
if len(f.func.returns) == 1:
return names[0]
if f.func.kind() == SchemaKind.out:
return f'std::forward_as_tuple({", ".join(names)})'
else:
moved = ", ".join(f'std::move({name})' for name in names)
return f'std::make_tuple({moved})'
def tie_return_values(f: NativeFunction) -> str:
if len(f.func.returns) == 1:
return f'auto {f.func.returns[0].name or "result"}'
names = cpp.return_names(f)
return f'std::tie({", ".join(names)})'
+42 -36
View File
@@ -41,43 +41,23 @@ from codegen.selective_build.selector import SelectiveBuilder
def gen_create_out_helper(backend_index: BackendIndex) -> List[str]:
if backend_index.dispatch_key == DispatchKey.Meta:
# TODO: dedupe this with below
core = """
if (strides.empty()) {
return at::empty(sizes, options.device(at::kMeta));
} else {
return at::empty_strided(sizes, strides, options.device(at::kMeta));
}
"""
else:
expanded_topts = "optTypeMetaToScalarType(options.dtype_opt()), options.layout_opt(), " \
"options.device_opt(), options.pinned_memory_opt()"
empty_init = ""
if backend_index.dispatch_key == DispatchKey.CPU:
empty_impl = "at::native::empty_cpu"
empty_strided_impl = "at::native::empty_strided_cpu"
elif backend_index.dispatch_key == DispatchKey.CUDA:
empty_init = "globalContext().lazyInitCUDA();"
empty_impl = "at::native::empty_cuda"
empty_strided_impl = "at::native::empty_strided_cuda"
elif backend_index.dispatch_key == DispatchKey.CompositeExplicitAutograd:
empty_impl = "at::empty"
empty_strided_impl = "at::empty_strided"
else:
return []
core = f"""
{empty_init}
if (strides.empty()) {{
return {empty_impl}(sizes, {expanded_topts}, options.memory_format_opt());
}} else {{
// TODO: assert options.memory_format_opt() is nullopt (debug only?)
return {empty_strided_impl}(sizes, strides, {expanded_topts});
}}
"""
if backend_index.dispatch_key != DispatchKey.CPU:
return []
empty_options = "options"
dispatch = str(backend_index.dispatch_key).lower()
empty_impl = f"at::detail::empty_{dispatch}"
empty_strided_impl = f"at::detail::empty_strided_{dispatch}"
runtime_empty_supported_check = ""
return [f"""
Tensor create_out(IntArrayRef sizes, IntArrayRef strides, const TensorOptions &options) {{
{core}
{runtime_empty_supported_check}
if (strides.empty()) {{
return {empty_impl}(sizes, {empty_options});
}} else {{
return {empty_strided_impl}(sizes, strides, {empty_options});
}}
}}
"""]
@@ -104,6 +84,7 @@ void resize_out(const Tensor &out, IntArrayRef sizes, IntArrayRef strides, const
}
"""]
def gen_check_inplace_helper(backend_index: BackendIndex) -> List[str]:
return ["""
void check_inplace(const Tensor &self, IntArrayRef sizes, const TensorOptions &options) {
@@ -157,6 +138,7 @@ class RegisterDispatchKey:
target: Union[
Literal[Target.ANONYMOUS_DEFINITION],
Literal[Target.ANONYMOUS_DEFINITION_UNSUPPORT],
Literal[Target.NAMESPACED_DEFINITION],
Literal[Target.NAMESPACED_DECLARATION],
Literal[Target.REGISTRATION]
@@ -355,6 +337,8 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
else:
impl_name = f"{self.cpp_namespace}::{self.class_method_name}::{metadata.kernel}"
op_api_impl_name = f"{self.cpp_namespace}::NPUNativeOpApiFunctions::{metadata.kernel}"
args_exprs_str = ', '.join(a.name for a in args)
device_check = ' // No device check\n'
@@ -394,6 +378,17 @@ torch_npu::profiler::NPURecordFunction guard;
if device_of is not None:
device_guard = f"const OptionalDeviceGuard device_guard(device_of({device_of}));"
if not f.op_api:
op_api_impl_name = impl_name
return_code = f"""\
if (c10_npu::NpuRunMode::IsGraphMode() || !at_npu::native::env::CheckForbidInternalFormat()) {{
return {impl_name}({args_exprs_str});
}} else {{
return {op_api_impl_name}({args_exprs_str});
}}
"""
return f"""\
namespace {{
@@ -402,7 +397,18 @@ namespace {{
{device_guard}
{record_func_def}
return {impl_name}({args_exprs_str});
{return_code}
}}
}} // anonymous namespace
"""
elif self.target is Target.ANONYMOUS_DEFINITION_UNSUPPORT:
return f"""\
namespace {{
{returns_type} {name}({args_str}) {{
TORCH_CHECK(false, "{f.func.name} is unsupported!");
}}
}} // anonymous namespace
+28 -20
View File
@@ -109,7 +109,7 @@ class RegisterDispatchKeyCPU:
# Note: We call gen_structured() if the operator is marked structured, regardless of the backend.
# gen_structured() has special logic to handle auto-generated kernels.
if g.structured:
return []
return self.gen_structured(g)
else:
return list(map_maybe(lambda f: self.gen_unstructured(f, g), g.functions()))
elif isinstance(f, NativeFunction):
@@ -524,7 +524,7 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
metadata = self.backend_index.get_kernel(self.g)
assert metadata is not None
class_name = f"structured_{metadata.kernel}_{k.name}"
parent_class = f"{self.cpp_namespace}::structured_{metadata.kernel}"
parent_class = f"at::native::structured_{metadata.kernel}"
if is_cuda_dispatch_key(self.backend_index.dispatch_key):
device_check_args = itertools.chain(
@@ -534,23 +534,26 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
sig_body.append(
RegisterDispatchKeyCPU.gen_device_check(f.device_check, list(device_check_args), sig.name()))
trans_to_cpu_code, args_name = transfer_args_of_wrapper_func_to_cpu(sig, f)
sig_body.append(trans_to_cpu_code)
if k is SchemaKind.functional:
sig_body.append(f"{class_name} op;")
elif k is SchemaKind.inplace:
sig_body.append(f"{class_name} op(self);")
sig_body.append(f"{class_name} op(self_cpu);")
elif k is SchemaKind.out:
out_args_str = ', '.join(a.name for a in f.func.arguments.out)
out_args_arr = []
for a in f.func.arguments.out:
out_args_arr.append(f"{a.name}_cpu")
for arg in out_args_arr:
if arg in args_name:
args_name.remove(arg)
out_args_str = ', '.join(out_args_arr)
sig_body.append(f"{class_name} op({out_args_str});")
# Translate the input native arguments into structured
# arguments for the meta call
meta_exprs = ', '.join(
e.expr for e in translate(
context,
structured.meta_arguments(self.g),
method=False
)
)
meta_exprs = ', '.join(args_name)
if self.g.out.precomputed:
# If this function group has precomputed elements, the meta function
@@ -616,14 +619,17 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
# I didn't do it for this version
sig_body.append(f"at::{api_name}({out_exprs});")
elif self.backend_index.dispatch_key != DispatchKey.Meta:
impl_exprs = ', '.join(
e.expr for e in translate(
context,
structured.impl_arguments(self.g),
method=False
)
)
sig_body.append(f"op.impl({impl_exprs});")
impl_arr = [e.expr for e in translate(context,
structured.impl_arguments(self.g),
method=False)]
tmp_arr = []
for x in impl_arr:
if '.' not in x and x not in args_name:
tmp_arr.append(f"{x}_cpu")
else:
tmp_arr.append(f"{x}")
sig_body.append(f"op.impl({', '.join(tmp_arr)});")
# Destructively return the final tensors
# TODO: Do this in translate instead
@@ -641,7 +647,9 @@ return {sig.name()}({', '.join(e.expr for e in translate(cpp_sig.arguments(), si
else:
refs = ', '.join(a.name for a in f.func.arguments.out)
ret_expr = f"std::forward_as_tuple({refs})"
sig_body.append(f"return {ret_expr};")
ret_code = transfer_ret_of_wrapper_func_to_xla(sig, ret_expr)
sig_body.append(f"{ret_code}")
sig_body_str = "\n".join(sig_body)
+2 -2
View File
@@ -18,14 +18,14 @@ import os
import stat
import functools
import hashlib
from typing import List, Dict, Optional, Set, Callable, Any, Union, Sequence, TypeVar, Iterable
from typing import (List, Dict, Optional, Set, Callable, Any,
Union, Sequence, TypeVar, Iterable)
from collections import defaultdict
from codegen.code_template import CodeTemplate
from codegen.model import (FunctionSchema, NativeFunction,
NativeFunctionsGroup, OperatorName,
SchemaKind, assert_never)
from codegen.utils import concat_map
T = TypeVar('T')
+128 -19
View File
@@ -91,6 +91,20 @@ ParsedYaml = namedtuple('ParsedYaml', ['native_functions', 'backend_indices'])
def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
global _GLOBAL_PARSE_NATIVE_YAML_CACHE
if path not in _GLOBAL_PARSE_NATIVE_YAML_CACHE:
# Filter the custom native yaml file, and extract the functions we defined.
from io import StringIO
f_str = StringIO()
with open(custom_path, 'r') as f:
for line in f:
if ':' not in line:
continue
f_str.write(line)
f_str.seek(0)
custom_data = yaml.safe_load(f_str)
custom_es = custom_data['custom'] + custom_data['custom_autograd']
with open(path, 'r') as f:
es = yaml.safe_load(f)
assert isinstance(es, list)
@@ -98,25 +112,16 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
bs: Dict[DispatchKey, Dict[OperatorName, BackendMetadata]] = defaultdict(dict)
for e in es:
funcs = e.get('func')
if custom_data['supported']:
for op in custom_data['supported']:
if op['func'] == funcs.split('(')[0]:
op['func'] = funcs
e.update(op)
with context(lambda: f'in {path}:\n {funcs}'):
func, m = NativeFunction.from_yaml(e)
rs.append(func)
BackendIndex.grow_index(bs, m)
# Filter the custom native yaml file, and extract the functions we defined.
from io import StringIO
f_str = StringIO()
with open(custom_path, 'r') as f:
for line in f:
if line.split(':')[0] in ['backend', 'cpp_namespace', 'tocpu',
'supported', 'autograd', 'custom', 'custom_autograd']:
continue
if ':' not in line:
continue
f_str.write(line)
f_str.seek(0)
custom_es = yaml.safe_load(f_str)
for e in custom_es:
funcs = e.get('func')
with context(lambda: f'in {custom_path}:\n {funcs}'):
@@ -139,7 +144,7 @@ def parse_native_and_custom_yaml(path: str, custom_path: str) -> ParsedYaml:
# Parses the external backend's yaml, and adds a new BackendIndex for the backend's dispatch key.
# Returns a Tuple of (true_backend, backend_key, autograd_key, cpp_namespace, updated BackendIndex mapping)
ParsedExternalYaml = namedtuple('ParsedExternalYaml', [
'true_backend', 'backend_key', 'autograd_key', 'cpp_namespace', 'backend_indices'])
'true_backend', 'backend_key', 'autograd_key', 'unsupport_key', 'cpp_namespace', 'backend_indices'])
def parse_backend_yaml(
backend_yaml_path: str,
grouped_native_functions: Sequence[Union[NativeFunction, NativeFunctionsGroup]],
@@ -156,7 +161,8 @@ def parse_backend_yaml(
yaml_values = yaml.safe_load(f)
assert isinstance(yaml_values, dict)
valid_keys = ['backend', 'cpp_namespace', 'tocpu', 'supported', 'autograd', 'custom', 'custom_autograd']
valid_keys = ['backend', 'cpp_namespace', 'tocpu', 'supported', 'autograd',
'custom', 'custom_autograd', 'unsupported']
yaml_backend = yaml_values.pop('backend', None)
true_backend = 'XLA' if yaml_backend=='NPU' else yaml_backend
@@ -184,12 +190,17 @@ def parse_backend_yaml(
supported.append(item['func'][:item['func'].index('(')])
except ValueError:
raise Exception(f'Wrong format for function: {item["func"]}')
supported = [op['func'] if isinstance(op, Dict) else op for op in supported]
custom_autograd = yaml_values.pop('custom_autograd', [])
assert isinstance(custom_autograd, list), f'expected "autograd" to be a list, but got: {custom_autograd}'
for item in custom_autograd:
supported_autograd.append(item['func'][:item['func'].index('(')])
unsupported = yaml_values.pop('unsupported', [])
assert isinstance(unsupported, list), f'expected "unsupported" to be a list, but got: {unsupported}'
assert len(yaml_values.keys()) == 0, \
f'{backend_yaml_path} contains unexpected keys: {", ".join(yaml_values.keys())}. \
Only the following keys are supported: {", ".join(valid_keys)}'
@@ -212,10 +223,19 @@ the behavior of autograd for some operators on your backend. However "Autograd{b
autograd_idx = create_backend_index(supported_autograd, autograd_key, native_functions_map)
assert autograd_key not in backend_indices
backend_indices[autograd_key] = autograd_idx
unsupported_key: Optional[DispatchKey] = None
if len(unsupported) > 0:
with context(lambda: f'"Unsupport" is not a valid DispatchKey.'):
unsupport_key = DispatchKey.parse('Unsupport')
unsupported_idx = create_backend_index(unsupported, unsupported_key, native_functions_map)
assert unsupport_key not in backend_indices
backend_indices[unsupported_key] = unsupported_idx
check_op_on_cpu_kernels(supported_tocpu, backend_indices)
check_grouped_native_functions(backend_key, autograd_key, backend_indices, grouped_native_functions)
return ParsedExternalYaml(true_backend, backend_key, autograd_key, cpp_namespace, backend_indices)
return ParsedExternalYaml(true_backend, backend_key, autograd_key, unsupported_key, cpp_namespace, backend_indices)
def check_op_on_cpu_kernels(
@@ -225,7 +245,7 @@ def check_op_on_cpu_kernels(
op_names: List[OperatorName] = list(backend_indices[DispatchKey.CPU].index.keys())
for op_name in op_names:
if op_name.name.base not in expected_to_cpu:
if str(op_name) not in expected_to_cpu:
backend_indices[DispatchKey.CPU].index.pop(op_name, None)
@@ -317,6 +337,7 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
utils.backend = true_backend
backend_key = parsed_backend_yaml.backend_key
autograd_key = parsed_backend_yaml.autograd_key
unsupport_key = parsed_backend_yaml.unsupport_key
cpp_namespace = parsed_backend_yaml.cpp_namespace
backend_indices = parsed_backend_yaml.backend_indices
@@ -337,6 +358,49 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
'generated_comment': generated_comment,
'cpp_namespace': cpp_namespace,
'class_name': class_name,
'macro': '__SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__',
'include_npu_native_functions': '',
'static_define': '''
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
''',
# Convert to a set first to remove duplicate kernel names.
# Backends are allowed to repeat kernel names; only generate the declaration once!
'dispatch_declarations': list(set(concat_map(
lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]),
grouped_native_functions
))) + list(set(concat_map(
lambda f: dest.compute_native_function_declaration(f, backend_indices[autograd_dispatch_key]),
grouped_native_functions
))) if autograd_dispatch_key else list(set(concat_map(
lambda f: dest.compute_native_function_declaration(f, backend_indices[backend_dispatch_key]),
grouped_native_functions
))),
})
fm.write_with_template(f'{backend_dispatch_key}NativeOpApiFunctions.h',
'DispatchKeyNativeFunctions.h', lambda: {
'generated_comment': generated_comment,
'cpp_namespace': cpp_namespace,
'class_name': 'NPUNativeOpApiFunctions',
'macro': '__SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS_OPAPI__',
'include_npu_native_functions': '''
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
''',
'static_define': '',
# Convert to a set first to remove duplicate kernel names.
# Backends are allowed to repeat kernel names; only generate the declaration once!
'dispatch_declarations': list(set(concat_map(
@@ -355,7 +419,12 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
if not dispatch_key:
continue
native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"'
native_func_header = """
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/core/npu/NPURunMode.h"
#include "torch_npu/csrc/framework/interface/EnvVariables.h"
#include "torch_npu/csrc/aten/NPUNativeOpApiFunctions.h"
"""
fm.write_with_template(f'Register{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
'external_backend_headers': native_func_header,
'namespaced_headers': '',
@@ -393,6 +462,46 @@ def run(to_cpu: str, source_yaml: str, output_dir: str, dry_run: bool, impl_path
grouped_native_functions
)),
})
dispatch_key = backend_dispatch_key
native_func_header = f'#include "torch_npu/csrc/aten/NPUNativeFunctions.h"'
fm.write_with_template(f'RegisterUnsupport{dispatch_key}.cpp', 'RegisterDispatchKey.cpp', lambda: {
'external_backend_headers': native_func_header,
'namespaced_headers': '',
'DispatchKey': dispatch_key.name.replace("NPU", true_backend),
'dispatch_namespace': dispatch_key.lower(),
'dispatch_helpers': dest.gen_registration_helpers(backend_indices[unsupport_key]),
'dispatch_namespaced_definitions': list(concat_map(
dest.RegisterDispatchKey(
backend_indices[unsupport_key],
Target.NAMESPACED_DEFINITION,
selector,
rocm=False,
cpp_namespace=cpp_namespace,
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
grouped_native_functions
)),
'dispatch_anonymous_definitions': list(concat_map(
dest.RegisterDispatchKey(
backend_indices[unsupport_key],
Target.ANONYMOUS_DEFINITION_UNSUPPORT,
selector,
rocm=False,
cpp_namespace=cpp_namespace,
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
grouped_native_functions
)),
'dispatch_registrations': list(concat_map(
dest.RegisterDispatchKey(
backend_indices[unsupport_key],
Target.REGISTRATION,
selector,
rocm=False,
cpp_namespace=cpp_namespace,
class_method_name=f'{backend_dispatch_key}NativeFunctions'),
grouped_native_functions
)),
})
if to_cpu.upper() in {'OFF', '0', 'NO', 'FALSE', 'F', 'N'}:
return
+10 -2
View File
@@ -47,7 +47,7 @@ from codegen.model import (BaseOperatorName, NativeFunction,
Type, Variant, BackendIndex,
BackendMetadata, DispatchKey, OperatorName)
from codegen.utils import context
from codegen.autograd.gen_variable_type import NPU_AUTOGRAD_FUNCTION
# These functions require manual Python bindings or are not exposed to Python
_SKIP_PYTHON_BINDINGS = [
@@ -86,6 +86,7 @@ SKIP_PYTHON_BINDINGS_SIGNATURES = []
DONT_RECORD_TRACE = []
def should_trace(f: NativeFunction) -> bool:
# Operations involving Storage or Type are not traceable at the moment
if any(str(arg.type) in {'Storage', 'Type', 'ConstQuantizerPtr'}
@@ -664,9 +665,14 @@ def emit_single_dispatch(
init_npu_device = f"//"
# dispatch lambda body
is_npu_autograd = str(f.func.name) in NPU_AUTOGRAD_FUNCTION
record_func_define = cpp_record_func(f, custom=custom)
dispatch_callee = cpp_dispatch_target(f, custom=custom)
dispatch_key_set = '' if not is_npu_autograd else 'auto ks_set = ' \
'c10::DispatchKeySet().add(c10::DispatchKey::AutogradXLA).add(c10::DispatchKey::XLA);'
dispatch_callee = cpp_dispatch_target(f, custom=custom, is_npu_autograd=is_npu_autograd)
dispatch_args = ', '.join(cpp_dispatch_exprs(f, python_signature=ps, faithful=custom))
if is_npu_autograd:
dispatch_args = 'ks_set, ' + dispatch_args
# from arg parser outputs to dispatch lambda arguments
parser_outputs = arg_parser_output_exprs(ps, f)
@@ -687,6 +693,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
{init_npu_device}
pybind11::gil_scoped_release no_gil;
{record_func_define}
{dispatch_key_set}
{dispatch_callee}({dispatch_args});
}};
dispatch_{name}({lambda_args}){set_requires_grad};
@@ -702,6 +709,7 @@ auto dispatch_{name} = []({lambda_formals}) -> {lambda_return} {{
{init_npu_device}
pybind11::gil_scoped_release no_gil;
{record_func_define}
{dispatch_key_set}
return {dispatch_callee}({dispatch_args});
}};
return wrap({namedtuple_typeref}dispatch_{name}({lambda_args}){set_requires_grad});
+28 -2
View File
@@ -52,6 +52,15 @@ def assert_never(x: NoReturn) -> NoReturn:
# and you're expected to populate information once during
# construction.
# Represent a source location; used for better error reporting
@dataclass(frozen=True)
class Location:
file: str
line: int
def __str__(self) -> str:
return "{}:{}".format(self.file, self.line)
# Valid values of the 'variants' field in native_functions.yaml
Variant = Enum('Variant', ('function', 'method'))
@@ -95,6 +104,7 @@ class DispatchKey(Enum):
PrivateUse3 = auto()
EndOfBackendKeys = PrivateUse3
Unsupport = auto()
ZeroTensor = auto()
Meta = auto()
BackendSelect = auto()
@@ -291,6 +301,8 @@ class NativeFunction:
# Whether or not the NativeFunction is bishengcpp kernel
bscpp_op: bool
op_api: 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.
@@ -386,6 +398,7 @@ class NativeFunction:
tag = parse_tag(e, structured)
bscpp_op = e.pop("bscpp_op", False)
op_api = e.pop("op_api", False)
from codegen.api import cpp
@@ -455,8 +468,7 @@ class NativeFunction:
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, tag=tag,
bscpp_op=bscpp_op), backend_metadata
bscpp_op=bscpp_op, op_api=op_api), backend_metadata
def validate_unstructured(self) -> None:
# TODO: probably better to accumulate these errors and report them all
@@ -505,6 +517,20 @@ class NativeFunction:
@property
def has_composite_kernel(self) -> bool:
return self.has_composite_implicit_autograd_kernel or self.has_composite_explicit_autograd_kernel
@property
def is_view_op(self) -> bool:
rets = self.func.returns
is_non_mutating_view = len(rets) > 0 and any(r.annotation is not None
and not r.annotation.is_write for r in rets)
is_inplace_view = self.tag is not None and self.tag is Tag.inplace_view
is_wildcard_view = any(inp.annotation is not None and
inp.annotation.alias_set_after != "" for inp in self.func.schema_order_arguments())
return is_non_mutating_view or is_inplace_view or is_wildcard_view
@property
def root_name(self) -> str:
return self.func.name.name.base
SchemaKind = Enum('SchemaKind', ('functional', 'inplace', 'out'))
+18 -17
View File
@@ -15,35 +15,36 @@
// limitations under the License.
#pragma once
#ifndef __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
#define __SCRIPTS_CODEGEN_TEMPLATES_DISPATCHKEYNATIVEFUNCTIONS__
#ifndef ${macro}
#define ${macro}
#include <ATen/Tensor.h>
#include <ATen/ATen.h>
#include <c10/core/Device.h>
${include_npu_native_functions}
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
${static_define}
// ${generated_comment}
namespace ${cpp_namespace} {
struct ${class_name} {
static at::Tensor argmax(const at::Tensor & self, c10::optional<int64_t> dim, bool keepdim);
static at::Tensor argmin(const at::Tensor & self, c10::optional<int64_t> dim, bool keepdim);
static at::Tensor _embedding_bag_dense_backward(
const at::Tensor& grad,
const at::Tensor& indices,
const at::Tensor& offset2bag,
const at::Tensor& bag_size,
const at::Tensor & maximum_indices,
int64_t num_weights,
bool scale_grad_by_freq,
int64_t mode,
const c10::optional<at::Tensor> & per_sample_weights,
int64_t padding_idx);
${dispatch_declarations}
};
@@ -61,6 +61,8 @@ namespace at {
// at namespace already.
namespace {
${dispatch_helpers}
${dispatch_anonymous_definitions}
TORCH_LIBRARY_IMPL(aten, ${DispatchKey}, m) {
@@ -57,6 +57,7 @@
#include "torch_npu/csrc/aten/NPUNativeFunctions.h"
#include "torch_npu/csrc/utils/LazyInit.h"
#include "torch_npu/csrc/utils/DeviceParser.h"
#include "torch_npu/csrc/aten/VariableType.h"
using at::Tensor;
using at::Device;
+52 -2
View File
@@ -13,13 +13,27 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import dis
from functools import wraps
import torch
import torch_npu
from torch_npu.utils.device_guard import torch_device_guard
def wrap_ewf_warning_func(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not wrapper.warned:
print(f"Warning: torch.empty_with_format is deprecated and will be removed in future version. "
f"Use torch_npu.empty_with_format instead.")
wrapper.warned = True
return func(*args, **kwargs)
wrapper.warned = False
return wrapper
@torch_device_guard
def _tensor(*args, **kwargs):
return torch_npu.tensor(*args, **kwargs)
@@ -45,6 +59,7 @@ def _arange(*args, **kwargs):
return torch_npu.arange(*args, **kwargs)
@wrap_ewf_warning_func
@torch_device_guard
def _empty_with_format(*args, **kwargs):
return torch_npu.empty_with_format(*args, **kwargs)
@@ -77,6 +92,40 @@ def _as_tensor(*args, **kwargs):
return torch._C._VariableFunctions.as_tensor(*args, **kwargs).to(dst_device)
def _eval_no_call(stmt, glob, loc):
"""Evaluate statement as long as it does not contain any method/function calls"""
bytecode = compile(stmt, "", mode="eval")
for insn in dis.get_instructions(bytecode):
if "CALL" in insn.opname:
raise RuntimeError(f"Type annotation should not contain calls, but '{stmt}' does")
return eval(bytecode, glob, loc)
def _parse_type_line(type_line, rcb, loc):
"""Parses a type annotation specified as a comment.
Example inputs:
# type: (Tensor, torch.Tensor) -> Tuple[Tensor]
# type: (Tensor, Tuple[Tensor, Tensor]) -> Tensor
"""
arg_ann_str, ret_ann_str = torch.jit.annotations.split_type_line(type_line)
try:
arg_ann = _eval_no_call(arg_ann_str, {}, torch.jit.annotations.EvalEnv(rcb))
except (NameError, SyntaxError) as e:
raise RuntimeError("Failed to parse the argument list of a type annotation") from e
if not isinstance(arg_ann, tuple):
arg_ann = (arg_ann,)
try:
ret_ann = _eval_no_call(ret_ann_str, {}, torch.jit.annotations.EvalEnv(rcb))
except (NameError, SyntaxError) as e:
raise RuntimeError("Failed to parse the return type of a type annotation") from e
arg_types = [torch.jit.annotations.ann_to_type(ann, loc) for ann in arg_ann]
return arg_types, torch.jit.annotations.ann_to_type(ret_ann, loc)
${device_methods_def_py_dispatch}
def add_torch_funcs():
@@ -90,5 +139,6 @@ def add_torch_funcs():
torch.jit.script = jit_script
torch.as_tensor = _as_tensor
torch.new_device = _new_device
torch.jit.annotations.parse_type_line = _parse_type_line
${device_methods_def_py}
${device_methods_def_py}
+19
View File
@@ -20,12 +20,30 @@ from enum import Enum
import contextlib
import textwrap
# Safely load fast C Yaml loader/dumper if they are available
try:
from yaml import CSafeLoader as Loader
except ImportError:
from yaml import SafeLoader as Loader # type: ignore[misc]
try:
from yaml import CSafeDumper as Dumper
except ImportError:
from yaml import SafeDumper as Dumper # type: ignore[misc]
YamlDumper = Dumper
# A custom loader for YAML that errors on duplicate keys.
# This doesn't happen by default: see https://github.com/yaml/pyyaml/issues/165
class YamlLoader(Loader):
def construct_mapping(self, node, deep=False): # type: ignore[no-untyped-def]
mapping = []
for key_node, value_node in node.value:
key = self.construct_object(key_node, deep=deep) # type: ignore[no-untyped-call]
assert key not in mapping, f"Found a duplicate key in the yaml. key={key}, line={node.start_mark.line}"
mapping.append(key)
mapping = super().construct_mapping(node, deep=deep) # type: ignore[no-untyped-call]
return mapping
# Many of these functions share logic for defining both the definition
# and declaration (for example, the function signature is the same), so
# we organize them into one function that takes a Target to say which
@@ -42,6 +60,7 @@ Target = Enum('Target', (
'REGISTRATION',
# namespace { ... }
'ANONYMOUS_DEFINITION',
'ANONYMOUS_DEFINITION_UNSUPPORT',
# namespace cpu { ... }
'NAMESPACED_DEFINITION',
'NAMESPACED_DECLARATION',

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

Before

Width:  |  Height:  |  Size: 406 B

After

Width:  |  Height:  |  Size: 406 B

Before

Width:  |  Height:  |  Size: 253 B

After

Width:  |  Height:  |  Size: 253 B

Before

Width:  |  Height:  |  Size: 580 B

After

Width:  |  Height:  |  Size: 580 B

@@ -1,4 +1,11 @@
# FrameworkPTAdapter 3.0.0 版本说明书
# FrameworkPTAdapter 5.0.RC1 版本说明书
- [FrameworkPTAdapter 5.0.RC1](#FrameworkPTAdapter-5-0-RC1md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
- [特性修改](#特性修改md)
- [已修复问题](#已修复问题md)
- [已知问题](#已知问题md)
- [兼容性](#兼容性md)
- [FrameworkPTAdapter 3.0.0](#FrameworkPTAdapter-3-0-0md)
- [用户须知](#用户须知md)
- [新增特性](#新增特性md)
@@ -49,6 +56,117 @@
- [已知问题](#已知问题-4md)
- [兼容性](#兼容性-5md)
<h2 id="FrameworkPTAdapter-5-0-RC1md">FrameworkPTAdapter 5.0.RC1</h2>
<h3 id="用户须知md">用户须知</h3>
本框架基于Facebook主导的开源PyTorch进行修改,延续原生的PyTorch特性,使用NPU进行动态图训练;以算子粒度进行模型适配,代码重用性好,支持现有的网络只修改设备类型或数据类型,即可迁移到NPU上使用。
PyTorch1.8.1版本开始采用插件化适配方式,与原生PyTorch框架实现彻底解耦,对用户安装使用及后端算子适配开发提供较好体验。
<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="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>
<p id="p17381229135615"><a name="p17381229135615"></a><a name="p17381229135615"></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>优化设备内存分配策略,修复少量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>FX</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p3634127577"><a name="p3634127577"></a><a name="p3634127577"></a>支持模型IR图构建以及基于IR图的代码生成</p>
</td>
</tr>
<tr id="row938172915567"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6466153955816"><a name="p6466153955816"></a><a name="p6466153955816"></a>优化器</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p20382294568"><a name="p20382294568"></a><a name="p20382294568"></a>支持npu_fused_adam等融合优化器</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>
<p id="p7778931115613"><a name="p7778931115613"></a><a name="p7778931115613"></a></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="p193246215619"><a name="p193246215619"></a><a name="p193246215619"></a>优化设备内存分配策略,修复少量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>FX</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1281850105718"><a name="p1281850105718"></a><a name="p1281850105718"></a>支持模型IR图构建以及基于IR图的代码生成</p>
</td>
</tr>
<tr id="row577853110564"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p546144505813"><a name="p546144505813"></a><a name="p546144505813"></a>优化器</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p47781431165614"><a name="p47781431165614"></a><a name="p47781431165614"></a>支持npu_fused_adam等融合优化器</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-0md">FrameworkPTAdapter 3.0.0</h2>
<h3 id="用户须知md">用户须知</h3>

Before

Width:  |  Height:  |  Size: 394 B

After

Width:  |  Height:  |  Size: 394 B

Before

Width:  |  Height:  |  Size: 253 B

After

Width:  |  Height:  |  Size: 253 B

@@ -1,918 +0,0 @@
# Multi-server Multi-device Training Adaptation Guide for PyTorch Models
- [Overview](#overview)
- [Training Workflow](#training-workflow)
- [Quick Start](#quick-start)
- [Overview](#overview-1)
- [Setting Up the Environment](#setting-up-the-environment)
- [Preparing a Model](#preparing-a-model)
- [Modifying the Model](#modifying-the-model)
- [Starting the Training](#starting-the-training)
- [Multi-server Multi-device Training](#multi-server-multi-device-training)
- [Common Concepts and Parameters](#common-concepts-and-parameters)
- [Multi-server Multi-device Training Process](#multi-server-multi-device-training-process)
- [Setting Up the Environment](#setting-up-the-environment-1)
- [Preparing a Model](#preparing-a-model-1)
- [Modifying the Model](#modifying-the-model-1)
- [Start the Training](#start-the-training)
- [Appendix](#appendix)
# Overview
Users can obtain PyTorch training models from Ascend ModelZoo, but the models do not support multi-server multi-device training. You need to modify the models based on the actual model code. This document describes how to quickly train a PyTorch model in Distributed Data Parallel (DDP) mode in multi-server multi-device scenario.
# Training Workflow
The process of training a PyTorch model in multi-server multi-device scenario includes environment setup, model preparation, model modification, and training startup.
1. Environment Setup
Prepare the software, hardware, and network environment for multi-server multi-device training, including setting up the development and operating environment, connecting the cluster network, setting the processor IP address, and setting the firewall.
2. Model Preparation
Prepare a PyTorch model, data loader, and optimizer for training. You can download them from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch) or prepare them by yourself.
3. Model Modification
Modify the basic model and add the code and environment variables required by DDP to enable the multi-server multi-device training.
4. Training Startup
Start model training in the multi-server multi-device scenario and view training logs.
# Quick Start
## Overview
The example presented in this document helps you quickly understand how a PyTorch model is trained in multi-server multi-device scenario. The example uses a custom model for training in two-computer eight-device scenario. The two computers are named AI Server0 and AI Server1. The eight Ascend 910 Processors on each computer are named device0 to device7.
## Setting Up the Environment
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each computer.
1. Prepare the development and operating environment on each computer.
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide*.
2. Prepare the network.
Set up the network by directly connecting switches or optical ports. For details, see the *Ascend Data Center Solution Networking Guide* at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
In this example, two computers with eight devices are used for training, so optical ports are used for network connection.
3. Configure the device IP address.
Configure the device IP address on AI Server0.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.101 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.101 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.101 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.101 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.100 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.100 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.100 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.100 netmask 255.255.255.0
```
Configure the device IP address on AI Server1.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
hccn_tool -i 1 -ip -s address 192.168.101.111 netmask 255.255.255.0
hccn_tool -i 2 -ip -s address 192.168.102.111 netmask 255.255.255.0
hccn_tool -i 3 -ip -s address 192.168.103.111 netmask 255.255.255.0
hccn_tool -i 4 -ip -s address 192.168.100.110 netmask 255.255.255.0
hccn_tool -i 5 -ip -s address 192.168.101.110 netmask 255.255.255.0
hccn_tool -i 6 -ip -s address 192.168.102.110 netmask 255.255.255.0
hccn_tool -i 7 -ip -s address 192.168.103.110 netmask 255.255.255.0
```
4. Configure the firewall.
- Command for disabling the firewall on Ubuntu:
```shell
ufw disable
```
```
- Command for disabling the firewall on Red Hat or CentOS 7:
```shell
systemctl stop firewalld
```
## Preparing a Model
This example creates a simple model for you to quickly understand multi-server multi-device training. You can also obtain the Ascend NPU-based PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
1. Prepare a DDP model.
The following is an example of main.py for multi-server multi-device training.
```python
import argparse
import os
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
### 1. Perform basic operations. ###
# Build a model.
class ToyModel(nn.Module):
def __init__(self):
super(ToyModel, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Obtain a dataset.
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
### 2. Initialize the parameters, data, model, loss function, and optimizer. ####
# Obtain local_rank and addr.
parser = argparse.ArgumentParser()
parser.add_argument("--local_rank", default=-1, type=int)
parser.add_argument("--addr", default='127.0.0.1', type=str, help='master addr')
FLAGS = parser.parse_args()
local_rank = FLAGS.local_rank
addr = FLAGS.addr
# Set the IP address and port of the master node.
os.environ['MASTER_ADDR'] = addr
os.environ['MASTER_PORT'] = '29501'
# Initialize the DDP backend.
loc = 'npu:{}'.format(local_rank)
torch.npu.set_device(loc)
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
# Prepare data after DDP initialization.
trainloader = get_dataset()
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight. The weight needs to be loaded only on the master node before the DDP model is built.
ckpt_path = None
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# Build the DDP model.
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
### 3. Train the network.
model.train()
iterator = range(100)
for epoch in iterator:
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
# 2. You only need to save the model on process 0 once to avoid repeated saving.
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
2. Ensure that the model is correct for training in the single-server multi-device scenario.
1. The Python third-party library is required if you install the model script yourself.
2. Configure NPU environment variables. For information about the **env_npu.sh** script, see the appendix.
```shell
source env_npu.sh
```
3. Execute **torch.distributed.launch** to run the following main.py command to train a model in single-server multi-device scenario.
```shell
python -m torch.distributed.launch --nproc_per_node 8 main.py
```
`--nproc_per_node` indicates the number of training cards.
After the command is run successfully, the model is trained on the eight NPUs of the device.
## Modifying the Model
The example provided in "Quick Start" is adapted to the multi-server multi-device training. You do not need to modify the script. For details about how to modify other models, see section "Multi-server Multi-device Training".
## Starting the Training
1. Upload main.py model script to any directory on AI Server0 and AI Server1.
2. Query the host IP addresses of the servers.
```shell
hostname -I
```
All IP addresses are displayed, and the first IP address is the host IP address of the current server.
For example, the host IP address of AI Server0 is **192.168.*xx*.22**, and that of AI Server1 is **192.168.*xx*.23**.
3. Use AI Server0 as the master node, and start the 2 x 8 cluster.
Startup commands for AI Server0:
```shell
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
source env_npu.sh
# Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=192.168.xx.22
#
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=0 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
Startup commands for AI Server1:
```shell
# Set environment variables. Obtain the env_npu.sh script content from the appendix.
source env_npu.sh
# Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC, and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=192.168.xx.23
python3.7 -m torch.distributed.launch --nnodes=2 --node_rank=1 --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
Parameter description:
--nnode: specifies the number of nodes used for distributed training scripts.
--node_rank: specifies the rank of the current node during multi-node distributed training.
--nproc_per_node: specifies the number of GPU-based training processes on the current node.
--master_addr: address of the master node (rank is 0). The value can be the IP address or the host name of node 0.
--master_port: specifies the port number used by the master node during distributed training.
--addr: input parameter of the main.py script, specifying the host IP address of the master node.
3. View the host logs.
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
# Multi-server Multi-device Training
## Common Concepts and Parameters
Basic concepts for PyTorch distributed training
| Basic Concept | Description |
| :-----------: | ------------------------------------------------------------ |
| AI Server | Computer with an Ascend 910 Processors. Multiple computers are identified as AI Server +serial number, for example, AI Server0 and AI Server1. |
| device | Ascend 910 Processors on the AI server. Multiple processors are represented as device 0, device 1, ..., and device 7. |
| host | AI server host. |
| master | Select one of multiple AI servers as the master node for data communication. |
| group | Process group. By default, there is only one group. Use the default value. |
| world size | Number of global parallel processes, which can be obtained by running **torch.distributed.get_world_size()**. The value is the same for different processes. |
| rank | Sequence number of the current process, which is used for communication between processes. For example, for a 2 x 8 cluster, the **world size** is 16, and the rank in each process is [0, 1, 2, ..., 15]. |
| local_rank | Sequence number of processes on each host, for example, there are processes 0-7 on each host. Generally, **local_rank** is used to set the GPU/NPU on which the current model runs. |
Parameters for executing **torch.distributed.launch** to start multi-device training
| Parameter | Description |
| ------------------ | ------------------------------------------------------------ |
| **nnodes** | Specifies the number of nodes used for distributed training scripts. |
| **node_rank** | Specifies the rank of the current node during multi-node distributed training. |
| **nproc_per_node** | Specifies the number of GPU-based training processes on the current node. You are advised to set this parameter to the number of GPUs on the current node. In this way, each process can independently control a GPU to achieve the highest efficiency. |
| **master_addr** | Address of the master node (rank is 0). The value can be the IP address or the host name of node 0. For single-node multi-process training, set this parameter to **127.0.0.1**. |
| **master_port**: | Specifies the port number used by the master node during distributed training. The port number must be different from the port numbers of other applications. |
## Multi-server Multi-device Training Process
### Setting Up the Environment
At least two computers with Ascend 910 Processors installed are required, and the NPU firmware and driver are correctly installed on each server.
1. Prepare the development and operating environment on each computer.
- Install the CANN development and operating environment. For details, see the *CANN Software Installation Guide*. Use CANN later than 5.0.3.
- Install the PyTorch that adapts to NPU. For details, see the *PyTorch Installation Guide.*
2. Prepare the network.
Cluster training is completed by multiple computers (a maximum of 128) with Ascend 910 Processors installed. The computers need to work with switches to form a fully-connected active/standby network on the data plane. The 8 x *n*-device training is supported. Two computers can be directly connected through optical ports. For details, see the *Ascend Data Center Solution Networking Guide * at https://support.huawei.com/enterprise/en/doc/EDOC1100221995/229cc0e4.
3. Configure the device IP address.
Use hccn_tool to configure the device IP address. hccn_tool is provided by CANN.
```shell
hccn_tool -i 0 -ip -s address 192.168.100.111 netmask 255.255.255.0
```
Observe the following rules when configuring the device IP address:
1. On the AI servers, devices 0/4, 1/5, 2/6, and 3/7 must be in the same network segment. But devices 0, 1, 2, and 3 must be in different network segments, and devices 4, 5, 6, and 7 must be in different network segments.
2. In the cluster scenario, the devices corresponding to each AI server must be in the same network segment. NICs 0 and 1 of AI Server0 and AI Server1 must be in the same network segment.
3. Each IP address must be unique. IP addresses in the same network segment must be distinguished by the last eight bits.
Use hccn_tool to check whether the device IP address is correct.
- Query the IP address of each device.
```shell
hccn_tool -i 0 -ip –g
```
The IP addresses are displayed:
> ipaddr:192.168.100.101
>
> netmask:255.255.255.0
- Use hccn_tool to ensure that the devices of the two hosts are correctly connected by performing the test for eight times from device0 to devcie7.
```shell
hccn_tool -i 0 -netdetect -s address xx.xx.xx.xx
hccn_tool -i 0 -net_health –g
```
**-i**: device ID.
**-s address**: ***xx.xx.xx.xx*** is the IP address of device *i* on the other host.
If `success` is returned, the connection is successful.
4. Configure the firewall.
During HCCL communication, the firewall may intercept the communication port, causing communication timeout. Therefore, you need to disable the firewall on the server for PyTorch cluster training.
- Command for disabling the firewall on Ubuntu:
```shell
ufw disable
```
- Command for disabling the firewall on Red Hat or CentOS 7:
```shell
systemctl stop firewalld
```
### Preparing a Model
There are two methods for preparing a model.
- Download a PyTorch training model from the open source community (https://gitee.com/ascend/modelzoo/tree/master/built-in/PyTorch).
The model obtained from the open source community supports single-server multi-device training. Modify the model based on the related parameters described in section "Modifying the Model".
- Manually build a PyTorch training model.
1. Prepare a PyTorch training model and data loader.
Prepare a PyTorch model:
```python
class ToyModel(nn.Module):
def __init__(self):
...
def forward(self,x):
...
```
Prepare data:
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(my_trainset,batch_size=16,)
return trainloader
trainloader=get_dataset()
```
2. Instantiate the model.
```python
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight
if ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
```
3. Prepare the loss function and optimizer.
```python
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
```
4. Train the model.
```python
### 3. Train the network.
model.train()
iterator = range(100)
for epoch in iterator:
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
torch.save(model.state_dict(), "%d.ckpt" % epoch)
```
### Modifying the Model
Modify the IP address and port of the master node, initialize the **distributed ** function, model DDP, data DDP, and optimizer, and modify the DDP model training method based on the initial model code.
1. Set the IP address and port for the master node. In the NPU distributed training, HCCL is used for communication, while in PyTorch, the HCCL communication mechanism that is detected by automatic topology is used. That is, **RANK_TABLE_FLIE** is not required, but the communication depends on the NIC on the host side. Therefore, you need to set environment variables in the code to set the communication NIC.
```python
os.environ['MASTER_ADDR'] = xxx.xxx.xxx.xxx
os.environ['MASTER_PORT'] = 'xxx'
```
**MASTER_ADDR**: Set this parameter to the IP address of the master node in the cluster. (Select any host as the master node.)
**MASTER_PORT**: Set this parameter to the idle port of the master node.
In the model code, the IP address and port number of the master node are generally presented as transferred parameters. In some open-source code, the IP address and port number may be presented as **127.0.0.1**. In this case, you need to modify them.
The preceding variables must be declared before **torch.distributed.init_process_group()** is invoked.
2. Initialize **distributed**.
In PyTorch, `dist.init_process_group(backend='hccl', world_size=world_size, rank=rank)` is used to initialize thread groups. The parameters are described as follows:
`backend`: communication protocol used for distributed training. Only hccl can be used on the NPU.
`world_size`: total number of devices used for training.
`rank`: rank ID of the currently initialized device, that is, the global logical ID.
There are two methods to start multi-device training:
- **torch.distributed.launch**:
```python
import torch.distributed as dist
dist.init_process_group(backend='hccl') # HCCL is the backend of the NPU device.
```
- **mp.spawn**:
```python
import torch.distributed as dist
def main_worker(pid_idx, device_nums_per_node, args):
args.distributed_rank = args.rank * device_nums_per_node + pid_idx
dist.init_process_group(backend=args.dist_backend, world_size=args.distributed_world_size, rank=args.distributed_rank)
```
In the preceding commands:
`pid_idx`: device ID.
`device_nums_per_node`: number of devices on each AI server.
3. Initialize the model DDP.
```python
# Instantiate the model.
model = ToyModel().to(loc)
# Load the model weight. It needs to be loaded only on the master node before the DDP model is built.
if dist.get_rank() == 0 and ckpt_path is not None:
model.load_state_dict(torch.load(ckpt_path))
# Build the DDP model.
model = DDP(model, device_ids=[local_rank], output_device=local_rank)
```
4. Initialize the data DDP.
```python
def get_dataset():
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
my_trainset = torchvision.datasets.CIFAR10(root='./data', train=True,
download=True, transform=transform)
train_sampler = torch.utils.data.distributed.DistributedSampler(my_trainset)
trainloader = torch.utils.data.DataLoader(my_trainset,
batch_size=16, num_workers=2, sampler=train_sampler)
return trainloader
trainloader = get_dataset()
```
5. Initialize the loss function and optimizer.
```python
# Initialize the optimizer. After the DDP model is built, use the model to initialize the optimizer.
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
# Initialize the loss function.
loss_func = nn.CrossEntropyLoss().to(loc)
```
6. Train the DDP model.
```python
model.train()
iterator = range(100)
for epoch in iterator:
# Set epoch.
trainloader.sampler.set_epoch(epoch)
for data, label in trainloader:
data, label = data.to(local_rank), label.to(local_rank)
optimizer.zero_grad()
prediction = model(data)
loss = loss_func(prediction, label)
loss.backward()
print("loss = %0.3f \n" % loss)
optimizer.step()
# 1. Similar to the DP mode, when you save a model, note that model.module instead of model is saved.
# That is because the model actually refers to a DDP model, and the parameters are packaged by `model=DDP(model)`.
# 2. You only need to save the model on process 0 once to avoid repeated saving.
if dist.get_rank() == 0:
torch.save(model.module.state_dict(), "%d.ckpt" % epoch)
```
### Start the Training
The training can be started manually or using the shell script.
- Start the training manually using **torch.distributed.launch**.
1. Configure NPU environment variables. For details, see the **env_npu.sh** script in the appendix.
2. Add environment variables. For multi-server training, add the `HCCL_WHITELIST_DISABLE` and `HCCL_IF_IP` environment variables.
- **HCCL_WHITELIST_DISABLE**: HCCL channel trustlist. The value **1** indicates that the trustlist is disabled.
- **HCCL_IF_IP**: initialized IP address of the HCCL communication NIC. Set it to the IP address of the host NIC IP of the current server.
3. Upload the modified model script to each AI server.
4. Install the required Python library on each AI server.
5. Select an AI server as the master node and query the IP address of each AI server.
6. Run the following commands on each AI server:
```
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr 192.168.xx.22 --master_port 29501 main.py --addr 192.168.xx.22
```
In the preceding commands:
**--nnodes**: number of AI servers used for distributed training scripts.
**--node_rank**: AI server ID.
**--nproc_per_node**: number of devices of each AI server.
**--master_addr**: IP address of the AI server that functions as the master node.
**--master_port**: port number of the AI server that functions as the master node.
**main.py**: Change it to the name of the startup script.
**--addr**: indicates the IP address of the master node, which is a parameter transferred to the startup script.
- Start the training using Open MPI.
1. Install the PI open-source library.
In the multi-server multi-device scenario, distributed training deployment depends on the Open MPI open-source library, which must be installed on each server that participates in model training. Currently, Open MPI 4.0.1, 4.0.2, or 4.0.3 is required.
Run the **mpirun --version** command to check whether Open MPI has been installed. If `mpirun (Open MPI) 4.0.2 Report bugs to http://www.open-mpi.org/community/help/` is returned, Open MPI has been installed. If it has been installed and its version is 4.0.1, 4.0.2, or 4.0.3, you do not need to install it again.
Otherwise, perform the following steps to install it
1. Visit the following link to download the Open MPI software package, for example, openmpi-4.0.2.tar.bz2.
https://www.open-mpi.org/software/ompi/v4.0/
2. Log in to the installation environment as the root user.
3. Upload the downloaded Open MPI software package to a directory in the installation environment.
4. Go to the directory and run the following command to decompress the software package:
```shell
tar -jxvf openmpi-4.0.2.tar.bz2
```
5. Go to the directory generated after the decompression, and run the following commands to configure, compile, and install Open MPI:
```shell
./configure --prefix=/usr/local/mpirun4.0.2
make
make install
```
The **--prefix** parameter specifies the Open MPI installation path. Change it based on the site requirements.
6. Run the **vi ~/.bashrc** command to open the **.bashrc** file, and add the following environment variables to the end of the file:
```shell
export OPENMPI=/usr/local/mpirun4.0.2
export LD_LIBRARY_PATH=$OPENMPI/lib
export PATH=$OPENMPI/bin:$PATH
```
In the environment variables, **/usr/local/mpirun4.0.2** indicates the Open MPI installation path. Change it based on the site requirements.
Run the **:wq!** command to save the file and exit.
7. Make the configuration take effect.
```
source ~/.bashrc
```
8. After the installation is complete, run the following command to check the installation version. If the required version information is displayed, the installation is successful.
```
mpirun --version
```
2. Configure SSH password-free login for the AI servers.
If Open MPI is used for distributed training deployment in the multi-server multi-device scenario, you need to configure SSH password-free login between every two servers to ensure that the servers can communicate with each other. The procedure is as follows:
1. Log in to each server as the root user.
2. Configure the reliability among hosts in the cluster.
Open the **/etc/ssh/ssh_config** file and add the following fields to the end of the file:
```
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
```
3. Open the **/etc/hosts** file on each server and add the corresponding IP address and host name of the server to the first line of the file. If the file already contains the IP address and host name, skip this step. The following is an example of the content to be added:
```
xxx.xxx.xxx.111 ubuntu
```
In the preceding content, **xxx.xxx.xxx.111** is the IP address of the server, and **ubuntu** is the host name.
4. Run the following commands on the first server to generate a public key (Assume that the IP address of the first server is **xxx.xxx.xxx.111**.):
```
cd ~/.ssh/ # If the directory does not exist, run the ssh localhost command first.
ssh-keygen -t rsa # After the key is generated, a message is displayed. Press Enter for three consecutive times.
mv id_rsa.pub authorized_keys # Renames the generated key id_rsa.pub to authorized_keys.
```
5. Generate a key on each of the other servers, and copy the keys to the **authorized_keys** file on the first server.
1. Run the following commands on each of the other servers to generate a key:
cd ~/.ssh/
ssh-keygen -t rsa
2. Download the key file **id_rsa.pub** generated on each server to the local host and copy the key in the file.
3. On the first server, run the following command to open the authorized_keys file and copy the keys of each of other servers to the end of the public key of the first server.
```
vi ~/.ssh/authorized_keys
```
Run the **:wq!** command to save the file.
6. Run the following commands on each of the other servers to copy the public key of the first server to each of the other servers:
cd ~/.ssh/
scp root@xxx.xxx.xxx.111:~/.ssh/authorized_keys ./
7. Run the following command on each server to test password-free login:
```
ssh User name@IP address
```
For example, run the **ssh root@xxx.xxx.xxx.222** command to log in to the server whose IP address is xxx.xxx.xxx.222 from the first server whose IP address is xxx.xxx.xxx.111 without a password.
If information similar to the following is displayed, the login without a password is successful.
```
Linux ubuntu 4.19.28 #1 SMP Tue Jun 23 19:05:23 EDT 2020 x86_64
The programs included with the ubuntu GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
ubuntu GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Tue Sep 15 14:37:21 2020 from 10.254.88.75
```
You can run the **exit** command to log out of the server. If information similar to the following is displayed, the logout is successful.
```
logout
Connection to xxx.xxx.xxx.222 closed.
```
3. Use Open MPI to start model training.
1. Compile a startup script for each AI server, for example, train.sh, and move the startup script to the same path of the corresponding AI server.
```
# Configure NPU environment variables. For information about the env_npu.sh script, see the appendix.
source env_npu.sh
#Disable the trustlist of HCCL channel.
export HCCL_WHITELIST_DISABLE=1
# Initialize the IP address of the HCCL communication NIC , and set the IP address to the host IP address of the current server.
export HCCL_IF_IP=xxx.xxx.xx.xxx
python3 -m torch.distributed.launch --nnodes=${nnodes} --node_rank=i --nproc_per_node 8 --master_addr xxx.xxx.xx.xxx --master_port 29501 main.py --addr xxx.xxx.xx.xxx
```
For details about the script parameters, see section "Start the training manually using **torch.distributed.launch**".
2. Compile the startup script.
```
# Configuring the mpirun environment variables.
export PATH=$PATH:/usr/local/mpirun4.0.2/bin
# Run the mpirun tool.
mpirun -H xxx.xxx.xxx.xxx:1,xxx.xxx.xxx.xxx:1 \
--bind-to none -map-by slot \
--mca btl_tcp_if_exclude lo,docker0,endvnic\
--allow-run-as-root \
--prefix /usr/local/mpirun4.0.2/ \
./train.sh
```
In the preceding command:
**-H**: IP address of each AI server and the number of started processes.
**--bind-to**: process-binding policy.
**--mca**: MCA parameter in a specific context. **arg0** is the parameter name, and **arg1** is the parameter value.
**--allow-run-as-root**: The root user is allowed to run this script.
**--prefix**: path of mpirun4.0.2.
**./train.sh**: path of the startup script of each AI server.
4. View the log information after the training succeeds.
Host logs are stored in the `~/ascend/log` directory. You can go to this directory to view the device logs of each host.
# Appendix
The following shows the NPU environment variable configuration script **env_npu.sh**, which can be used to configure the operating and development environment variables.
```shell
#!/bin/bash
export install_path=/usr/local/Ascend
if [ -d ${install_path}/toolkit ]; then
export LD_LIBRARY_PATH=/usr/include/hdf5/lib/:/usr/local/:/usr/local/lib/:/usr/lib/:${install_path}/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons:${path_lib}:${LD_LIBRARY_PATH}
export PATH=${install_path}/fwkacllib/ccec_compiler/bin:${install_path}/fwkacllib/bin:$PATH
export PYTHONPATH=${install_path}/fwkacllib/python/site-packages:${install_path}/tfplugin/python/site-packages:${install_path}/toolkit/python/site-packages:$PYTHONPATH
export PYTHONPATH=/usr/local/python3.7.5/lib/python3.7/site-packages:$PYTHONPATH
export ASCEND_OPP_PATH=${install_path}/opp
else
if [ -d ${install_path}/nnae/latest ];then
export LD_LIBRARY_PATH=/usr/local/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:/usr/local/lib/:/usr/lib64/:/usr/lib/:${install_path}/nnae/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64_64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/nnae/latest/fwkacllib/ccec_compiler/bin/:${install_path}/nnae/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/nnae/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/nnae/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=${install_path}/nnae/latest/fwkacllib/python/site-packages/:${install_path}/nnae/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/nnae/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/nnae/latest
else
export LD_LIBRARY_PATH=/usr/local/:/usr/local/lib/:/usr/lib64/:/usr/lib/:/usr/local/python3.7.5/lib/:/usr/local/openblas/lib:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/:${install_path}/driver/lib64/common/:${install_path}/driver/lib64/driver/:${install_path}/add-ons/:/usr/lib/aarch64-linux-gnu:$LD_LIBRARY_PATH
export PATH=$PATH:${install_path}/ascend-toolkit/latest/fwkacllib/ccec_compiler/bin/:${install_path}/ascend-toolkit/latest/toolkit/tools/ide_daemon/bin/
export ASCEND_OPP_PATH=${install_path}/ascend-toolkit/latest/opp/
export OPTION_EXEC_EXTERN_PLUGIN_PATH=${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libfe.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libaicpu_engine.so:${install_path}/ascend-toolkit/latest/fwkacllib/lib64/plugin/opskernel/libge_local_engine.so
export PYTHONPATH=${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/auto_tune.egg/auto_tune:${install_path}/ascend-toolkit/latest/fwkacllib/python/site-packages/schedule_search.egg:$PYTHONPATH
export ASCEND_AICPU_PATH=${install_path}/ascend-toolkit/latest
fi
fi
#Output host logs to the serial port. 0: disable; 1: enable.
export ASCEND_SLOG_PRINT_TO_STDOUT=0
#Set the default log level. 0: debug; 1: info; 2: warning; 3: error.
export ASCEND_GLOBAL_LOG_LEVEL=3
#Enable or disable the event log. 0: disable; 1: enable.
export ASCEND_GLOBAL_EVENT_ENABLE=0
#Enable or disable taskque. 0: disable; 1: enable.
export TASK_QUEUE_ENABLE=1
#Enable or disable the HCCL trustlist. 1: disable; 0: enable.
export HCCL_WHITELIST_DISABLE=1
#Set the device-side log to error.
${install_path}/driver/tools/msnpureport -g error -d 0
${install_path}/driver/tools/msnpureport -g error -d 1
${install_path}/driver/tools/msnpureport -g error -d 2
${install_path}/driver/tools/msnpureport -g error -d 3
${install_path}/driver/tools/msnpureport -g error -d 4
${install_path}/driver/tools/msnpureport -g error -d 5
${install_path}/driver/tools/msnpureport -g error -d 6
${install_path}/driver/tools/msnpureport -g error -d 7
#Disable the event log on the device side.
${install_path}/driver/tools/msnpureport -e disable
path_lib=$(python3.7 -c """
import sys
import re
result=''
for index in range(len(sys.path)):
match_sit = re.search('-packages', sys.path[index])
if match_sit is not None:
match_lib = re.search('lib', sys.path[index])
if match_lib is not None:
end=match_lib.span()[1]
result += sys.path[index][0:end] + ':'
result+=sys.path[index] + '/torch/lib:'
print(result)"""
)
echo ${path_lib}
export LD_LIBRARY_PATH=/usr/local/python3.7.5/lib/:${path_lib}:$LD_LIBRARY_PATH
```
File diff suppressed because it is too large Load Diff
@@ -1,475 +0,0 @@
# PyTorch Installation Guide
- [Overview](#overviewa-nameoverviewa)
- [System Dependencies](#system-dependenciesa-namesystem-dependenciesa)
- [Ascend Auxiliary Software](#ascend-auxiliary-softwarea-nameascend-auxiliary-softwarea)
- [Installation Methods](#installation-methodsa-nameinstallation-methodsa)
- [Running](#runninga-namerunninga)
- [(Optional) Installing the Mixed Precision Module](#optional-installing-the-mixed-precision-modulea-nameoptional-installing-the-mixed-precision-modulea)
- [FAQs](#faqsa-namefaqsa)
- [Version Descriptio](#version-descriptiona-nameversion-descriptiona)
# Overview<a name="Overview"></a>
This project develops the PyTorch Adapter plugin to adapt Ascend to the PyTorch framework so that developers who use the PyTorch framework can obtain powerful compute capabilities of Ascend AI Processors. When setting up the environments for PyTorch model development and operating, developers can manually compile related modules on servers.
## Prerequisites
- The development or operating environment of CANN has been installed. For details, see the *CANN Software Installation Guide*.
- Python 3.7.5, 3.8, and 3.9 are supported.
# System Dependencies<a name="System-Dependencies"></a>
## CentOS & EulerOS
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
## 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
>![](public_sys-resources/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.
# Ascend Auxiliary Software<a name="Ascend-Auxiliary-Software"></a>
| AscendPyTorch Version| CANN Version| Supported PyTorch Version| Gitee Branch|
| :------------ | :----------- | :----------- | ------------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0.post2 | 2.0.2.tr5 |
| 2.0.3 | CANN 5.0.3 | 1.5.0.post3 | 2.0.3.tr5 |
| 2.0.4 | CANN 5.0.4 | 1.5.0.post4 | 2.0.4.tr5 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| 3.0.rc1 | CANN 5.1.RC1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| 3.0.rc2 | CANN 5.1.RC2 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
# Installation Methods<a name="Installation-Methods"></a>
## Install the PyTorch environment dependencies.
If you install dependencies as a non-root user, add **--user** at the end of each command in this step, for example, **pip3 install pyyaml --user**.
```sh
pip3 install pyyaml
pip3 install wheel
```
## Compile and install the PyTorch and Ascend plugin.
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.
#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.
```
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
cd pytorch
# Specify the Python version packaging mode:
bash ci/build.sh --python=3.7
# or
bash ci/build.sh --python=3.8
#or
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
```
Download TorchVision.
```
pip3 install torchvision==0.9.1
```
# Running<a name="Running"></a>
## Execute environment variables.
Run the script for setting environment variables in the root directory of the current repository.
```
source env.sh
```
## Customize environment variables.
The following are optional environment variables that may affect running models:
```
export COMBINED_ENABLE=1 # (Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
```
**Table 1** Description of environment variables
<a name="zh-cn_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="zh-cn_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="zh-cn_topic_0000001152616261_p51981251161315"><a name="zh-cn_topic_0000001152616261_p51981251161315"></a><a name="zh-cn_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="zh-cn_topic_0000001152616261_p9198135114133"><a name="zh-cn_topic_0000001152616261_p9198135114133"></a><a name="zh-cn_topic_0000001152616261_p9198135114133"></a>Description</p>
</td>
</tr>
<tr id="row78312162301"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1832171673019"><a name="p1832171673019"></a><a name="p1832171673019"></a>COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p583261643014"><a name="p583261643014"></a><a name="p583261643014"></a>(Optional) Discontinuous-to-continuous level-2 derivation optimization. To enable this function, set the value to 1. When a large number of time-consuming AsStrided operators are called in the model, you can enable this function to improve the device execution efficiency. However, the host delivery performance may deteriorate.</p>
</td>
</tr>
<tr id="row183041355123411"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p730435533415"><a name="p730435533415"></a><a name="p730435533415"></a>ACL_DUMP_DATA</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p16304105533412"><a name="p16304105533412"></a><a name="p16304105533412"></a>(Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.</p>
</td>
</tr>
</tbody>
</table>
## Run the unit test script.
Verify the running. The output is **OK**.
```shell
cd test/test_network_ops/
python3 test_div.py
```
# (Optional) Installing the Mixed Precision Module<a name="(Optional) Installing the Mixed Precision Module"></a>
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.
- AMP
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
- Tensor fusion is not supported.
- Apex
- O1 configuration mode: Conv and Matmul use the float16 precision for computing, and Softmax and BN use float32.
- O2 configuration mode: BN uses the float32 precision for computing, and others use float16.
- Static loss scale: Parameters are statically set to ensure the convergence of training with mixed precision.
- Dynamic loss scale: The loss scale value is dynamically calculated to determine whether overflow occurs.
# FAQs<a name="FAQs"></a>
## 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.
Download the PyTorch 1.8.1 source package.
```
git clone -b v1.8.1 https://github.com/pytorch/pytorch.git --depth=1 pytorch_v1.8.1
```
Access the source package to obtain the passive dependency code.
```
cd pytorch_v1.8.1
git submodule sync
git submodule update --init --recursive
```
Compile and install PyTorch 1.8.1.
```
python3 setup.py install
```
## When PIP is set to the Huawei source, a Python environment error occurs after the typing dependency in the **requirements.txt** file is installed.
When PIP is set to the Huawei source, open the **requirements.txt** file, delete the typing dependency, and then run the following command:
```
pip3 install -r requirments.txt
```
## The error message "no module named yaml/typing_extensions." is displayed when **bash build.sh** is run during compilation.
PyTorch compilation depends on the YAML and typing_extensions libraries, which need to be manually installed.
```
pip3 install pyyaml
pip3 install typing_extensions
```
After the installation is successful, run **make clean** and then **bash build.sh** to perform compilation. Otherwise, an unknown compilation error may occur due to the cache.
## TE cannot be found during running.
Development state:
```
cd /urs/local/Ascend/ascend-toolkit/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
User state:
```
cd /urs/local/Ascend/nnae/latest/{arch}-linux/lib64 # {arch} is the architecture name.
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
```
## During CMake installation through the CLI, an error is reported indicating that the package cannot be found. During CMake compilation, another error is reported indicating that the version is too early. In this cause, you can use the installation script or source code to compile and install CMake.
Method 1: Download the installation script and install CMake. (For details, see the CMake official website.)
​ x86_64 environment: cmake-3.12.0-Linux-x86_64.sh
​ AArch64 environment: cmake-3.12.0-Linux-aarch64.sh
1. Run the following command:
```
./cmake-3.12.0-Linux-{arch}.sh # {arch} indicates the architecture name.
```
2. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
3. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
Method 2: Use the source code to compile and install.
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.12/cmake-3.12.0.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.12.0.tar.gz
cd cmake-3.12.0/
```
3. Run the configuration, compilation, and installation commands.
```
./configure --prefix=/usr/local/cmake
make && make install
```
4. Set the soft link.
```
ln -s /usr/local/cmake/bin/cmake /usr/bin/cmake
```
5. Run the following command to check whether CMake has been installed:
```
cmake --version
```
If the message "cmake version 3.12.0" is displayed, the installation is successful.
## During GCC installation through the CLI, an error is reported indicating that the package cannot be found. During GCC compilation, another error is reported.
When downloading GCC from some sources, you may be prompted by an error message indicating that the package cannot be found. In this case, use the source code to compile and install GCC.
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).
2. GCC installation requires adequate temporary space. Run the following command to clear the **/tmp** directory in advance:
```
sudo rm -rf /tmp/*
```
3. Install the dependency package. (CentOS and Ubuntu are used as examples.)
- For CentOS, run the following command:
```
yum install bzip2
```
- For Ubuntu, run the following command:
```
apt-get install bzip2
```
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:
```
tar -zxvf gcc-7.3.0.tar.gz
```
2. Go to the extracted directory and download the GCC dependency packages:
```
cd gcc-7.3.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:
```
wget http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2
wget http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz
wget http://gcc.gnu.org/pub/gcc/infrastructure/isl-0.16.1.tar.bz2
```
After the preceding dependencies are downloaded, run the following command again:
```
./contrib/download_prerequisites
```
If the verification fails, check whether there are duplicate dependency packages in the folder. If yes, delete duplicate ones.
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
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
```
>![](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**.
4. Change the soft links.
```
ln -s ${install_path}/bin/gcc /usr/bin/gcc
ln -s ${install_path}/bin/g++ /usr/bin/g++
ln -s ${install_path}/bin/c++ /usr/bin/c++
```
5. Configure environment variables.
Training must be performed in the compilation environment with GCC upgraded. If you want to run training, configure the following environment variable in your training script:
```
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/linux_gcc7.3.0/**.
>![](public_sys-resources/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)
## libblas.so cannot be found.
The OpenBLAS library is missing in the environment. You need to install it.
CentOS and EulerOS
```sh
yum -y install openblas
```
Ubuntu
```sh
apt install libopenblas-dev
```
## No device is mounted to the container.
An NPU-related error is reported when a script is run in the container. The **device** parameter is not set before container instance startup. As a result, the instance cannot be started.
![](figures/FAQ.png)
Run the following command to restart the container:
```sh
docker run -it --ipc=host \
--device=/dev/davinciX \
--device=/dev/davinci_manager \
--device=/dev/devmm_svm \
--device=/dev/hisi_hdc \
-v /usr/local/Ascend/driver \
-v /usr/local/dcmi \
-v /usr/local/bin/npu-smi \
${image name}:{tag} \
/bin/bash
```
Parameter description:
**/dev/davinci*X***: NPU device. *X* is the physical ID of the chip, for example, **davinci0**.
**/dev/davinci_manager**: management device
**/dev/devmm_svm**: management device
**/dev/hisi_hdc**: management device
**/usr/local/Ascend/driver**: driver directory
**/usr/local/dcmi**: DCMI directory
**/usr/local/bin/npu-smi**: npu-smi tool
**$*{image name}:{tag}***: image name and version
## An error is displayed during installation of -torch--whl-, indicating that -torch-1-5-0xxxx- and -torchvision- versions do not match.
During installation of **torch-\*.whl**, the message "ERROR: torchvision 0.6.0 has requirement torch==1.5.0, but you'll have torch 1.5.0a0+1977093 which is incompatible" is displayed.
![](https://gitee.com/ascend/pytorch/raw/v1.8.1-3.0.rc2/figures/zh-cn_image_0000001190081735.png)
When the PyTorch is installed, the version check is automatically triggered. The version of the torchvision installed in the environment is 0.6.0. During the check, it is found that the version of the **torch-\*.whl** is inconsistent with the required version 1.5.0. As a result, an error message is displayed, but the installation is successful.
This problem does not affect the actual result, and no action is required.
## When you run **import torch_npu**, if "_has_compatible_shallow_copy_type" is output, a warning about a repeated registration error is displayed.
The warning is triggered by the shallow copy operation of **Tensor.set_data**, as shown in the following figure. The main cause is that after the PyTorch plugin is decoupled, `_has_compatible_shallow_copy_type` cannot detect shallow copy of NPU tensors. You need to register `_has_compatible_shallow_copy_type` again.
This error can be ignored because it does not affect the model accuracy and performance.
It will be resolved after the NPU's device ID is incorporated into the community or the `_has_compatible_shallow_copy_type` registration mode is changed in a later PyTorch version.
![Input Image Description](https://images.gitee.com/uploads/images/2022/0701/153621_2b5080c4_7902902.png)
## An error is reported when torch_npu is referenced with Python commands in the compilation directory.
To verify the torch_npu reference, switch to another directory. If you perform the verification in the compilation directory, the following error message is displayed:
<img src="figures/FAQ torch_npu.png" style="zoom:150%;" />
# Version Description<a name='Version Description'></a>
For details, see [Release Notes](https://gitee.com/ascend/pytorch/tree/master/docs/en/RELEASENOTE).
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 356 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 946 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 946 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 356 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 607 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 140 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.2 KiB

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