Compare commits

..
196 Commits
Author SHA1 Message Date
i-robot 97768cc4f1 !1038 网络模型移植与训练指南修改
Merge pull request !1038 from 彭子荣/2.0.3.tr5
2022-07-11 12:15:32 +00:00
pengzirong 7ccc615c8f 网络移植与训练指南新增硬件支持说明 2022-07-11 14:53:13 +08:00
weili10 8416c82f71 !907 安装指南资料修改
Merge pull request !907 from 彭子荣/2.0.3.tr5
2022-06-15 07:19:17 +00:00
pengzirong 7f9180b9cb 修改下载昇腾适配的apex源码命令 2022-06-14 17:21:58 +08:00
weili10 ef44e346f4 !843 README更新
Merge pull request !843 from 彭子荣/2.0.3.tr5
2022-05-25 02:47:11 +00:00
pengzirong fc90b887b9 readme更新 2022-05-24 18:33:48 +08:00
i-robot f3d1b422fe !482 Pytorch 安装指南 资料更新
Merge pull request !482 from 彭子荣/2.0.3.tr5
2022-03-23 07:39:56 +00:00
pengzirong 20a46fd2bf update 2022-03-22 09:58:50 +08:00
pengzirong eaac1a63ad 新增 版本配套描述列表 2022-03-21 10:58:00 +08:00
AtlasAccount 84dec6d4e7 同步1.5.0 c4d906fd48455a4e673afac21f7992aaac51c9ec
!2816 修复conv3d梯度分布式计算错误问题
    Merge pull request !2816 from lijing/2.0.3.tr5
--
    !2815 修复lstm算子bug
    Merge pull request !2815 from shibo/2.0.3.tr5
--
    !2809 【Requirement】模型issue需求,2.0.3tr5同步Silu适配
    Merge pull request !2809 from wuxiankun/203tr5silu
同步1.8.1 438c8daf58550d882e8b4763910cc93b927d89f7
2021-12-04 10:36:15 +08:00
AtlasAccount 3379cfc19b 同步1.5.0 b40935915374492ee86c8ac22df3c3b71d395a0b
!2723 在调用acl接口时释放gil锁,防止算子编译需要gil锁。
    Merge pull request !2723 from 宇世康/tr5
同步1.8.1 438c8daf58550d882e8b4763910cc93b927d89f7
    !2790 Task: clean codecheck warnings
    Merge pull request !2790 from 赵光灿/pytorch1.8.1
--
    !2773 1.8.1算子适配:ge,le
    Merge pull request !2773 from 王晓/1.8_ge_le_gt_lt
--
    !2770 【BugFix】【需求】NPU独有算子适配apply_adam_out_npu、bert_apply_adam_out_npu
    Merge pull request !2770 from 姚斌/pytorch1.8.1
--
    !2762 Task: clean codecheck warnings
    Merge pull request !2762 from 赵光灿/pytorch1.8.1
--
    !2740 【bugfix】【需求】【1.8NPU独有算子适配整改】npu_bert_apply_adam
    Merge pull request !2740 from 姚斌/pytorch1.8.1
--
    !2702 【需求】【1.8NPU独有算子适配】npu_bert_apply_adam、npu_apply_adam
    Merge pull request !2702 from 姚斌/pytorch1.8.1
--
    !2722 add cross-device copy check
    Merge pull request !2722 from weili10/pytorch1.8.1
--
    !2599 add:  erf op for ver 1.8.1
    Merge pull request !2599 from 郭夏/erf
--
    !2657 【1.8.1】适配“upsamplebilinear2d”
Merge: 1fb062334 049b1e4f2
    !2662 【1.8.1】适配“Scatter_”
    Merge pull request !2662 from 李攀/do_1.8.1
--
    !2647 delete redundant check_match and invalid trans-contiguous code
    Merge pull request !2647 from weili10/pytorch1.8.1
--
    !2700 bugfix: 修复profiler打印信息错误问题
    Merge pull request !2700 from shibo/profiler_bug
--
    !2696 【1.8算子适配】cdist、cdist_backward、pdist
    Merge pull request !2696 from 姚斌/pytorch1.8.1_1
--
    !2661 【1.8算子适配】softmax、true_divide
    Merge pull request !2661 from 姚斌/pytorch1.8.1
--
    !2642 【pytorch 1.8 算子适配】提交算子addmv、addr
    Merge pull request !2642 from TD_lihan/py18_addmv
--
    !2640 【pytorch 1.8 算子适配】提交算子adaptive_avg_pool1d
    Merge pull request !2640 from TD_lihan/py18_AdaptiveAvgPool1d
--
    !2604 【1.8算子迁移】卷积类修改等
    Merge pull request !2604 from 吴贤坤/conv_1.8
--
    !2654 增加profiler UT
    Merge pull request !2654 from shibo/profiler_ut
--
    !2668 【1.8算子适配】celu、selu
    Merge pull request !2668 from 姚斌/pytorch1.8.1_1
--
    !2683 1.8版本增加HCCL环境变量
    Merge pull request !2683 from shibo/add_env
--
    !2681 ddp在fp32场景下训练失败修复
    Merge pull request !2681 from shibo/dd_bugfix
--
    !2682 修复npu tensor类型转换丢失梯度属性问题
    Merge pull request !2682 from shibo/cast_bugfix
--
    !2601 PyTorch1.8算子适配:uniform_
    Merge pull request !2601 from 牛作东/uniform_
--
    !2645 Task: clean codecheck warnings
    Merge pull request !2645 from 赵光灿/pytorch1.8.1
--
    !2655 【1.8算子适配】randperm、stack
    Merge pull request !2655 from 姚斌/pytorch1.8.1_1
--
    !2652 【1.8算子适配】std、std_mean、trunc
    Merge pull request !2652 from 姚斌/pytorch1.8.1
--
    !2646 【1.8.1】适配“maxunpool3d”
    Merge pull request !2646 from 李攀/do_1.8.1_2
--
    !2638 【pytorch 1.8 算子适配】提交算子abs
    Merge pull request !2638 from TD_lihan/py18_abs
--
    !2648 【1.8适配】“优化test_floatstatus.py”
    Merge pull request !2648 from 李攀/do_1.8.1
--
    !2639 【pytorch 1.8 算子适配】提交算子acos
    Merge pull request !2639 from TD_lihan/py18_acos
--
    !2626 【1.8升级】L1Loss
--
    !2624 【适配】To/Rsub算子适配
    Merge pull request !2624 from 陈庆/pytorch1.8.1
--
    !2603 1.8算子迁移】ps_roi_pooling,npu_roi_align, npu_iou等
    Merge pull request !2603 from 吴贤坤/npu_fd_bd_1.8_bnms
--
    !2636 1.8版本优化profiler
    Merge pull request !2636 from shibo/profiler_simple
--
    !2631 Task: clean codecheck warnings
    Merge pull request !2631 from 赵光灿/pytorch1.8.1
--
    !2616 1.8.1算子tril、ne、eq适配迁移
    Merge pull request !2616 from 王晓/tril
--
    !2613 1.8.1算子triu适配迁移
    Merge pull request !2613 from 王晓/1.8.1_triu
--
    !2600 add:  exp op for 1.8.1
    Merge pull request !2600 from 郭夏/exp
--
    !2565 1.8.1适配“maxpool3d, smoothL1Loss, SoftMarginLoss”
    Merge pull request !2565 from 李攀/do_1.8.1_2
--
    !2617  【function】add python3.8 compiling to pytorch1.8
    Merge pull request !2617 from 李超/pytorch1.8.1
--
    !2612 【1.8算子迁移】tanh,sigmoidgrad等
    Merge pull request !2612 from 吴贤坤/backward_1.8
--
    !2610 【1.8适配】nllloss2dbackward
    Merge pull request !2610 from 李攀/do_1.8.1_5
--
    !2618 1.8版本profiling支持屏蔽适配层内算子
    Merge pull request !2618 from shibo/profiler_simple
--
    !2611 【1.8算子适配】min、mv、ones
    Merge pull request !2611 from 姚斌/pytorch1.8.1
--
    !2607 【1.8算子适配】round、rsqrt、sqrt
    Merge pull request !2607 from 姚斌/pytorch1.8.1
--
    !2582 【1.8算子迁移】thnn_conv2d_forward重构
    Merge pull request !2582 from 吴贤坤/thnn_conv_1.8
--
    !2581 【1.8算子迁移】Upsample部分
    Merge pull request !2581 from 吴贤坤/up3d_1.8
--
    !2579 1.8.1算子适配 cross
    Merge pull request !2579 from 王晓/1.8_cross
--
    !2495 【pytorch1.8适配】Where、Resize、Norm、Pow适配
    Merge pull request !2495 from 陈庆/pytorch1.8.1
--
    !2577 【1.8算子迁移】col2im等
    Merge pull request !2577 from 吴贤坤/colim_1.8
--
    !2574 pytorch1.8 pprofiling功能
    Merge pull request !2574 from shibo/profiler_update
--
    !2566 1.8.1适配“mseloss, avgpool2d, avgpool3d”
--
    !2575 1.8.1“float_status”
    Merge pull request !2575 from 李攀/do_1.8.1
2021-11-30 17:57:38 +08:00
weili10 4c2cf375f7 update README.zh.md. 2021-11-19 08:16:56 +00:00
i-robot cbdc747866 !79 update the catalog of en docs
Merge pull request !79 from yinzijun/2.0.3.tr5
2021-10-26 01:30:55 +00:00
ZijunYin 1669c7fb13 update en docs 2021-10-22 17:24:05 +08:00
i-robot ce67fc0403 !77 update image in Installation Guide
Merge pull request !77 from yinzijun/2.0.3.tr5
2021-10-15 10:32:48 +00:00
weili10 25a75f9138 update README.zh.md. 2021-10-15 10:05:03 +00:00
ZijunYin 46be05d4a2 update image in docs/en/PyTorch Installation Guide 2021-10-15 17:51:00 +08:00
i-robot 10a621ac7e !75 update English docs
Merge pull request !75 from yinzijun/2.0.3.tr5
2021-10-15 09:36:48 +00:00
ZijunYin 0d912b623e Merge branch '2.0.3.tr5' of https://gitee.com/yinzijun/pytorch into 2.0.3.tr5 2021-10-15 17:21:02 +08:00
ZijunYin d65305484e update English docs. 2021-10-15 17:20:53 +08:00
i-robot bc2de075f5 !73 更新readme:增加文档链接
Merge pull request !73 from shibo/2.0.3.tr5
2021-10-13 09:30:49 +00:00
shibo19 b9b85d8bb7 update readme 2021-10-13 16:16:16 +08:00
i-robot af55dd59af !71 update RELEASENOTE with 2.0.2
Merge pull request !71 from yinzijun/2.0.3.tr5
2021-10-09 10:11:51 +00:00
ZijunYin 2e1a17d4b1 Merge branch '2.0.3.tr5' of https://gitee.com/yinzijun/pytorch into 2.0.3.tr5 2021-10-09 17:55:00 +08:00
ZijunYin ab5f233823 update RELEASENOTE.md 2021-10-09 17:54:49 +08:00
yinzijun 4146762193 !68 update docs/zh/RELEASENOTE/RELEASENOTE.md.
Merge pull request !68 from liuquan/N/A
2021-10-09 08:42:49 +00:00
刘全 c24a2a26f2 update docs/zh/RELEASENOTE/RELEASENOTE.md. 2021-10-09 07:10:10 +00:00
yinzijun 99baa47bac !66 add releasenote
Merge pull request !66 from yinzijun/2.0.3.tr5
2021-10-09 07:03:02 +00:00
ZijunYin 3aad7226de add RELEASENOTE.md 2021-10-09 09:54:56 +08:00
weili10 2c1766a041 update README.zh.md. 2021-10-08 02:46:19 +00:00
yinzijun 58402d67d2 !64 update docs 2.0.3.B090
Merge pull request !64 from yinzijun/2.0.3.tr5
2021-09-30 07:26:33 +00:00
ZijunYin 22a5bf8eba update docs 2.0.3.B090 2021-09-30 15:14:19 +08:00
AtlasAccount 7ec3a5a42a 同步1.5.0 2c2f79aaccfa455fb24553f77cca62d838b75bdf
!2559 【BugFix】修复输入shape不一致,算子侧未broadcast,导致不支持
    Merge pull request !2559 from 姚斌/2.0.3.tr5
--
    !2558 modify:del test_cases of 1 dim and NZ format in UT files
    Merge pull request !2558 from 郭夏/2.0.3.tr5
--
    !2556 修复IOU输出数据类型转换
    Merge pull request !2556 from 李攀/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-28 22:05:02 +08:00
AtlasAccount 8611e0e3d5 同步1.5.0 a3c3eef54ba99da98fcfb1f47315ab0aaecb6f54
!2553 修复load模式时conv2d反向dump结果ir_name被覆盖的问题,合入商发
    Merge pull request !2553 from gaokai21/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 21:00:32 +08:00
AtlasAccount a2ed4eb074 同步1.5.0 55e1c5be4b9ce8cf007fdf7848d3e933c7dba800
!2548 [contrib/npu/optimized_lib/] merge master to 2.0.3.tr5
    Merge pull request !2548 from 王姜奔/2.0.3.tr5
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 14:33:37 +08:00
AtlasAccount c6d5d99656 同步1.5.0 210593a373ef600735b60946c7edeccefa97e5eb
!2546 修复maxunpool2dbackward执行报错
    Merge pull request !2546 from 李攀/bugfix
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
2021-09-27 11:01:57 +08:00
AtlasAccount c927f4d52e 同步1.5.0 f0be9e9f84b731b59baf432510a25b601e2ba1b3
!2538 修改norm精度问题
    Merge pull request !2538 from 李攀/bugfix
--
    !2534 添加gpu和npu映射接口
    Merge pull request !2534 from gaokai21/master
--
    !2541 【bugfix】修复输入维度不一致时,算子不支持场景
    Merge pull request !2541 from 陈庆/lshift
同步1.8.1 7afd57f35ebc3b81dd4c3f642e3f8ba81c1f07f0
    !2542 build.sh二次编译问题
    Merge pull request !2542 from 周司南/pytorch1.8.1
2021-09-26 18:06:10 +08:00
AtlasAccount a52a2a7582 同步1.5.0 b8c5f967d3793315893507c8bb0e8ef9d5f8ad5b
!2540 修改batchnormstats接口精度(静态)
    Merge pull request !2540 from 吴贤坤/bnstats
--
    !2535 [cube] bmmv2 delete expand
    Merge pull request !2535 from 丁世浩/master
同步1.8.1 bcb12248e9ba9e72b6852c05b06c80b7ca395169
2021-09-26 12:01:03 +08:00
AtlasAccount 28b81ba784 同步1.5.0 c22928e1702155adb6f17d45277269f90f0b6e43
!2533 Ptiou整改
    Merge pull request !2533 from 李攀/bugfix
同步1.8.1 bcb12248e9ba9e72b6852c05b06c80b7ca395169
2021-09-25 12:00:46 +08:00
AtlasAccount 118cead9db 同步1.5.0 67d1906d95b9ff3658f65b5e955b983950045425
!2531 PT整改scatterAdd
    Merge pull request !2531 from 李攀/bugfix
同步1.8.1 bcb12248e9ba9e72b6852c05b06c80b7ca395169
2021-09-24 12:00:46 +08:00
AtlasAccount 37983612eb 同步1.5.0 4951d13206bcd73597b7449b40ca7cf6cb846840
!2526 mm、bmm支持对齐shape的nd适配开关
    Merge pull request !2526 from 詹隽/mm_nd_dev
--
    !2484 [dump utils] support NPU dump and gpu load
    Merge pull request !2484 from lijing/master
--
    !2523 清理冗余代码
    Merge pull request !2523 from weili10/master
--
    !2518 修改 codex 问题
    Merge pull request !2518 from 周司南/master
同步1.8.1 bcb12248e9ba9e72b6852c05b06c80b7ca395169
    !2519 编译问题已修复,脚本还原
    Merge pull request !2519 from shibo/update_build
2021-09-23 12:01:05 +08:00
AtlasAccount a0d5f0413a 同步1.5.0 860b52e16d12312680f057183820b849682f701f
!2521 【问题清理】pad3问题修改
    Merge pull request !2521 from 吴贤坤/bugclear
--
    !2528 修复BatchNormElemt精度问题
    Merge pull request !2528 from 李攀/bugfix
--
    !2516 PT整改-UpsampleBilinear2D
    Merge pull request !2516 from 李攀/bugfix
同步1.8.1 0eab0ff8a6b96eb6053b87d428c18cdc0556ec8e
2021-09-22 12:00:46 +08:00
AtlasAccount 3f7654bb90 同步1.5.0 a515d5fc8cf79e7f998e72f7f358476a6f071d5b
同步1.8.1 0eab0ff8a6b96eb6053b87d428c18cdc0556ec8e
2021-09-21 12:00:58 +08:00
AtlasAccount 6f3c3f8c93 同步1.5.0 a515d5fc8cf79e7f998e72f7f358476a6f071d5b
同步1.8.1 0eab0ff8a6b96eb6053b87d428c18cdc0556ec8e
2021-09-20 12:01:04 +08:00
yinzijun 663e48a628 !62 update docs API支持清单
Merge pull request !62 from yinzijun/master
2021-09-19 13:53:30 +00:00
AtlasAccount 4c0b1766ab 同步1.5.0 a515d5fc8cf79e7f998e72f7f358476a6f071d5b
同步1.8.1 0eab0ff8a6b96eb6053b87d428c18cdc0556ec8e
2021-09-19 12:00:45 +08:00
ZijunYin 69547a0826 update docs/zh/PyTorch API支持清单/PyTorch API支持清单.md 2021-09-19 11:05:41 +08:00
ZijunYin 5b9b7041b2 update docs/zh/PyTorch API支持清单/PyTorch API支持清单.md 2021-09-19 11:02:34 +08:00
AtlasAccount bc0fbdcac9 同步1.5.0 a515d5fc8cf79e7f998e72f7f358476a6f071d5b
!2520 删除OpcommandBase的拷贝和赋值构造函数,不应出现UpSample**算子适配中的这种用法
    Merge pull request !2520 from 宇世康/master
--
    !2515 Bugfix: fix codemars warnings and add path check
    Merge pull request !2515 from 赵光灿/master
同步1.8.1 0eab0ff8a6b96eb6053b87d428c18cdc0556ec8e
    !2513 适配"elu, hardsigmoid, nllloss2d, multilabel_margin_loss"
Merge: d767dccb7 bbfa373d9
    !2517 1.8适配“softshrink, softplus, adaptiveavgpool3d, adaptivemaxpool2d”
    Merge pull request !2517 from 李攀/do_1.8.1_3
2021-09-18 12:03:11 +08:00
i-robot ea561b97c9 !57 Add py38 package building method
Merge pull request !57 from 李超/master
2021-09-17 05:50:33 +00:00
AtlasAccount f431153967 同步1.5.0 888d06f1b261e49f6329a2a72358792bab258c94
同步1.8.1 d767dccb71ea1043a0fbe0d7a814f6bde2232923
2021-09-17 12:01:01 +08:00
AtlasAccount e82066018d 同步1.5.0 888d06f1b261e49f6329a2a72358792bab258c94
!2510 路径检查
    Merge pull request !2510 from shibo/path_check
同步1.8.1 d767dccb71ea1043a0fbe0d7a814f6bde2232923
    !2512 bugfix 编译错误
    Merge pull request !2512 from 周司南/pytorch1.8.1
--
    !2508 pytorch 1.5.0 同步 1.8.1
    Merge pull request !2508 from 周司南/pytorch1.8.1
--
    !2511 1.8"hardtanh, leakyrelu, logsigmoid"
    Merge pull request !2511 from 李攀/do_1.8.1_3
--
    !2494 diag 1.8.1适配
    Merge pull request !2494 from 王晓/1.8_diag
2021-09-17 09:25:03 +08:00
yinzijun a4fdc51ac9 !61 2.0.3.B060版本资料更新
Merge pull request !61 from yinzijun/master
2021-09-16 12:09:19 +00:00
ZijunYin 42badebbad 2.0.3.B060资料转测 2021-09-16 19:48:58 +08:00
yinzijun 9d43973a43 !60 update docs with all-in-one
Merge pull request !60 from yinzijun/master
2021-09-16 08:11:50 +00:00
ZijunYin 9d4224f9a5 update all-in-one docs/zh/PyTorch安装指南/PyTorch安装指南.md 2021-09-16 15:54:01 +08:00
AtlasAccount c2a7dc3f17 同步1.5.0 faf66d48f5856b0b9c16a07aec78f76bee01e675
!2487 泛化:norm算子适配修改
    Merge pull request !2487 from 姚斌/master
--
    !2509 performance optimization
    Merge pull request !2509 from 蒋荣强/optimize1
--
    !2507 【Adapter Task】batch_norm_backward_reduce 适配
    Merge pull request !2507 from 吴贤坤/bn_bw_rd
同步1.8.1 09f155356e3f4323d88c7181e8b2915ba04e6033
    !2462 1.8版本:更新readme文件
    Merge pull request !2462 from shibo/add_readme_181
2021-09-16 12:01:54 +08:00
i-robot be21b4c339 !58 docs更新:增加编译选项说明
Merge pull request !58 from shibo/update_idp
2021-09-15 08:32:30 +00:00
i-robot 851cc9e42e !56 更新readme
Merge pull request !56 from shibo/read_me
2021-09-15 08:30:35 +00:00
AtlasAccount 6963a9c6f5 同步1.5.0 0fc7ffde0cfcfb82e1bee4ab124136433a54dee0
!2502 [fixbug]  Fill, avgpool2d修复
    Merge pull request !2502 from 吴贤坤/fixbug
--
    !2500 batchnormelemt添加参数检查
    Merge pull request !2500 from 李攀/bugfix
同步1.8.1 fd81d36aac30c9ea0c1cb91f1e36c146d549711e
2021-09-15 12:00:49 +08:00
shibo19 f38ae2d871 add compile option note 2021-09-14 20:24:09 +08:00
AtlasAccount cc3ebabbca 同步1.5.0 6ce19779227f5b627f6aa39eb5c8db32d3fd91ea
!2501 修复ndexing不支持动态shape问题
    Merge pull request !2501 from 李攀/bugfix_2
--
    !2485 path路径强校验
    Merge pull request !2485 from 周司南/master
同步1.8.1 fd81d36aac30c9ea0c1cb91f1e36c146d549711e
    !2499 移除CPU上NPU的依赖, 支持USE_NPU=0编译
    Merge pull request !2499 from 周司南/pytorch1.8.1
2021-09-14 12:00:45 +08:00
AtlasAccount d70ae50d78 同步1.5.0 aff14c6dd491ed6b2ddebb15c64a366bfb231188
同步1.8.1 135d70c6d0d16b381e35a39747659e7f3d6cda96
2021-09-13 12:00:45 +08:00
李超 f99298b02b Add py38 package building method 2021-09-13 10:54:06 +08:00
AtlasAccount 8d64c91316 同步1.5.0 aff14c6dd491ed6b2ddebb15c64a366bfb231188
!2489 修复双向lstm参数传入数量不对问题
    Merge pull request !2489 from zhusiyi/master
同步1.8.1 135d70c6d0d16b381e35a39747659e7f3d6cda96
2021-09-12 12:00:54 +08:00
AtlasAccount a40e37d953 同步1.5.0 0cfee0d7ea81c78b852cadfadf8e64021b167307
同步1.8.1 135d70c6d0d16b381e35a39747659e7f3d6cda96
2021-09-11 12:00:46 +08:00
AtlasAccount 5996fed7b1 同步1.5.0 0cfee0d7ea81c78b852cadfadf8e64021b167307
同步1.8.1 135d70c6d0d16b381e35a39747659e7f3d6cda96
    !2498 fixBug conv2d_out_npu
    Merge pull request !2498 from 周司南/pytorch1.8.1
2021-09-10 15:50:07 +08:00
AtlasAccount 3be7bcf63d 同步1.5.0 0cfee0d7ea81c78b852cadfadf8e64021b167307
同步1.8.1 88795ab0435ba8144a5b419d0144698c6dc7c7b3
    !2491 【pytorch1.8算子适配】neg reciprocal sin sinh tan tanh
    Merge pull request !2491 from 姚斌/pytorch1.8.1
2021-09-10 13:56:49 +08:00
AtlasAccount 6fc30ad19f 同步1.5.0 0cfee0d7ea81c78b852cadfadf8e64021b167307
同步1.8.1 a69145e398ceaa35226f3c5d977a07f041448939
2021-09-10 12:00:48 +08:00
AtlasAccount 81a39d545f 同步1.5.0 0cfee0d7ea81c78b852cadfadf8e64021b167307
!2496 [bugfix] BinaryCrossEntroy反向适配代码修改
    Merge pull request !2496 from 吴贤坤/bugfix
同步1.8.1 a69145e398ceaa35226f3c5d977a07f041448939
2021-09-09 16:08:52 +08:00
AtlasAccount 75a9089e09 同步1.5.0 45372575e229cb5261582ebd322a30805f68ebb3
!2493 修复ndexing不支持动态shape问题
    Merge pull request !2493 from 李攀/bugfix
--
    !2492 适配batch_norm_elemt
    Merge pull request !2492 from 李攀/master
同步1.8.1 a69145e398ceaa35226f3c5d977a07f041448939
    !2474 convolution
    Merge pull request !2474 from 周司南/pytorch1.8.1
2021-09-09 12:00:45 +08:00
weili10 b256f3cfcd update README.zh.md. 2021-09-09 02:55:55 +00:00
AtlasAccount a03b990d2f 同步1.5.0 0bebd44de43cda65ac171865c966d0f050740d04
!2471 【ut修复】GE增加对tensor的shape校验,导致部分UT不过
    Merge pull request !2471 from TD_lihan/utMod
--
    !2476 【FixBug】修复prod精度问题
    Merge pull request !2476 from 王晓/prod
同步1.8.1 493306e5d89167be4d0e81258af2cbddafc07364
2021-09-08 12:01:03 +08:00
shibo19 b1de459aab update readme 2021-09-07 20:16:00 +08:00
i-robot 78bb23dcfc !55 更新readme文件
Merge pull request !55 from shibo/master
2021-09-07 05:54:37 +00:00
AtlasAccount 358e163e2b 同步1.5.0 a82d3d1c73af57ba35e1e468b406140f13b34b51
!2481 更新环境变量设置HCCL
    Merge pull request !2481 from shibo/add_env
--
    !2479 【适配】ReflectionPad2D支持fp32输入
    Merge pull request !2479 from 陈庆/master
同步1.8.1 493306e5d89167be4d0e81258af2cbddafc07364
    !2475 1.8版本:更新编译报错信息
    Merge pull request !2475 from shibo/update_build
2021-09-07 12:00:55 +08:00
shibo19 e3cacd1240 update read me 2021-09-06 16:34:48 +08:00
AtlasAccount 5a675a23c2 同步1.5.0 766d7155090aaefb27fff8934d644d2741922d15
!2470 Feature: add load with acl dump function
    Merge pull request !2470 from 赵光灿/master
同步1.8.1 c28fda19acb944bc0859c243c889137491da831d
2021-09-06 12:00:55 +08:00
yinzijun 62e6edd1be update docs/zh/PyTorch网络模型移植&训练指南/PyTorch网络模型移植&训练指南.md.
修改表格样式问题
2021-09-05 09:38:58 +00:00
AtlasAccount 8b0bb12ed2 同步1.5.0 488d65cf1f2832a605272d7ed32678bc9286828e
!2473 适配: roi_align&roi_align_backward算子适配重构与修改
    Merge pull request !2473 from 姚斌/master
--
    !2467 泛化:logical_not_out算子增加outshape_resize
    Merge pull request !2467 from 姚斌/master
--
    !2472 适配replicationPad2dBackward
    Merge pull request !2472 from 李攀/replication_backward
--
    !2466 【适配】ReflectionPad2D反向适配
    Merge pull request !2466 from 陈庆/padv3grad
--
    !2461 "修改适配replicationPad2d, reflectionPad2d"
    Merge pull request !2461 from 李攀/master
--
    !2459 [Requirement] batchnormstats adapter
    Merge pull request !2459 from 吴贤坤/bnstats
--
    !2463 [bugfix] span-axis indexing should execute ptcopy
    Merge pull request !2463 from 李超/master
--
    !2457 bugfix: const节点性能优化
    Merge pull request !2457 from 郭鹏/master
--
    !2464 max_unpool3d正反向添加输入校验
    Merge pull request !2464 from 王晓/max_unpool3d
--
    !2460 【迭代四需求】max_unpool3d正反向适配
    Merge pull request !2460 from 王晓/max_unpool3d
--
    !2454 泛化:inverse支持入参fp16
    Merge pull request !2454 from 姚斌/master
--
    !2446 【迭代四需求】修改constant_pad_nd反向适配,支持更多场景
    Merge pull request !2446 from 王晓/constant_pad_nd
--
    !2447 "MaxUnpool2d"适配
    Merge pull request !2447 from 李攀/master
--
    !2445 [optimize]  optimize mm adapter and refresh storage desc
    Merge pull request !2445 from 李超/master
--
    !2453 [dump utils] fix bug: creating Int blob with Long data
    Merge pull request !2453 from lijing/master
--
    !2439 [contrib/npu/optimized_lib/] add npu_bbox_coder_encode_xyxy2xywh and npu_bbox_coder_decode_xywh2xyxy
    Merge pull request !2439 from 王姜奔/bounding_box_decode
--
    !2451 Feature: support detect_anomaly when check overflow is on
    Merge pull request !2451 from 赵光灿/master
--
    !2452 【客户现场问题】softmax_backward支持动态nz场景
    Merge pull request !2452 from 王晓/softmax_backward_nz
--
    !2437  [contrib/npu/optimized_lib/] add 双向lstm
    Merge pull request !2437 from zhusiyi/master
--
    !2449 const节点创建host tensor使用memcpy优化性能
    Merge pull request !2449 from 郭鹏/master
--
    !2450 performance optimization
    Merge pull request !2450 from 蒋荣强/optimize
--
    !2448 [Optim] 优化AvgPoolv2性能
    Merge pull request !2448 from 吴贤坤/avgpoolv2
--
    !2443 cumsum性能优化
    Merge pull request !2443 from 陈庆/cumsum
--
    !2429 softmax_backward添加nz分支
    Merge pull request !2429 from 王晓/softmax_backward_nz
--
    !2442 requirement文件修改:pytorch1.5版本仅支持torchvision0.6版本
    Merge pull request !2442 from shibo/fix_readme
--
    !2427 performance optimization
    Merge pull request !2427 from 蒋荣强/optimize
--
    !2433 mm及bmm适配代码优化
    Merge pull request !2433 from 郭鹏/master
--
    !2436 [Bugfix] avgpoolv2问题修复
    Merge pull request !2436 from 吴贤坤/avgpolv2
--
    !2438 [Bugfix] con3dBackward 特殊shape问题修复
    Merge pull request !2438 from 吴贤坤/conv3dbackwardissue
--
    !2423 适配acl Prof api,支持cann profiling
    Merge pull request !2423 from 李攀/master
--
    !2428 算子适配:conv_transpose3d_backward
    Merge pull request !2428 from 姚斌/master
--
    !2432 [contrib/npu/optimized_lib/] add Mish
    Merge pull request !2432 from 王姜奔/master
--
    !2426 【适配】增加cummin aicpu算子适配,支持int64输入
    Merge pull request !2426 from 陈庆/cummin
--
    !2431 修改NPUClearFloatStatus算子适配
    Merge pull request !2431 from 詹隽/master
--
    !2430  [optimize] 支持py37和py38 torch包编译
    Merge pull request !2430 from 李超/master
--
    !2414 change TBE-OP for select contiguous opt
    Merge pull request !2414 from 王强/master
--
    !2425 泛化:logspace_out算子增加outshape_resize
    Merge pull request !2425 from 姚斌/master
--
    !2406 Feature: add overflow detection function
    Merge pull request !2406 from 赵光灿/master
--
    !2408 DDP: fix bug. when using DDP, the grad format is different from variable results in an error.
    Merge pull request !2408 from 袁舰/master
--
    !2419 LayerNorm正反向下发性能优化
    Merge pull request !2419 from 郭鹏/master
--
    !2407 [contrib/npu/optimized_lib/] add npu_fast_condition_index_put
    Merge pull request !2407 from 王姜奔/master
--
    !2422 泛化:torch.lt(xx, out=output)场景限制output_dtype为Bool
    Merge pull request !2422 from 姚斌/master
--
    !2420 【算子适配】适配shift系列算子
    Merge pull request !2420 from TD_lihan/bsd
--
    !2416 DUMP:fix bug. when cloning a tensor from gpu to cpu, the stride of the tensor still keeps invariable.
    Merge pull request !2416 from 袁舰/tmp
--
    !2421 [bugfix] 修改padv3执行时传参错误
    Merge pull request !2421 from 吴贤坤/padv2_issue
--
    !2411 泛化:topk算子增加outshape_resize场景
    Merge pull request !2411 from 姚斌/master
--
    !2415 【bugfix】修复`fill` 当dim=0 bug
    Merge pull request !2415 from 吴贤坤/fill_issue
--
    !2403 放开layernorm_backward适配层format限制
    Merge pull request !2403 from 王晓/layernorm_backward
--
    !2412 [issue] 模型场景问题修改
    Merge pull request !2412 from 吴贤坤/issue_3
--
    !2410 performance optimization
    Merge pull request !2410 from 蒋荣强/optimize
--
    !2405 泛化:argmin算子输出format为ND
    Merge pull request !2405 from 姚斌/master
--
    !2409  aoe功能使用多线程调优加速
    Merge pull request !2409 from shibo/aoe_thread
同步1.8.1 c28fda19acb944bc0859c243c889137491da831d
    !2469 1.8版本arm编译失败临时修复
    Merge pull request !2469 from shibo/update_build
--
    !2468 1.8.1移除动态shape能力
    Merge pull request !2468 from 周司南/pytorch1.8.1
--
    !2458 1.8版本:reducer中hook更新,与开源版本保持一致
    Merge pull request !2458 from shibo/ddp_181_hook
--
    !2455 add new adaper for 1.8.1
    Merge pull request !2455 from 周司南/pytorch1.8.1
--
    !2441 pytorch1.8.1: 支持DDP训练
    Merge pull request !2441 from shibo/test_181_ddp
2021-09-03 17:51:40 +08:00
weili10 08895e3452 !53 更新1.8.1:增加1.8.1的版本
Merge pull request !53 from shibo/pt1.8.1_test
2021-09-03 09:44:40 +00:00
shibo19 eb19e5be07 update sh 2021-09-03 15:42:23 +08:00
shibo19 dbbb5b935b 同步1.5.0 ce8e47ddddc42aa66b88188f25be654e3baf1739
同步1.8.1 e4cc08b6ff7a4dcf246e669f0d2d424e2742a7cc
2021-09-02 20:06:56 +08:00
shibo19 27b2513f2f 同步1.5.0 ce8e47ddddc42aa66b88188f25be654e3baf1739 同步1.8.1 e4cc08b6ff7a4 2021-09-02 20:05:45 +08:00
shibo19 18cee26cfb update UT control 2021-09-02 19:47:40 +08:00
shibo19 d9c203af66 rename 2021-09-02 19:26:29 +08:00
shibo19 a96f349728 同步1.5.0 ce8e47ddddc42aa66b88188f25be654e3baf1739 同步1.8.1 e4cc08b6ff7a4dcf246e669f0d2d424e2742a7cc 2021-09-02 16:58:09 +08:00
weili10 08d67bb93b 删除文件 pt_sync.log 2021-09-02 06:41:21 +00:00
AtlasAccount 9d1f8c2062 同步 86fcbb8e91b16e2437c36fc6ca3a8d224e95bfb9
泛化:logical_not_out算子增加outshape_resize
2021-09-02 12:00:33 +08:00
yinzijun e56d176f63 !50 2.0.3.B050资料转测
Merge pull request !50 from yinzijun/master
2021-09-02 02:02:26 +00:00
AtlasAccount 46d2c88c76 同步 c023657b36fc647854d45a12b9833e2409cbf6e7
适配replicationPad2dBackward
 【适配】ReflectionPad2D反向适配
 "修改适配replicationPad2d, reflectionPad2d"
 [Requirement] batchnormstats adapter
2021-09-01 23:00:36 +08:00
ZijunYin 16c6efb99c 2.0.3.B050资料刷新 2021-09-01 17:27:12 +08:00
AtlasAccount 3deb4f4041 同步 16fcae50a1131194038eec02a1fccd28387424e5
[bugfix] span-axis indexing should execute ptcopy
 bugfix: const节点性能优化
 max_unpool3d正反向添加输入校验
 【迭代四需求】max_unpool3d正反向适配
2021-08-31 23:00:36 +08:00
AtlasAccount 63f22cf38d 同步 9ba6d751ab1207d32114588c43d1d366d9581783
泛化:inverse支持入参fp16
 【迭代四需求】修改constant_pad_nd反向适配,支持更多场景
 "MaxUnpool2d"适配
2021-08-30 23:00:35 +08:00
AtlasAccount 95bc96954a 同步 9fb28f8d7e69fa020ebe4b5bb91727b80c8b676b
[optimize] optimize mm adapter and refresh storage desc
2021-08-28 23:00:41 +08:00
AtlasAccount a323bfb26d 同步 51620ab6aa9631e02aff3c893c4a98b3441be1d7
[dump utils] fix bug: creating Int blob with Long data
 [contrib/npu/optimized_lib/] add npu_bbox_coder_encode_xyxy2xywh and npu_bbox_coder_decode_xywh2xyxy
 Feature: support detect_anomaly when check overflow is on
2021-08-28 12:00:36 +08:00
AtlasAccount 4c28fae7ff 同步 a50381c14de1fe552161254749e980f6993d4074
【客户现场问题】softmax_backward支持动态nz场景
 [contrib/npu/optimized_lib/] add 双向lstm
2021-08-27 23:00:33 +08:00
AtlasAccount d73f7d15d1 同步 84bf1f2f6e1e5bcd2515f4504587527371b56413
const节点创建host tensor使用memcpy优化性能
2021-08-27 12:00:37 +08:00
AtlasAccount 64142762fb 同步 57eb858d9a5188f7ccbd3fa2ef99d4467589a086
performance optimization
2021-08-26 23:00:34 +08:00
yinzijun 2671012415 !47 2.0.3.B030版本资料更新
Merge pull request !47 from yinzijun/master
2021-08-26 04:25:21 +00:00
ZijunYin 9cb88c4ae8 add img pth 2021-08-26 11:41:58 +08:00
ZijunYin 3015977115 delete img pth 2021-08-26 11:40:56 +08:00
ZijunYin 25e1415cb4 renew . 2021-08-26 11:31:36 +08:00
AtlasAccount 9276d4c441 同步 15422a9ff9ee2bb3c906de5f068297fe98c61cee
[Optim] 优化AvgPoolv2性能
2021-08-25 23:00:37 +08:00
yinzijun 3ab4642abd Remove docs/en 2021-08-25 09:32:18 +00:00
AtlasAccount aa1466742a 同步 02aa66378171f6b55cbe50ae3a6067de937af8d0
cumsum性能优化
 softmax_backward添加nz分支
 requirement文件修改:pytorch1.5版本仅支持torchvision0.6版本
2021-08-24 23:00:37 +08:00
AtlasAccount 9bfd72d468 同步 ead0163f4e42079e08e018f89b7d4b1caa7a5b27
performance optimization
 mm及bmm适配代码优化
2021-08-24 12:00:41 +08:00
AtlasAccount 0fa13028d3 同步 8468e3b692abe1e24a2576c1c3db71e76105fd3b
[Bugfix] avgpoolv2问题修复
 [Bugfix] con3dBackward 特殊shape问题修复
 适配acl Prof api,支持cann profiling
2021-08-23 23:00:37 +08:00
AtlasAccount 358cba8b6d 同步 a479199b1693507a24d1df875f6844a2665d9306
算子适配:conv_transpose3d_backward
 [contrib/npu/optimized_lib/] add Mish
 【适配】增加cummin aicpu算子适配,支持int64输入
 修改NPUClearFloatStatus算子适配
2021-08-23 12:00:32 +08:00
AtlasAccount c684b7c74a 同步 c6cc6fae2f5bb369d7b166fa1900f6e75723cad8
[optimize] 支持py37和py38 torch包编译
2021-08-21 23:00:38 +08:00
AtlasAccount d836a9cb3c 同步 b6418a68885f2731c65d5d860d37b0ab866367c5
change TBE-OP for select contiguous opt
2021-08-20 23:00:34 +08:00
AtlasAccount 369ebefd2e 同步 f50f0921fd20ee29f1d82784ec88c1be6ef18820
泛化:logspace_out算子增加outshape_resize
 Feature: add overflow detection function
2021-08-19 23:00:34 +08:00
AtlasAccount e1b754a902 同步 a7b60a03303b40169cbab3829fcc57f2ce72faf2
DDP: fix bug. when using DDP, the grad format is different from variable results in an error.
 LayerNorm正反向下发性能优化
2021-08-18 12:00:40 +08:00
AtlasAccount c6ad5c5cc5 同步 082c70d8d31797c00fb0e00cfb0a84c1cc11651d
[contrib/npu/optimized_lib/] add npu_fast_condition_index_put
 泛化:torch.lt(xx, out=output)场景限制output_dtype为Bool
 【算子适配】适配shift系列算子
 DUMP:fix bug. when cloning a tensor from gpu to cpu, the stride of the tensor still keeps invariable.
 [bugfix] 修改padv3执行时传参错误
 泛化:topk算子增加outshape_resize场景
2021-08-17 23:00:33 +08:00
AtlasAccount 54af470c20 同步 3d1cd19f02b15fb9699e73594416f28187a96990
【bugfix】修复`fill` 当dim=0 bug
 放开layernorm_backward适配层format限制
 [issue] 模型场景问题修改
 performance optimization
2021-08-16 23:00:32 +08:00
AtlasAccount c56e5299d5 同步 77355b7650e725d5db500750c0215000598f3e29
泛化:argmin算子输出format为ND
2021-08-16 12:00:34 +08:00
AtlasAccount edfe8b0306 同步 7485a1162efb716e0ab3b6c214098246f62f4fd5
aoe功能使用多线程调优加速
2021-08-14 23:00:33 +08:00
AtlasAccount 0143c1c06e 同步 ce8e47ddddc42aa66b88188f25be654e3baf1739
新增适配reflection_pad2d
 DDP: fix bug of set broadcast_buffers true
 泛化:index_select_out算子增加outshape_resize
 [contrib/npu/optimized_lib/] add npu_yolo_bbox_coder
 【PT整改】PTTriu算子整改
 【算子适配】cummax算子适配
 泛化:stack输出format修改为ND
 开源申明修改
 [bugfix] 修复scatter操作报错当dtype为int32
 Feature: add some debug logs for accuracy comparison
 算子cumsum 在dim=0时走aicpu分支
 算子适配整改:masked_select重构、增加outshape_resize
 算子适配:slow_conv3d、slow_conv3d_forward
 搬运:修改env中拼写错误
2021-08-13 18:32:50 +08:00
weili10 fe09035482 update OWNERS. 2021-08-10 09:00:24 +00:00
yinzijun e8f0e0055c Create en 2021-08-10 03:17:53 +00:00
weili10 255e1b94f6 update scripts/mkdirs.sh. 2021-08-09 07:57:30 +00:00
weili10 b184e1c1d3 update scripts/gen.sh. 2021-08-09 07:57:18 +00:00
weili10 a85cb62301 update LICENSE. 2021-08-09 07:55:30 +00:00
weili10 1500208c7f update LICENSE. 2021-08-09 07:55:03 +00:00
weili10 073ad70cc4 update LICENSE. 2021-08-09 07:54:46 +00:00
weili10 6741696481 调整安装python依赖库位置 2021-08-09 03:23:45 +00:00
i-robot 48dd2489e0 !39 在README中增加版本配套信息
Merge pull request !39 from yinzijun/master
2021-08-06 09:09:23 +00:00
AtlasAccount 7e0b4081ac 同步 43d1f773fd5478ce787360f3c9ced77ae075fbee
修复triangular_solve out报错
 [contrib/npu/optimized_lib/] add npu_single_level_responsible_flags
2021-08-06 16:45:30 +08:00
i-robot 88d5c2c545 !38 env.sh拼写错误
Merge pull request !38 from luweizheng/master
2021-08-05 09:55:22 +00:00
ZijunYin c39847cbba 在README中增加版本配套关系 2021-08-05 17:52:16 +08:00
Lu Weizheng 8fa79690b2 fix env.sh ASCEND typo 2021-08-04 09:46:25 +08:00
AtlasAccount b6464ff2b2 同步 99861473ecf33d695ac1b85a43b5e71b3ac6b6d0
修改deformable_conv2d ut
 scatter算子修改适配到ScatterElements
2021-08-03 21:45:37 +08:00
i-robot a12b0dd319 !37 同步 fb8fc52370bce643091b8572fae8fd151d233bde
Merge pull request !37 from weili10/master
2021-08-03 08:37:20 +00:00
i-robot b9c513ed2d !35 更新算子文档
Merge pull request !35 from yinzijun/master
2021-08-03 08:35:22 +00:00
weili10 e7218aaf60 同步 fb8fc52370bce643091b8572fae8fd151d233bde
[Issue] 模型问题修复
 [contrib/npu/optimized_lib/] add DCNv2
 [bugfix] 规避aicpu fp16不支持场景
 修改pytorch版本到post3
 dump: fix bug of uncontiguous
 “回退scatter_add,性能不达标”
2021-08-03 16:07:57 +08:00
weili10 5de5ce6d04 update OWNERS. 2021-07-31 08:00:23 +00:00
ZijunYin 62992d4000 更新算子开发指南和适配算子清单 2021-07-31 10:25:57 +08:00
weili10 34f84c6ca4 !34 同步 b55753edf56f77307aa77d9034d581430892dff8
Merge pull request !34 from weili10/master
2021-07-29 12:33:33 +00:00
weili10 4ebeb1fd6a 同步 b55753edf56f77307aa77d9034d581430892dff8
【泛化】NllLoss2d & NllLoss2dBackward only support Target Int32/Long
 放开dropout适配层format限制
 PT整改,回退“PTTriu”
 增加算子编译选项:使用高精度/高性能模式算子
 【泛化】torch.lt( )计算支持bool类型入参
 _svd_helper算子适配
2021-07-29 20:15:47 +08:00
i-robot c4c5da1ed0 !26 文档修改命名格式归档
Merge pull request !26 from yinzijun/master
2021-07-29 09:17:03 +00:00
张昱杰 4ad96e17f4 update scripts/mkdirs.sh. 2021-07-29 09:13:17 +00:00
ZijunYin f6bd4ea357 change name of releasenote 2021-07-29 16:46:11 +08:00
i-robot 6c52cd2a5d !29 增加开源软件使用说明
Merge pull request !29 from weili10/master
2021-07-29 01:15:03 +00:00
weili10 11ee398a57 增加开源软件使用说明 2021-07-28 21:59:09 +08:00
ZijunYin c4c9340104 update docs, add releasenote 2021-07-28 20:55:49 +08:00
ZijunYin 931f3c3878 add docs with new name and icon 2021-07-27 16:50:44 +08:00
ZijunYin a48b4fd558 update doc with new file name and icon 2021-07-27 16:42:59 +08:00
i-robot d44bc70aae !25 同步 2e109bb3201b0dab4d8445c7c431c2edf5868ccc
Merge pull request !25 from weili10/master
2021-07-26 13:55:24 +00:00
weili10 021efdf1da 同步 2e109bb3201b0dab4d8445c7c431c2edf5868ccc
【Task】Erfc适配
 算子适配:conv_transpose3d
 _triangular_solve_helper算子适配
 API兼容性整改:编译接口AclopSetCompileFlag
2021-07-26 21:32:26 +08:00
i-robot 1d607dcf4f !24 同步 99ba430b04031e42d0284436f13584a845d82b53
Merge pull request !24 from weili10/master
2021-07-23 10:54:34 +00:00
weili10 b2afdd7871 同步 99ba430b04031e42d0284436f13584a845d82b53
Symeig算子适配
 rrelu_with_noise适配
2021-07-23 18:20:45 +08:00
i-robot 37fc10168a !23 同步 8ec7266c6bdd8119c253919567c2870a3f5aae0c
Merge pull request !23 from weili10/master
2021-07-22 12:40:49 +00:00
weili10 6432bc6349 同步 8ec7266c6bdd8119c253919567c2870a3f5aae0c
泛化:smooth_l1_loss算子支持 0 Shape输入
 【算子适配】tril_indices/triu_indices算子适配
2021-07-22 20:24:36 +08:00
weili10 4160ab8ab6 !22 同步 384a3c920d51a9e7538b7f99737d8acd0f8bd63e
Merge pull request !22 from weili10/master
2021-07-22 01:14:11 +00:00
weili10 afaa4d4e88 同步 384a3c920d51a9e7538b7f99737d8acd0f8bd63e
PT整改
 泛化:torch.max(input, dim, keppdim)支持input为DT_BOOL或DT_INT32入参
 modify the method of query event status
2021-07-21 17:15:46 +08:00
weili10 91014cd3b8 !21 同步 7ea28538822d890b75b190fbd8a1e1f984e4e9e2
Merge pull request !21 from weili10/master
2021-07-20 11:42:49 +00:00
weili10 798f0c3b16 同步7ea28538822d890b75b190fbd8a1e1f984e4e9e2 2021-07-20 19:11:41 +08:00
weili10 c28c47c9cd update LICENSE. 2021-07-16 13:42:44 +00:00
weili10 bda914c574 !17 同步b98f7ec21ee0d6c14be8b0bd09301d9f6e686816
Merge pull request !17 from weili10/master
2021-07-16 13:42:01 +00:00
weili10 edb5c70443 同步b98f7ec21ee0d6c14be8b0bd09301d9f6e686816 2021-07-16 18:19:48 +08:00
weili10 4689a0514b !13 [Task]新版本文档归档
Merge pull request !13 from fenghaolin/master
2021-07-14 13:53:10 +00:00
fenghaolin 63950d1412 新版本资料归档 2021-07-14 21:27:33 +08:00
weili10 16fb2692c6 update LICENSE. 2021-07-14 05:52:06 +00:00
weili10 193cd1f80d update LICENSE. 2021-07-14 04:08:58 +00:00
weili10 6b5302218a update LICENSE. 2021-07-14 03:54:29 +00:00
weili10 a27e4f60c6 !11 同步44740072b1b0ea6a5b63ef7203bab73f986e2472
Merge pull request !11 from weili10/master
2021-07-13 07:55:04 +00:00
weili10 ae48832f81 同步44740072b1b0ea6a5b63ef7203bab73f986e2472 2021-07-13 15:52:09 +08:00
weili10 08403764d6 !10 优化readme中命令执行目录说明
Merge pull request !10 from weili10/master
2021-07-12 12:26:05 +00:00
weli10 998d0c88b9 优化readme中命令执行目录说明 2021-07-12 20:24:20 +08:00
张昱杰 7a0a5a6eb0 !5 [Task]添加docs文件夹中的文档
Merge pull request !5 from fenghaolin/0706
2021-07-09 09:54:27 +00:00
张昱杰 cb9b8627b9 !8 同步42f3827ef92a65a09eee3dd1a9f527de774f5da2
Merge pull request !8 from 张昱杰/master
2021-07-09 09:52:37 +00:00
ascendzyj 6b80c3e7d6 Merge branch 'master' of https://gitee.com/ascend/pytorch into master 2021-07-09 17:47:57 +08:00
weili10 b6069682fd !7 修改命名
Merge pull request !7 from 张昱杰/master
2021-07-09 09:47:39 +00:00
ascendzyj 9cb7f795df Merge branch 'master' of https://gitee.com/ascend/pytorch into master 2021-07-09 17:44:15 +08:00
ascendzyj 7024d04779 同步42f3827ef92a65a09eee3dd1a9f527de774f5da2 2021-07-09 17:43:07 +08:00
z00444290 70f0613df8 修改命名 2021-07-09 16:55:01 +08:00
z00444290 2468dd37ae 修改生成代码和编译脚本 2021-07-08 21:29:58 +08:00
张昱杰 7446763b5f !6 删除URL信息
Merge pull request !6 from 张昱杰/master
2021-07-08 02:25:23 +00:00
ascendzyj a45cb145e9 删除URL信息 2021-07-07 13:54:50 +08:00
fenghaolin 6bbc1db7d2 新增网络模型移植&训练指南 2021-07-06 11:35:16 +08:00
fenghaolin 59d9f9fe86 新增在线推理指南 2021-07-06 11:34:55 +08:00
fenghaolin c682f1e267 新增API支持清单 2021-07-06 11:34:38 +08:00
fenghaolin 1505864443 新增PyTorch适配算子清单 2021-07-06 11:34:19 +08:00
fenghaolin fdfb70af54 新增开发指南 2021-07-06 11:33:56 +08:00
fenghaolin aac3e9f237 添加算子清单 2021-07-06 11:33:16 +08:00
fenghaolin cb5937bf50 删除不需要的内容 2021-07-06 11:32:45 +08:00
fenghaolin 45a79b8865 Merge branch 'master' of https://gitee.com/ascend/pytorch 2021-07-06 11:30:14 +08:00
i-robot 18a27fad1f !4 同步f2209ee61066ae89d4efd1782a30b6235e0e0548
Merge pull request !4 from 张昱杰/master
2021-07-05 11:05:18 +00:00
ascendzyj 2ae4953208 同步f2209ee61066ae89d4efd1782a30b6235e0e0548 2021-07-05 17:14:18 +08:00
i-robot 2e90ba92b9 !3 同步739736a13b52b3203c116ea551f82c78aefe9bee
Merge pull request !3 from 张昱杰/master
2021-06-26 02:30:51 +00:00
ascendzyj dfb77c9348 同步739736a13b52b3203c116ea551f82c78aefe9bee 2021-06-26 09:52:46 +08:00
fenghaolin eca80895e7 添加CRNN文档 2021-06-26 09:11:03 +08:00
i-robot 30722c29f5 !1 [Task]补充CONTRIBUTING.zh.md文件
Merge pull request !1 from fenghaolin/master
2021-06-25 06:44:06 +00:00
fenghaolin e0003631b5 添加CONTRIBUTING.zh.md 2021-06-25 08:35:53 +08:00
ascendzyj a83ecb1f7f init repo pytorch-develop of f14e649790d60cc88e60460743b0038cc00346c9 2021-06-24 16:41:42 +08:00
张昱杰 b2b33bd531 Initial commit 2021-06-24 08:13:55 +00:00
4082 changed files with 421356 additions and 535631 deletions
-7
View File
@@ -1,7 +0,0 @@
# Python dependencies required for unit tests
mypy==1.9.0
# Pin MyPy version because new errors are likely to appear with each release
#Description: linter
#Pinned versions: 1.9.0
#test that import: test_typing.py, test_type_hints.py
-127
View File
@@ -1,127 +0,0 @@
---
AccessModifierOffset: -1
AlignAfterOpenBracket: AlwaysBreak
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
AlignEscapedNewlinesLeft: true
AlignOperands: false
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Empty
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: true
AlwaysBreakTemplateDeclarations: true
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
BeforeCatch: false
BeforeElse: false
IndentBraces: false
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Attach
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 80
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: false
DisableFormat: false
ForEachMacros:
- FOR_EACH_RANGE
- FOR_EACH
IncludeCategories:
- Regex: '^<.*\.h(pp)?>'
Priority: 1
- Regex: '^<.*'
Priority: 2
- Regex: '.*'
Priority: 3
IndentCaseLabels: true
IndentWidth: 2
IndentWrappedFunctionNames: false
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
Macros:
- >-
PyObject_HEAD_INIT(type)={
/* this is not exactly match with PyObject_HEAD_INIT in Python source code
* but it is enough for clang-format */
{ 0xFFFFFFFF },
(type)
},
- >-
PyVarObject_HEAD_INIT(type, size)={
{
/* manually expand PyObject_HEAD_INIT(type) above
* because clang-format do not support recursive expansion */
{ 0xFFFFFFFF },
(type)
},
(size)
},
MaxEmptyLinesToKeep: 1
NamespaceIndentation: None
PenaltyBreakBeforeFirstCallParameter: 1
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 2000000
PointerAlignment: Left
ReflowComments: true
SortIncludes: true
SpaceAfterCStyleCast: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++17
StatementMacros:
- C10_DEFINE_bool
- C10_DEFINE_int
- C10_DEFINE_int32
- C10_DEFINE_int64
- C10_DEFINE_string
- C10_DEFINE_REGISTRY_WITHOUT_WARNING
- C10_REGISTER_CREATOR
- DEFINE_BINARY
- PyObject_HEAD
- PyObject_VAR_HEAD
- PyException_HEAD
- TORCH_DECLARE_bool
TabWidth: 8
UseTab: Never
---
Language: ObjC
ColumnLimit: 120
AlignAfterOpenBracket: Align
IndentWidth: 2
ObjCBlockIndentWidth: 2
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: false
...
-81
View File
@@ -1,81 +0,0 @@
---
# NOTE there must be no spaces before the '-', so put the comma last.
# The check bugprone-unchecked-optional-access is also turned on.
# Note that it can cause clang-tidy to hang randomly. The tracking issue
# can be found at https://github.com/llvm/llvm-project/issues/69369.
# When that happens, we can disable it on the problematic code by NOLINT.
InheritParentConfig: true
Checks: '
bugprone-*,
-bugprone-easily-swappable-parameters,
-bugprone-forward-declaration-namespace,
-bugprone-macro-parentheses,
-bugprone-lambda-function-name,
-bugprone-reserved-identifier,
-bugprone-return-const-ref-from-parameter,
-bugprone-swapped-arguments,
clang-analyzer-core.*,
clang-analyzer-cplusplus.*,
clang-analyzer-nullability.*,
clang-analyzer-deadcode.*,
clang-diagnostic-missing-prototypes,
cppcoreguidelines-*,
-cppcoreguidelines-avoid-do-while,
-cppcoreguidelines-avoid-magic-numbers,
-cppcoreguidelines-avoid-non-const-global-variables,
-cppcoreguidelines-interfaces-global-init,
-cppcoreguidelines-macro-usage,
-cppcoreguidelines-macro-to-enum,
-cppcoreguidelines-owning-memory,
-cppcoreguidelines-pro-bounds-array-to-pointer-decay,
-cppcoreguidelines-pro-bounds-constant-array-index,
-cppcoreguidelines-pro-bounds-pointer-arithmetic,
-cppcoreguidelines-pro-type-cstyle-cast,
-cppcoreguidelines-pro-type-reinterpret-cast,
-cppcoreguidelines-pro-type-static-cast-downcast,
-cppcoreguidelines-pro-type-union-access,
-cppcoreguidelines-pro-type-vararg,
-cppcoreguidelines-non-private-member-variables-in-classes,
-facebook-hte-RelativeInclude,
hicpp-exception-baseclass,
hicpp-avoid-goto,
misc-*,
-misc-confusable-identifiers,
-misc-const-correctness,
-misc-include-cleaner,
-misc-use-anonymous-namespace,
-misc-unused-parameters,
-misc-no-recursion,
-misc-non-private-member-variables-in-classes,
-misc-unused-using-decls,
modernize-*,
-modernize-macro-to-enum,
-modernize-return-braced-init-list,
-modernize-use-auto,
-modernize-use-using,
-modernize-use-trailing-return-type,
-modernize-use-nodiscard,
performance-*,
-performance-enum-size,
readability-container-size-empty,
readability-delete-null-pointer,
readability-duplicate-include,
readability-named-parameter,
readability-misplaced-array-index,
readability-redundant*,
readability-simplify-subscript-expr,
readability-static-definition-in-anonymous-namespace
readability-string-compare,
-readability-redundant-access-specifiers,
-readability-redundant-control-flow,
-readability-redundant-inline-specifier,
'
HeaderFilterRegex: '^(aten/|c10/|torch/).*$'
WarningsAsErrors: '*'
LineFilter:
- name: '/usr/include/.*'
CheckOptions:
cppcoreguidelines-special-member-functions.AllowSoleDefaultDtor: true
cppcoreguidelines-special-member-functions.AllowImplicitlyDeletedCopyOrMove: true
misc-header-include-cycle.IgnoredFilesList: 'format.h;ivalue.h;custom_class.h;Dict.h;List.h;IListRef.h'
...
-1
View File
@@ -1 +0,0 @@
filter=-convention/filename,-linelength,-package/consistency,-readability/logic,-readability/mixedcase,-readability/wonkycase,-syntax,-whitespace/eol,+whitespace/extra,-whitespace/indent,-whitespace/mismatch,-whitespace/newline,-whitespace/tabs
-36
View File
@@ -1,36 +0,0 @@
root = true
[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
# Python
[*.{py,pyi,py.in,pyi.in}]
indent_style = space
indent_size = 4
# C/C++/CUDA
[*.{cpp,hpp,cxx,cc,c,h,cu,cuh}]
indent_style = space
indent_size = 2
# Objective-C
[*.{mm,m,M}]
indent_style = space
indent_size = 2
# Clang tools
[.clang-{format,tidy}]
indent_style = space
indent_size = 2
# Make
[Makefile]
indent_style = tab
# Batch file
[*.bat]
indent_style = space
indent_size = 2
end_of_line = crlf
-53
View File
@@ -1,53 +0,0 @@
[flake8]
# NOTE: **Mirror any changes** to this file the [tool.ruff] config in pyproject.toml
# before we can fully move to use ruff
enable-extensions = G
select = B,C,E,F,G,P,SIM1,SIM911,T4,W,B9
max-line-length = 120
# C408 ignored because we like the dict keyword argument syntax
# E501 is not flexible enough, we're using B950 instead
ignore =
E203,E305,E402,E501,E704,E741,F405,F841,F999,W503,W504,C408,E302,W291,E303,F824,
# shebang has extra meaning in fbcode lints, so I think it's not worth trying
# to line this up with executable bit
EXE001,
# these ignores are from flake8-bugbear; please fix!
B007,B008,B017,B019,B023,B028,B903,B905,B906,B907,B908,B910
# these ignores are from flake8-simplify. please fix or ignore with commented reason
SIM105,SIM108,SIM110,SIM111,SIM113,SIM114,SIM115,SIM116,SIM117,SIM118,SIM119,SIM12,
# SIM104 is already covered by pyupgrade ruff
SIM104,
# flake8-simplify code styles
SIM102,SIM103,SIM106,SIM112
per-file-ignores =
__init__.py: F401
test/**: F821
test/**/__init__.py: F401,F821
torch/utils/cpp_extension.py: B950
torchgen/api/types/__init__.py: F401,F403
torchgen/executorch/api/types/__init__.py: F401,F403
test/dynamo/test_higher_order_ops.py: B950
test/dynamo/test_error_messages.py: B950
torch/testing/_internal/dynamo_test_failures.py: B950
torch/__init__.py: F401
torch/_prims/__init__.py: F401
optional-ascii-coding = True
exclude =
./.git,
./build_test_custom_build,
./build,
./caffe2,
./docs/caffe2,
./docs/cpp/src,
./docs/src,
./functorch/docs,
./functorch/examples,
./functorch/docs/source/tutorials,
./torch/testing/_internal/py312_intrinsics.py
./scripts,
./test/generated_type_hints_smoketest.py,
./third_party,
./torch/include,
./torch/lib,
./venv,
*.pyi
-34
View File
@@ -1,34 +0,0 @@
<!--
PR描述模板更新日期:20260203
-->
# 【合入来源】
> (如有)请关联需求文档/issue链接
- [ ] 需求
- [ ] 问题单
- [ ] issue/工单
- [ ] 重构优化
- [ ] 资料更新
# 【修改方案】
> 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\
> 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)
# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”
# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”
# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图
# 【CheckList】
> PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]
- [ ] 代码注释完备,正确记录错误日志
- [ ] 代码实现进行了返回值、空指针等校验
- [ ] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [ ] PR持续集成流水线(CI)执行通过,代码检查无异常
@@ -1,51 +0,0 @@
name: Fetch and Rebase
description: Fetch and rebase for repository
inputs:
repo_path:
description: the path the repository locate on
required: true
remote_branch:
description: the branch rebased from
required: true
loop:
description: loop times when fails
required: true
runs:
using: composite
steps:
- name: Fetch and rebase
env:
REPO_PATH: ${{ inputs.repo_path }}
REMOTE_BRANCH: ${{ inputs.remote_branch }}
LOOP: ${{ inputs.loop }}
shell: bash
run: |
set +e
COUNT=0
for i in $(seq 1 ${LOOP})
do
pushd ${REPO_PATH} &&
git fetch --all &&
git rebase ${REMOTE_BRANCH} &&
git submodule sync &&
git submodule update --init --recursive &&
git reset --hard HEAD &&
git clean -dfx &&
git submodule foreach git reset --hard HEAD &&
git submodule foreach git clean -dfx &&
popd
if [[ $? -ne 0 ]]
then
let COUNT++
else
break
fi
done
[[ ${COUNT} -lt ${LOOP} ]] && true || false
-61
View File
@@ -1,61 +0,0 @@
name: Build and Test
on:
workflow_call:
inputs:
runner:
required: true
type: string
description: The runner selected to run on
devices:
required: true
type: string
description: The devices selected to run on
image:
required: true
type: string
description: The docker iamge which will be loaded
jobs:
build-and-test:
runs-on: ${{ inputs.runner }}
defaults:
run:
shell: bash
container:
image: ${{ inputs.image }}
env:
HOME: /root
volumes:
- /usr/local/dcmi:/usr/local/dcmi
- /usr/local/bin/npu-smi:/usr/local/bin/npu-smi
- /usr/local/Ascend/driver/lib64/:/usr/local/Ascend/driver/lib64/
- /usr/local/Ascend/driver/version.info:/usr/local/Ascend/driver/version.info
- /root/codes/:/root/codes
options: --network host ${{ inputs.devices }} --device /dev/davinci_manager --device /dev/devmm_svm --device /dev/hisi_hdc
steps:
- name: Set environment
run: |
source /root/.bashrc && conda activate torch_npu
- name: Prepare the codes
run: |
\cp -rf /root/codes/ /root/build
- name: Compile torch
working-directory: /root/build/pytorch/pytorch
run: |
pip3 install -r requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple
export _GLIBCXX_USE_CXX11_ABI=1
export USE_CUDA=0
export USE_XNNPACK=0
python setup.py develop
- name: Compile and install torch_npu
working-directory: /root/build/npu/pytorch
run: |
pip3 install -r requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple
bash ci/build.sh --python=3.8
pip3 install dist/torch_npu*.whl
- name: Do the test
working-directory: /root/build
run: |
pip3 install -r npu/pytorch/test/requirements.txt -i https://mirrors.huaweicloud.com/repository/pypi/simple --no-deps
python npu/pytorch/ci/access_control_test.py
-30
View File
@@ -1,30 +0,0 @@
name: Fetch and Rebase
on:
workflow_call:
inputs:
runner:
required: true
type: string
description: The runner selected to run on
loop:
required: true
type: string
description: Loop time when fails
jobs:
fetch-and-rebase:
runs-on: ${{ inputs.runner }}
steps:
- name: Pull latest codes for torch
uses: ascend/pytorch/.github/actions/fetch-and-rebase@master
with:
repo_path: /root/codes/pytorch/pytorch
remote_branch: upstream/main
loop: ${{ inputs.loop }}
- name: Pull latest codes for torch_npu
uses: ascend/pytorch/.github/actions/fetch-and-rebase@master
with:
repo_path: /root/codes/npu/pytorch
remote_branch: upstream/master
loop: ${{ inputs.loop }}
-37
View File
@@ -1,37 +0,0 @@
name: Ascend NPU(Manual)
on:
workflow_dispatch:
inputs:
runner:
required: true
type: string
default: 'self-hosted'
description: The runner selected to run on
devices:
required: true
type: string
default: '--device /dev/davinci6'
description: The devices selected to run on
image:
required: true
type: string
default: 'ascendai/cann:7.1-openeuler2203sp2'
description: The docker iamge which will be loaded
jobs:
linux-py3_8-fetch-and-rebase:
name: linux-py3_8-7.0.RC1.alpha005
uses: ./.github/workflows/_fetch_and_rebase.yml
with:
runner: ${{ inputs.runner }}
loop: 10
linux-py3_8-build-and-test:
name: linux-py3_8-7.0.RC1.alpha005
uses: ./.github/workflows/_build-and-test.yml
needs: linux-py3_8-fetch-and-rebase
with:
runner: ${{ inputs.runner }}
devices: ${{ inputs.devices }}
image: ${{ inputs.image }}
-26
View File
@@ -1,26 +0,0 @@
# Note:
# Same runner only needs one job named like .*fetch-and-rebase
name: Ascend NPU
on:
schedule:
- cron: '0 12 * * *'
workflow_dispatch:
jobs:
linux-py3_8-fetch-and-rebase:
name: linux-py3_8-7.0.RC1.alpha005
uses: ./.github/workflows/_fetch_and_rebase.yml
with:
runner: self-hosted
loop: 10
linux-py3_8-build-and-test:
name: linux-py3_8-7.0.RC1.alpha005
uses: ./.github/workflows/_build-and-test.yml
needs: linux-py3_8-fetch-and-rebase
with:
runner: self-hosted
devices: --device /dev/davinci6
image: ascendai/cann:7.1-openeuler2203sp2
-204
View File
@@ -1,204 +0,0 @@
# READ THIS BEFORE YOU REFACTOR ME
#
# setup.py uses the list of patterns in this file to decide
# what to delete, but it's not 100% sound. So, for example,
# if you delete aten/build/ because it's redundant with build/,
# aten/build/ will stop being cleaned. So be careful when
# refactoring this file!
## PyTorch
.coverage
coverage.xml
.dmypy.json
.gradle
.hypothesis
.mypy_cache
*/*.so*
*/**/__pycache__
*/**/*.dylib*
*/**/*.pyd
*/**/*.so*
log
# Root level file used in CI to specify certain env configs.
# E.g., see .circleci/config.yaml
env
.circleci/scripts/COMMIT_MSG
# IPython notebook checkpoints
.ipynb_checkpoints
# Editor temporaries
*.swn
*.swo
*.swp
*.swm
*~
# macOS dir files
.DS_Store
# Ninja files
.ninja_deps
.ninja_log
compile_commands.json
*.egg-info/
## General
# Compiled Object files
*.slo
*.lo
*.o
*.cuo
*.obj
# Compiled Dynamic libraries
*.so
*.dylib
*.dll
# Compiled Static libraries
*.lai
*.la
*.a
*.lib
# Compiled protocol buffers
*.pb.h
*.pb.cc
*_pb2.py
# Compiled python
*.pyc
*.pyd
# Compiled MATLAB
*.mex*
# IPython notebook checkpoints
.ipynb_checkpoints
# Editor temporaries
*.swn
*.swo
*.swp
*~
# Sublime Text settings
*.sublime-workspace
*.sublime-project
# Eclipse Project settings
*.*project
.settings
# QtCreator files
*.user
# PyCharm files
.idea
# OSX dir files
.DS_Store
# GDB history
.gdb_history
## Caffe2
# build, distribute, and bins (+ python proto bindings)
build
build_host_protoc
build_android
build_ios
/build_*
.build_debug/*
.build_release/*
.build_profile/*
distribute/*
*.testbin
*.bin
cmake_build
.cmake_build
gen
.setuptools-cmake-build
.pytest_cache
aten/build/*
dist
# Bram
plsdontbreak
# Generated documentation
docs/_site
docs/gathered
_site
doxygen
docs/dev
# LevelDB files
*.sst
*.ldb
LOCK
CURRENT
MANIFEST-*
# generated version file
caffe2/version.py
# setup.py intermediates
.eggs
caffe2.egg-info
# Atom/Watchman required file
.watchmanconfig
# Files generated by CLion
cmake-build-debug
# BEGIN NOT-CLEAN-FILES (setup.py handles this marker. Do not change.)
#
# Below files are not deleted by "setup.py clean".
# Visual Studio Code files
.vscode
.vs
# YouCompleteMe config file
.ycm_extra_conf.py
# Files generated when a patch is rejected
*.orig
*.rej
# Files generated by ctags
CTAGS
GTAGS
GRTAGS
GSYMS
GPATH
tags
TAGS
# ccls file
.ccls-cache/
# clang-format storage location used by apply_clang_format.py
.clang-format-bin
# clangd background index
.clangd/
.cache/
# 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
torch_npu/_op_plugin_docs.py
-27
View File
@@ -1,27 +0,0 @@
[submodule "third_party/op-plugin"]
path = third_party/op-plugin
url = https://gitcode.com/ascend/op-plugin.git
ignore = dirty
[submodule "third_party/googletest"]
path = third_party/googletest
url = https://gitee.com/mirrors/googletest.git
[submodule "third_party/torchair/torchair"]
path = third_party/torchair/torchair
url = https://gitcode.com/ascend/torchair.git
[submodule "third_party/Tensorpipe"]
path = third_party/Tensorpipe
url = https://gitcode.com/ascend/Tensorpipe.git
[submodule "third_party/fmt"]
path = third_party/fmt
url = https://gitee.com/mirrors/fmt.git
[submodule "third_party/nlohmann"]
path = third_party/nlohmann
url = https://gitcode.com/GitHub_Trending/js/json
[submodule "third_party/torch-mlir"]
path = third_party/torch-mlir
url = https://gitee.com/mirrors_llvm/torch-mlir.git
update = none
[submodule "third_party/dvm/dvm"]
path = third_party/dvm/dvm
url = https://gitcode.com/mindspore/dvm.git
branch = r2.9
-1806
View File
File diff suppressed because it is too large Load Diff
-380
View File
@@ -1,380 +0,0 @@
cmake_minimum_required(VERSION 3.18 FATAL_ERROR)
find_program(CCACHE ccache)
if(${CCACHE} STREQUAL "CCACHE-NOTFOUND")
message(STATUS "Compile without ccache")
else()
set(CMAKE_C_COMPILER_LAUNCHER ${CCACHE} CACHE PATH "cache Compiler")
set(CMAKE_CXX_COMPILER_LAUNCHER ${CCACHE} CACHE PATH "cache Compiler")
message(STATUS "CMAKE_C_COMPILER_LAUNCHER:${CMAKE_C_COMPILER_LAUNCHER}")
message(STATUS "CMAKE_CXX_COMPILER_LAUNCHER:${CMAKE_CXX_COMPILER_LAUNCHER}")
endif()
project(TORCHNPU CXX C)
add_compile_options(-fmacro-prefix-map=${CMAKE_SOURCE_DIR}/=)
set(LINUX TRUE)
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)
set(CMAKE_SKIP_BUILD_RPATH FALSE)
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH "${RPATH_VALUE}/lib/:${RPATH_VALUE}/")
set(CMAKE_INSTALL_RPATH_USE_LINK_PATH FALSE)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${TORCHNPU_INSTALL_LIBDIR})
SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "-O2 -g")
SET(CMAKE_CXX_FLAGS_RELEASE "-O2")
SET(CMAKE_CXX_FLAGS_DEBUG "-O0 -g")
# LTO&PGO optimization in compile option
SET(IF_APPEND FALSE)
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
SET(APPEND_FLAGS "-fGNU-compatibility -fuse-ld=lld -Wno-non-pod-varargs")
if (DEFINED ENABLE_LTO)
SET(IF_APPEND TRUE)
SET(APPEND_FLAGS "${APPEND_FLAGS} -flto=thin")
endif()
if (DEFINED PGO_MODE)
SET(IF_APPEND TRUE)
if (PGO_MODE EQUAL 1)
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-generate")
elseif (PGO_MODE EQUAL 2)
SET(APPEND_FLAGS "${APPEND_FLAGS} -fprofile-use=${CMAKE_CURRENT_SOURCE_DIR}/default.profdata")
endif()
endif()
else()
if (DEFINED ENABLE_LTO)
message(FATAL_ERROR "Currently, LTO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
endif()
if (DEFINED PGO_MODE)
message(FATAL_ERROR "Currently, PGO auto build is not supported in ${CMAKE_CXX_COMPILER_ID}")
endif()
endif()
if (IF_APPEND)
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} ${APPEND_FLAGS}")
endif()
# check and set CMAKE_CXX_STANDARD
string(FIND "${CMAKE_CXX_FLAGS}" "-std=c++" env_cxx_standard)
if(env_cxx_standard GREATER -1)
message(
WARNING "C++ standard version definition detected in environment variable."
"PyTorch requires -std=c++17. Please remove -std=c++ settings in your environment.")
endif()
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_EXTENSIONS OFF)
set(TORCHNPU_ROOT "${PROJECT_SOURCE_DIR}/torch_npu/csrc")
set(TORCHNPU_THIRD_PARTY_ROOT "${PROJECT_SOURCE_DIR}/third_party")
set(Torch_DIR ${PYTORCH_INSTALL_DIR}/share/cmake/Torch)
FIND_PACKAGE(Torch REQUIRED)
set(LINUX TRUE)
set(CMAKE_INSTALL_MESSAGE NEVER)
#set(CMAKE_VERBOSE_MAKEFILE ON)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
# Define build type
IF(CMAKE_BUILD_TYPE MATCHES Debug)
message("Debug build.")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_DEBUG")
ELSEIF(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo)
message("RelWithDebInfo build")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNDEBUG")
ELSE()
message("Release build.")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DNDEBUG")
ENDIF()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-narrowing")
# Eigen fails to build with some versions, so convert this to a warning
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wextra")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-field-initializers")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-type-limits")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-array-bounds")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-pragmas")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-sign-compare")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-function")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-result")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-strict-overflow")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-strict-aliasing")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=deprecated-declarations")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-ignored-qualifiers")
if (CMAKE_COMPILER_IS_GNUCXX AND NOT (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 7.0.0))
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-stringop-overflow")
endif()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=pedantic")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=redundant-decls")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-error=old-style-cast")
# These flags are not available in GCC-4.8.5. Set only when using clang.
if ("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-invalid-partial-specialization")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-typedef-redefinition")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-warning-option")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-private-field")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-inconsistent-missing-override")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-aligned-allocation-unavailable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-c++17-extensions")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-constexpr-not-const")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-missing-braces")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Qunused-arguments")
if (${COLORIZE_OUTPUT})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fcolor-diagnostics")
endif()
endif()
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 4.9)
if (${COLORIZE_OUTPUT})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fdiagnostics-color=always")
endif()
endif()
if ((APPLE AND (NOT ("${CLANG_VERSION_STRING}" VERSION_LESS "9.0")))
OR (CMAKE_COMPILER_IS_GNUCXX
AND (CMAKE_CXX_COMPILER_VERSION VERSION_GREATER 7.0 AND NOT APPLE)))
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -faligned-new")
endif()
if (WERROR)
check_cxx_compiler_flag("-Werror" COMPILER_SUPPORT_WERROR)
if (NOT COMPILER_SUPPORT_WERROR)
set(WERROR FALSE)
else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror")
endif()
endif(WERROR)
if (NOT APPLE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-but-set-variable")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-uninitialized")
endif()
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -O0")
set(CMAKE_LINKER_FLAGS_DEBUG "${CMAKE_STATIC_LINKER_FLAGS_DEBUG} -fno-omit-frame-pointer -O0")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-math-errno")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-trapping-math")
set(CMAKE_CXX_COVERAGE $ENV{CALCULATE_CXX_COVERAGE})
if (CMAKE_BUILD_TYPE MATCHES Debug)
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
elseif (CMAKE_CXX_COVERAGE STREQUAL "1")
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fprofile-arcs -ftest-coverage -fPIE -pie ${CXXFLAGS}")
else()
set(CMAKE_C_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_C_FLAGS}")
set(CMAKE_CXX_FLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CMAKE_CXX_FLAGS}")
set(CXXFLAGS "-fstack-protector-all -Wl,-z,relro,-z,now,-z,noexecstack -fPIE -pie ${CXXFLAGS}")
endif()
if (NOT DEFINED GLIBCXX_USE_CXX11_ABI)
set(GLIBCXX_USE_CXX11_ABI 0)
endif()
message(STATUS "Determined _GLIBCXX_USE_CXX11_ABI=${GLIBCXX_USE_CXX11_ABI}")
set(_GLIBCXX_USE_CXX11_ABI ${GLIBCXX_USE_CXX11_ABI})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D_GLIBCXX_USE_CXX11_ABI=${GLIBCXX_USE_CXX11_ABI}")
if (${GLIBCXX_USE_CXX11_ABI} EQUAL 0)
set(CMAKE_CXX_FLAGS "-fabi-version=11 ${CMAKE_CXX_FLAGS}")
else()
set(CXX_STANDARD_REQUIRED ON)
if (DEFINED ABI_VERSION)
set(CMAKE_CXX_FLAGS "-fabi-version=${ABI_VERSION} ${CMAKE_CXX_FLAGS}")
endif()
endif()
if (DEFINED BUILD_LIBTORCH)
add_compile_definitions(BUILD_LIBTORCH)
endif()
include_directories(${PROJECT_SOURCE_DIR})
include_directories(${PROJECT_SOURCE_DIR}/torch_npu/csrc/aten)
include_directories(${PROJECT_SOURCE_DIR}/torch_npu/csrc/inductor)
include_directories(${PROJECT_SOURCE_DIR}/third_party/hccl/inc)
include_directories(${PROJECT_SOURCE_DIR}/third_party/acl/inc)
include_directories(${PROJECT_SOURCE_DIR}/third_party/Tensorpipe)
include_directories(${PROJECT_SOURCE_DIR}/third_party/nlohmann/include)
# Set installed PyTorch dir
if(DEFINED PYTORCH_INSTALL_DIR)
include_directories(${PYTORCH_INSTALL_DIR}/include)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/api/include)
include_directories(${PYTORCH_INSTALL_DIR}/include/torch/csrc/distributed)
else()
message(FATAL_ERROR "Cannot find installed PyTorch directory")
endif()
# Set Python include dir
if(DEFINED PYTHON_INCLUDE_DIR)
include_directories(${PYTHON_INCLUDE_DIR})
else()
message(FATAL_ERROR "Cannot find installed Python head file directory")
endif()
# sources
set(ATEN_SRCS)
set(CORE_SRCS)
set(FRAMEWORK_SRCS)
set(LOGGING_SRCS)
set(INDUCTOR_SRCS)
set(DIST_SRCS)
if (NOT DEFINED BUILD_LIBTORCH)
set(FLOP_SRCS)
set(NPU_SRCS)
set(PROF_SRCS)
set(IPC_SRCS)
set(UTILS_SRCS)
set(SAN_SRCS)
set(AFD_SRCS)
endif()
if (DEFINED BUILD_LIBTORCH)
set(NPU_CPP_LIBS_SRCS)
endif()
add_subdirectory(${TORCHNPU_ROOT}/aten)
add_subdirectory(${TORCHNPU_ROOT}/core)
add_subdirectory(${TORCHNPU_ROOT}/framework)
add_subdirectory(${TORCHNPU_ROOT}/flopcount)
add_subdirectory(${TORCHNPU_ROOT}/logging)
add_subdirectory(${TORCHNPU_ROOT}/custom_dtype)
add_subdirectory(${TORCHNPU_ROOT}/inductor)
add_subdirectory(${TORCHNPU_ROOT}/distributed)
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/npu)
add_subdirectory(${TORCHNPU_ROOT}/profiler)
add_subdirectory(${TORCHNPU_ROOT}/ipc)
add_subdirectory(${TORCHNPU_ROOT}/utils)
add_subdirectory(${TORCHNPU_ROOT}/sanitizer)
add_subdirectory(${TORCHNPU_ROOT}/afd)
endif()
if (DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/libs)
endif()
set(OPS_PLUGIN_SRCS)
# Add subdirectory of op-plugin
include_directories(${PROJECT_SOURCE_DIR}/third_party/op-plugin)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/op-plugin/op_plugin)
if (DEFINED BUILD_TENSORPIPE)
add_definitions(-DUSE_RPC_FRAMEWORK)
set(BUILD_SHARED_LIBS ON)
if(CMAKE_VERSION VERSION_GREATER_EQUAL "4.0.0")
message(WARNING "tensorpipe forces CMake compatibility")
set(CMAKE_POLICY_VERSION_MINIMUM 3.5)
endif()
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/Tensorpipe)
if(CMAKE_VERSION VERSION_GREATER_EQUAL "4.0.0")
unset(CMAKE_POLICY_VERSION_MINIMUM)
endif()
set(BUILD_SHARED_LIBS OFF)
endif()
if (DEFINED BUILD_LIBTORCH)
set(CPP_SRCS ${ATEN_SRCS} ${INDUCTOR_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${FRAMEWORK_SRCS} ${LOGGING_SRCS} ${NPU_CPP_LIBS_SRCS} )
else()
# Compile code with pybind11
set(CPP_SRCS ${ATEN_SRCS} ${INDUCTOR_SRCS} ${CORE_SRCS} ${OPS_PLUGIN_SRCS} ${DIST_SRCS} ${FLOP_SRCS} ${CUS_DTYPE_SRCS} ${LOGGING_SRCS} ${FRAMEWORK_SRCS} ${NPU_SRCS} ${PROF_SRCS} ${IPC_SRCS} ${UTILS_SRCS} ${SAN_SRCS} ${AFD_SRCS})
endif()
add_library(${PLUGIN_NAME} SHARED ${CPP_SRCS})
include(CheckCXXCompilerFlag)
check_cxx_compiler_flag("-fvisibility=hidden" COMPILER_SUPPORTS_HIDDEN_VISIBILITY)
if(${COMPILER_SUPPORTS_HIDDEN_VISIBILITY})
target_compile_options(${PLUGIN_NAME} PRIVATE "-fvisibility=hidden")
endif()
target_link_options(${PLUGIN_NAME} PRIVATE "-Wl,-Bsymbolic-functions,--no-as-needed")
if (DEFINED BUILD_TORCHAIR)
add_subdirectory(${TORCHNPU_THIRD_PARTY_ROOT}/torchair)
add_dependencies(${PLUGIN_NAME} copy_torchair_pyfiles)
endif()
add_subdirectory(${TORCHNPU_THIRD_PARTY_ROOT}/fmt EXCLUDE_FROM_ALL)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/dvm)
add_dependencies(${PLUGIN_NAME} dvm_build)
target_link_libraries(${PLUGIN_NAME} PRIVATE ${PROJECT_SOURCE_DIR}/third_party/dvm/dvm/libdvm.a)
link_directories(${PYTORCH_INSTALL_DIR}/lib)
link_directories(${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libhccl.so)
if (NOT DEFINED BUILD_LIBTORCH)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PYTORCH_INSTALL_DIR}/lib/libtorch_python.so)
endif()
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libascendcl.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libacl_op_compiler.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libge_runner.so)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${TORCHNPU_THIRD_PARTY_ROOT}/acl/libs/libgraph.so)
if (DEFINED BUILD_TENSORPIPE)
target_link_libraries(${PLUGIN_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/build/packages/torch_npu/lib/libtensorpipe.so)
endif()
target_link_libraries(${PLUGIN_NAME} PUBLIC torch torch_cpu c10 fmt::fmt-header-only)
if (NOT DEFINED BUILD_LIBTORCH)
set(ATEN_THREADING "OMP" CACHE STRING "ATen parallel backend")
message(STATUS "Using ATen parallel backend: ${ATEN_THREADING}")
if ("${ATEN_THREADING}" STREQUAL "OMP")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_OPENMP=1")
elseif ("${ATEN_THREADING}" STREQUAL "NATIVE")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE=1")
elseif ("${ATEN_THREADING}" STREQUAL "TBB")
target_compile_definitions(${PLUGIN_NAME} PUBLIC "-DAT_PARALLEL_NATIVE_TBB=1")
else()
message(FATAL_ERROR "Unknown ATen parallel backend: ${ATEN_THREADING}")
endif()
include(GNUInstallDirs)
target_compile_options(${PLUGIN_NAME} PRIVATE "-DC10_BUILD_MAIN_LIB")
install(TARGETS ${PLUGIN_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR})
endif()
if (NOT DEFINED BUILD_LIBTORCH)
add_subdirectory(${TORCHNPU_ROOT}/toolkit)
target_link_libraries(${PLUGIN_NAME} PUBLIC npu_profiler)
endif()
if (DEFINED BUILD_GTEST)
enable_testing()
SET(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/build/gtest)
add_subdirectory(${PROJECT_SOURCE_DIR}/third_party/googletest)
include_directories(${PROJECT_SOURCE_DIR}/third_party/googletest/googletest/include)
set(TORCH_API_TEST_SOURCES)
add_subdirectory(${PROJECT_SOURCE_DIR}/test/cpp/api)
add_executable(test_api ${TORCH_API_TEST_SOURCES})
target_link_libraries(test_api PUBLIC torch_npu)
target_link_libraries(test_api PUBLIC gtest_main gtest)
endif()
if (DEFINED BUILD_LIBTORCH)
configure_file(
${PROJECT_SOURCE_DIR}/cmake/Torch_npuConfig.cmake.in
${PROJECT_SOURCE_DIR}/build/Torch_npuConfig.cmake
@ONLY)
endif()
-205
View File
@@ -1,205 +0,0 @@
# PyTorch贡献指南
感谢您考虑为 PyTorch做出贡献!我们欢迎任何形式的贡献,包括错误修复、功能增强、文档改进等,甚至只是反馈。无论您是经验丰富的开发者还是第一次参与开源项目,您的帮助都是非常宝贵的。
您可以通过多种方式支持本项目:
- 通过[Issues](https://gitcode.com/Ascend/pytorch/issues)反馈问题。
- 建议或实现新功能。
- 改进或扩展文档。
- 审查Pull Request并协助其他贡献者。
- 传播项目:在博客文章、社交媒体上分享PyTorch,或给仓库点个⭐。
## 寻找可贡献的问题
您可以通过查看[Issues列表](https://gitcode.com/Ascend/pytorch/issues)了解项目的发展计划和路线图。
## 贡献流程
- [贡献者许可协议](#贡献者许可协议)
- [开发与测试](#开发与测试)
### 贡献者许可协议
在您第一次向 PyTorch 社区提交代码之前,需要签署 CLA。
对于个人贡献者,详细信息请参考[ICLA 在线文档](https://www.mindspore.cn/icla)。
### 开发与测试
1. 先在GitCode平台点击仓库右上角"Fork"按钮,将仓库克隆到个人账户
2. 克隆到本地:
```bash
git clone https://gitcode.com/<your-username>/pytorch.git
cd pytorch
```
3. 在个人仓库进行代码开发
代码开发请遵循 **[代码规范](#代码规范)**
4. 代码测试
参见 **[代码测试](https://gitcode.com/Ascend/pytorch/blob/master/test/README.md)**
5. **[门禁异常处理](#门禁异常处理)**
6. **[提交Pull Request](#提交Pull-Request)**
7. **[报告问题](#报告问题)**
#### 代码规范
请遵循这些风格,以使 PyTorch 易于开发、审查和维护。
- 编码指南
请在PyTorch社区使用规统一的编码分格,python建议的编码风格是[PEP 8编码样式](https://pep8.org/),C++编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。执行代码检查,可参照[本地静态检查](#本地静态检查)。
- 单元测试指南
请在PyTorch社区使用统一的单元测试风格, Python中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),C++单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
- 重构指南
我们鼓励开发人员重构我们的代码以消除[代码异味](https://en.wikipedia.org/wiki/Code_smell)。所有的代码都应该符合编码风格和测试风格的需求,重构代码也不例外。当您收到警告时,您必须重构要合并的代码。
#### 门禁异常处理
门禁异常主要包含如下几种,请根据相关提示解决异常问题。
- 编译异常
请检查代码编译失败的原因,解决问题后重新编译即可。
- 静态检查异常(代码Bug、代码漏洞、代码异味)
请依照提示查找代码中的异常并解决。
- UT测试未通过
请根据提示,查找测试用例不通过项并检查原因,解决后再测试。
#### 提交Pull Request
1. 本地创建分支。
为了避免多个分支之间的不一致,建议创建新的分支进行开发:
```
git checkout -b {new_branch_name} origin/master
```
以master分支为例,PyTorch可能会根据需要创建版本分支和下游开发分支,请先修复上游的bug。然后就可以随意更改代码了。
2. 将代码推送到远程仓库。
更新代码后,您需要以正式的方式推送更新:
```
git add .
git status # Check the update status
git commit -m "Your commit title"
git commit -s --amend #Add the concrete description of your commit
git push origin {new_branch_name}
```
3. 创建Pull Request
在GitCode上创建Pull Request
根据`.gitcode/PULL_REQUEST_TEMPLATE.md`中的规范模板,完整填写:
- 合入来源
- 修改方案
- 资料变更
- 接口变更
- 功能验证
- CheckList
确认信息完整准确后提交Pull Request,等待代码审查
#### 报告问题
为项目做出贡献的一个好方法是在遇到问题时发送详细报告。我们总是很感激写得很好、彻底的错误报告,并会由此感谢您!
报告问题时,请参考以下格式:
- 您使用的是什么版本的环境 (pytorch、os、python 等)?
- 这是错误报告还是功能请求?
- 什么样的问题,添加标签以在问题仪表板上突出显示。
- 发生了什么?
- 您预计会发生什么?
- 如何重现它?(尽可能最小和精确。)
- 给审稿人的特别说明?
问题咨询:
- 如果您发现一个未解决的问题,而这正是您要解决的问题,请对该问题发表一些评论,告诉其他人您将负责它。
- 如果问题已打开一段时间,建议贡献者在解决该问题之前进行预检查。
- 如果您解决了自己报告的问题,则还需要在关闭该问题之前让其他人知道。
### 本地静态检查
项目使用 [lintrunner](https://github.com/suo/lintrunner) 进行静态检查,支持在本地运行与 CI 完全一致的检查项,
包括 Python 代码风格(Flake8、Ruff、PYFMT)、C++ 格式(ClangFormat、ClangTidy)、拼写检查(Codespell)等。
#### 安装依赖
```bash
# 安装 lintrunner 及 uv(部分 linter 需要)
pip install lintrunner
pip install uv
```
#### 初始化(首次使用或更新时执行一次)
```bash
# 下载 lintrunner 所需的外部二进制工具(clang-format、clang-tidy 等)
lintrunner init
```
#### 执行静态检查
```bash
# 检查当前工作区改动和HEAD提交的文件增量(工作区 + HEAD)
lintrunner
# 仅运行指定检查项
lintrunner --take FLAKE8,RUFF,PYFMT,SPACES,TABS,NEWLINE
# 自动修复可自动修复的问题(formatter 类 linter, 如忽略PYREFLY)
lintrunner --skip PYREFLY -a
# 仅检查当前工作区改动的文件增量
git diff --name-only HEAD | xargs lintrunner
```
> **提示**:`--take` 参数可指定只运行部分检查项,常用项如下:
>
> | 代码 | 说明 |
> |------|------|
> | `FLAKE8` | Python 语法与风格检查 |
> | `RUFF` | Python 快速 lint 与 import 排序 |
> | `PYFMT` | Python 代码格式化(usort + ruff-format) |
> | `CLANGFORMAT` | C++ 代码格式化 |
> | `CLANGTIDY` | C++ 静态分析 |
> | `SPACES` | 行尾空格检查 |
> | `TABS` | Tab 字符检查 |
> | `NEWLINE` | 文件末尾换行检查 |
> | `CODESPELL` | 拼写检查,如果是误报可以将误报词按照字典序添加至 `tools/linter/dictionary.txt` 后再重新检查 |
更多执行命令可参照[lintrunner wiki](https://github.com/pytorch/pytorch/wiki/lintrunner)。
## 社区准则
### 行为准则
我们致力于为所有参与者提供一个友好、安全和包容的环境。参与本项目即表示您同意:
- 尊重不同的观点和经验
- 接受建设性的批评
- 关注对社区最有利的事情
- 对其他社区成员表示同理心
### 沟通渠道
- **Issues**:用于报告Bug、提出功能建议和讨论技术问题
- **Pull Requests**:用于代码审查和讨论具体实现
+227
View File
@@ -0,0 +1,227 @@
# PyTorch贡献指南
- [贡献者许可协议](#贡献者许可协议.md)
- [入门](#入门.md)
- [开发指导](#开发指导.md)
- [测试用例](#测试用例.md)
- [代码风格](#代码风格.md)
- [门禁异常处理](#门禁异常处理.md)
- [Fork-Pull开发模式](#Fork-Pull开发模式.md)
- [报告问题](#报告问题.md)
- [提出PR](#提出PR.md)
<h2 id="贡献者许可协议.md">贡献者许可协议</h2>
在您第一次向 PyTorch 社区提交代码之前,需要签署 CLA。
对于个人贡献者,详细信息请参考[ICLA 在线文档](https://www.mindspore.cn/icla)。
<h2 id="入门.md">入门</h2>
- 在[Gitee](https://gitee.com/ascend/pytorch)上Fork存储库。
- 阅读[README.md](#https://gitee.com/ascend/pytorch/blob/master/README.zh.md)以获取项目信息和构建说明。
<h2 id="开发指导.md">开发指导</h2>
- **[测试用例](#测试用例.md)**
- **[代码风格](#代码风格.md)**
- **[门禁异常处理](#门禁异常处理.md)**
- **[Fork-Pull开发模式](#Fork-Pull开发模式.md)**
- **[报告问题](#报告问题.md)**
- **[提出PR](#提出PR.md)**
<h2 id="测试用例.md">测试用例</h2>
通过具体示例,完成PyTorch的功能测试。
1. 编写测试脚本。
以add运算为例,在“pytorch/test/test\_npu/test\_network\_ops“路径下编写测试脚本文件: test\_add.py。
以下示例仅为一个简单的用例实现,供用户参考。具体测试用例的实现,需要根据运算定义进行完整的覆盖才能保证功能的基本正确。
```
# 引入依赖库
import sys
sys.path.append('..')
import torch
import numpy as np
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
# 定义add测试用例类
class TestAdd(TestCase):
# 定义CPU的add执行函数
def cpu_op_exec(self, input1, input2):
output = torch.add(input1, input2, alpha = 1)
output = output.numpy()
return output
# 定义NPU的add执行函数
def npu_op_exec_new(self, input1, input2):
output = torch.add(input1, input2, alpha = 1)
output = output.to("cpu")
output = output.numpy()
return output
# 定义add对应场景通用函数,该函数中负责场景对应输入数据和对比CPU和NPU返回结果
def add_result(self, shape_format):
for item in shape_format:
cpu_input1, npu_input1 = create_common_tensor(item, 0, 100)
cpu_input2, npu_input2 = create_common_tensor(item, 0, 100)
if cpu_input1.dtype == torch.float16:
cpu_input1 = cpu_input1.to(torch.float32)
cpu_input2 = cpu_input2.to(torch.float32)
cpu_output = self.cpu_op_exec(cpu_input1, cpu_input2)
npu_output = self.npu_op_exec_new(npu_input1, npu_input2)
cpu_output = cpu_output.astype(npu_output.dtype)
self.assertRtolEqual(cpu_output, npu_output)
# 定义具体add场景的测试用例,用例函数需要以test_开头
def test_add_shape_format_fp32_2d(self, device):
format_list = [0, 3, 29]
shape_format = [
[np.float32, i, [5, 256]] for i in format_list
]
self.add_result(shape_format)
instantiate_device_type_tests(TestAdd, globals(), except_for="cpu")
if __name__ == "__main__":
run_tests()
```
2. 设置环境变量。
进入“pytorh/src“路径,并执行env.sh脚本。
```
bash env.sh
```
3. 执行测试用例脚本。
进入“test\_add.py“所在的目录,执行:
```
python3.7 test_add.py
```
<h2 id="代码风格.md">代码风格</h2>
请遵循这些风格,以使 PyTorch 易于开发、审查和维护。
- 编码指南
请在PyTorch社区使用规统一的编码分格,_Python__中_建议的编码风格是[PEP 8编码样式](https://pep8.org/),_C++_编码所建议的风格是 [Google C++编码指南](http://google.github.io/styleguide/cppguide.html) 。可以使用[CppLint](https://github.com/cpplint/cpplint),[CppCheck](http://cppcheck.sourceforge.net/),[CMakeLint](https://github.com/cmake-lint/cmake-lint),[CodeSpell](https://github.com/codespell-project/codespell), [Lizard](http://www.lizard.ws/),[ShellCheck](https://github.com/koalaman/shellcheck)和[pylint](https://pylint.org/)检查代码的格式,建议在您的IDE中安装这些插件。
- 单元测试指南
请在PyTorch社区使用统一的单元测试风格, _Python_中建议的单元测试风格是[pytest](http://www.pytest.org/en/latest/),_C++_单元测试所建议的风格是 [Googletest Primer](#https://github.com/google/googletest/blob/master/docs/primer.md) 。测试用例的设计意图应该通过它的注释名称来反映。
- 重构指南
我们鼓励开发人员重构我们的代码以消除[代码异味](https://en.wikipedia.org/wiki/Code_smell)。所有的代码都应该符合编码风格和测试风格的需求,重构代码也不例外。当您收到警告时,您必须重构要合并的代码。
<h2 id="门禁异常处理.md">门禁异常处理</h2>
门禁异常主要包含如下几种,请根据相关提示解决异常问题。
- 编译异常
请检查代码编译失败的原因,解决问题后重新编译即可。
- 静态检查异常(代码Bug、代码漏洞、代码异味)
请依照提示查找代码中的异常并解决。
- UT测试未通过
请根据提示,查找测试用例不通过项并检查原因,解决后再测试。
<h2 id="Fork-Pull开发模式.md">Fork-Pull开发模式</h2>
1. Fork PyTorch存储库。
在向PyTorch项目提交代码之前,请确保该项目已经Fork到您自己的存储库。这意味着PyTorch存储库和您自己的存储库之间将存在并行开发,因此请注意避免存储库之间的不一致。
2. 克隆远程仓库。
如果要将代码下载到本地环境,git是很好的方法:
```
# For Gitee
git clone https://gitee.com/{insert_your_forked_repo}/pytorch.git
git remote add upstream https://gitee.com/pytorch/pytorch.git
```
3. 本地开发代码。
为了避免多个分支之间的不一致,建议签出到一个新的分支:
```
git checkout -b {new_branch_name} origin/master
```
以master分支为例,PyTorch可能会根据需要创建版本分支和下游开发分支,请先修复上游的bug。然后就可以随意更改代码了。
4. 将代码推送到远程仓库。
更新代码后,您需要以正式的方式推送更新:
```
git add .
git status # Check the update status
git commit -m "Your commit title"
git commit -s --amend #Add the concrete description of your commit
git push origin {new_branch_name}
```
5. 向 PyTorh存储库拉取请求。
在最后一步中,您需要在新分支和“PyTorch master“分支之间拉取比较请求。完成拉取请求后,“Jenkins CI“将自动设置为构建测试。您的pull request应该尽快合并到上游 master 分支,以降低合并的风险。
<h2 id="报告问题.md">报告问题</h2>
为项目做出贡献的一个好方法是在遇到问题时发送详细报告。我们总是很感激写得很好、彻底的错误报告,并会由此感谢您!
报告问题时,请参考以下格式:
- 您使用的是什么版本的环境 (pytorch、os、python 等)?
- 这是错误报告还是功能请求?
- 什么样的问题,添加标签以在问题仪表板上突出显示。
- 发生了什么?
- 您预计会发生什么?
- 如何重现它?(尽可能最小和精确。)
- 给审稿人的特别说明?
问题咨询:
- 如果您发现一个未解决的问题,而这正是您要解决的问题,请对该问题发表一些评论,告诉其他人您将负责它。
- 如果问题已打开一段时间,建议贡献者在解决该问题之前进行预检查。
- 如果您解决了自己报告的问题,则还需要在关闭该问题之前让其他人知道。
<h2 id="提出PR.md">提出PR</h2>
- 在[Gitee](https://gitee.com/ascend/pytorch/issues)上提出您的想法作为_问题_。
- 如果是需要大量设计细节的新功能,还应提交设计方案。
- 在问题讨论和设计提案审查中达成共识后,完成分叉回购的开发并提交 PR(Pull Request)。
- 在从批准者那里收到2+ LGTM(Looks Good To Me)之前,不允许任何PR 。请注意,审批人不允许在自己的 PR 上添加LGTM。
- 在 PR 被充分讨论后,它将根据讨论的结果被合并、放弃或拒绝。
公关咨询:
- 应避免任何不相关的更改。
- 确保你的提交历史被排序。
- 始终将您的分支与主分支保持一致。
- 对于错误修复 PR,请确保链接所有相关问题。
+18 -66
View File
@@ -1,78 +1,30 @@
From PyTorch:
BSD 3-Clause License
Copyright (c) 2020, Huawei Technologies Co., Ltd
Copyright (c) 2016- Facebook, Inc (Adam Paszke)
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
From Caffe2:
Copyright (c) 2016-present, Facebook Inc. All rights reserved.
All contributions by Facebook:
Copyright (c) 2016 Facebook Inc.
All contributions by Google:
Copyright (c) 2015 Google Inc.
All rights reserved.
All contributions by Yangqing Jia:
Copyright (c) 2015 Yangqing Jia
All rights reserved.
All contributions by Kakao Brain:
Copyright 2019-2020 Kakao Brain
All contributions by Cruise LLC:
Copyright (c) 2022 Cruise LLC.
All rights reserved.
All contributions from Caffe:
Copyright(c) 2013, 2014, 2015, the respective contributors
All rights reserved.
All other contributions:
Copyright(c) 2015, 2016 the respective contributors
All rights reserved.
Caffe2 uses a copyright model similar to Caffe: each contributor holds
copyright over their contributions to Caffe2. The project versioning records
all such contribution and copyright details. If a contributor wants to further
mark their specific copyright on a particular contribution, they should
indicate their copyright solely in the commit message of the change when it is
committed.
Copyright (c) 2019, Facebook CORPORATION.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the names of Facebook, Deepmind Technologies, NYU, NEC Laboratories America
and IDIAP Research Institute nor the names of its contributors may be
used to endorse or promote products derived from this software without
specific prior written permission.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+17 -50
View File
@@ -1,52 +1,19 @@
approvers:
- liwei386
- li_jing_hw
- clinglai
- aichunzheng
- yskhhh
- brightlyking
- wangjiangben_hw
- wangchao285
- AtlasAccount
- dilililiwhy
- chenhao_1209
- sunboquan
- wangchao430
- yanpengquan
- kaixin1976
reviewers:
- xiaxia3
- ascendzyj
- yskhhh
- li_jing_hw
- wangjiangben_hw
- liwei386
- clinglai
- shaoyf
- yanpengquan
- liu-jiaweikf
- xiepeng20
- brightlyking
- chenhao_1209
- wbigat
- will-devil
- ckirchhoff
- liu-tianlong
- wangchao285
- dilililiwhy
- sunjiayang
- huangyunlong2022
- misty-rain-typhoid
- du-jin-hang
- xqiangx1991
- zhan-jun
- wujianping996
- jiangpengfei712
- blian
- nalinaly
- wang-guangbin
- chuboning
- guo-guanghao
- yuhaiyan
- wangchao430
- insanecoder
- Chen_LiQing
reviewers:
- zhou_sinan
- shibo19
- Ronnie_zheng
- xiaxia3
- li_chao10
- petissue
- td__lihan
- ascendzyj
- wangyu0516
- yskhhh
- lvpeiyuan
- xchu42
- weili10
- goodjobwubai
- fairwarning
-283
View File
@@ -1,283 +0,0 @@
# Ascend Extension for PyTorch
## Overview
This repository develops the **Ascend Extension for PyTorch** named **torch_npu** to adapt **Ascend NPU** to **PyTorch** so that developers who use the **PyTorch** can obtain powerful compute capabilities of **Ascend AI Processors**.
Ascend is a full-stack AI computing infrastructure for industry applications and services based on Huawei Ascend processors and software. For more information about Ascend, see [Ascend Community](https://www.hiascend.com/en/).
## Installation
### From Binary
Provide users with wheel package to quickly install **torch_npu**. Before installing **torch_npu**, complete the installation of **CANN** according to [Ascend Auxiliary Software](#ascend-auxiliary-software). To obtain the **CANN** installation package, refer to the [CANN Installation](https://www.hiascend.com/cann).
1. **Install PyTorch**
Install **PyTorch** through pip.
**For Aarch64:**
```bash
pip3 install torch==2.8.0
```
**For x86:**
```bash
pip3 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu
```
2. **Install torch-npu dependencies**
Run the following command to install dependencies.
```bash
pip3 install pyyaml
pip3 install setuptools
```
If the installation fails, use the download link or visit the [PyTorch official website](https://pytorch.org/) to download the installation package of the corresponding version.
| OS arch | Python version | link |
|---------|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| x86 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_x86_64.whl#sha256=bda4f93d64dcd9ae5d51844bbccc6fcb7d603522bcc95d256b5fe3bdb9dccca3) |
| x86 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_x86_64.whl#sha256=16d75fa4e96ea28a785dfd66083ca55eb1058b6d6c5413f01656ca965ee2077e) |
| x86 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_x86_64.whl#sha256=cb06175284673a581dd91fb1965662ae4ecaba6e5c357aa0ea7bb8b84b6b7eeb) |
| aarch64 | Python3.9 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp39-cp39-manylinux_2_28_aarch64.whl#sha256=eac8b7ef5c7ca106daec5e829dfa8ca56ca47601db13b402d2608861ad3ab926) |
| aarch64 | Python3.10 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp310-cp310-manylinux_2_28_aarch64.whl#sha256=b2149858b8340aeeb1f3056e0bff5b82b96e43b596fe49a9dba3184522261213) |
| aarch64 | Python3.11 | [link](https://download.pytorch.org/whl/cpu/torch-2.8.0%2Bcpu-cp311-cp311-manylinux_2_28_aarch64.whl#sha256=680129efdeeec3db5da3f88ee5d28c1b1e103b774aef40f9d638e2cce8f8d8d8) |
3. **Install torch-npu**
```
pip3 install torch-npu==2.8.0
```
### From Source
In some special scenarios, users may need to compile **torch-npu** by themselves.Select a branch in table [Ascend Auxiliary Software](#ascend-auxiliary-software) and a Python version in table [PyTorch and Python Version Matching Table](#pytorch-and-python-version-matching-table) first. The docker image is recommended for compiling torch-npu through the following steps(It is recommended to mount the working path only and avoid the system path to reduce security risks.), the generated .whl file path is ./dist/. Note that gcc version has the following constraints if you try to compile without using docker image: we recommend to use gcc 13.3 for both ARM and X86.
1. **Clone torch-npu**
```
git clone https://github.com/ascend/pytorch.git -b v2.8.0-7.2.0 --depth 1
```
2. **Build Docker Image**
```
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
3. **Enter Docker Container**
```
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
4. **Compile torch-npu**
Take **Python 3.9** as an example.
```
cd /home/pytorch
bash ci/build.sh --python=3.9
```
**Tips**
If you would like to compile with new C++ ABI, then first run this command, at this point, the recommended compilation environment is same to community torch package: glibc 2.28, gcc 13.3.1
```
export _GLIBCXX_USE_CXX11_ABI=1
```
Meanwhile, we support configuring -fabi-version using the following variables,require consistency with the community torch package
```
export _ABI_VERSION=18
```
## Getting Started
### Prerequisites
Initialize **CANN** environment variable by running the command as shown below.
```Shell
# Default path, change it if needed.
source /usr/local/Ascend/ascend-toolkit/set_env.sh
```
### Quick Verification
You can quickly experience **Ascend NPU** by the following simple examples.
```diff
import torch
- import torch_npu # No longer needed in torch_npu 2.5.1 and later versions
x = torch.randn(2, 2).npu()
y = torch.randn(2, 2).npu()
z = x.mm(y)
print(z)
```
## User Manual
Refer to [API of Ascend Extension for PyTorch](docs/api/torch_npu_apis.md) for more detailed information.
## PyTorch and Python Version Matching Table
| PyTorch Version | Python Version |
|-----------------|:----------------------------------------------------------|
| PyTorch1.11.0 | Python3.7.x(>=3.7.5),Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.1.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.2.0 | Python3.8.x,Python3.9.x,Python3.10.x |
| PyTorch2.3.1 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.4.0 | Python3.8.x,Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.5.1 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.6.0 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.7.1 | Python3.9.x,Python3.10.x,Python3.11.x |
| PyTorch2.8.0 | Python3.9.x,Python3.10.x,Python3.11.x |
## Ascend Auxiliary Software
**PyTorch Extension** versions follow the naming convention `{PyTorch version}-{Ascend version}`, where the former represents the PyTorch version compatible with the **PyTorch Extension**, and the latter is used to match the CANN version. The detailed matching is as follows:
| CANN Version | Supported PyTorch Version | Supported Extension Version | Github Branch |
|-----------------------|---------------------------|-----------------------------|-------------------|
| CANN 8.5.0 | 2.9.0 | 2.9.0 | v2.9.0-7.3.0 |
| | 2.8.0 | 2.8.0.post2 | v2.8.0-7.3.0 |
| | 2.7.1 | 2.7.1.post2 | v2.7.1-7.3.0 |
| | 2.6.0 | 2.6.0.post5 | v2.6.0-7.3.0 |
| CANN 8.3.RC1 | 2.8.0 | 2.8.0 | v2.8.0-7.2.0 |
| | 2.7.1 | 2.7.1 | v2.7.1-7.2.0 |
| | 2.6.0 | 2.6.0.post3 | v2.6.0-7.2.0 |
| | 2.1.0 | 2.1.0.post17 | v2.1.0-7.2.0 |
| CANN 8.2.RC1 | 2.6.0 | 2.6.0 | v2.6.0-7.1.0 |
| | 2.5.1 | 2.5.1.post1 | v2.5.1-7.1.0 |
| | 2.1.0 | 2.1.0.post13 | v2.1.0-7.1.0 |
| CANN 8.1.RC1 | 2.5.1 | 2.5.1 | v2.5.1-7.0.0 |
| | 2.4.0 | 2.4.0.post4 | v2.4.0-7.0.0 |
| | 2.3.1 | 2.3.1.post6 | v2.3.1-7.0.0 |
| | 2.1.0 | 2.1.0.post12 | v2.1.0-7.0.0 |
| CANN 8.0.0 | 2.4.0 | 2.4.0.post2 | v2.4.0-6.0.0 |
| | 2.3.1 | 2.3.1.post4 | v2.3.1-6.0.0 |
| | 2.1.0 | 2.1.0.post10 | v2.1.0-6.0.0 |
| CANN 8.0.RC3 | 2.4.0 | 2.4.0 | v2.4.0-6.0.rc3 |
| | 2.3.1 | 2.3.1.post2 | v2.3.1-6.0.rc3 |
| | 2.1.0 | 2.1.0.post8 | v2.1.0-6.0.rc3 |
| CANN 8.0.RC2 | 2.3.1 | 2.3.1 | v2.3.1-6.0.rc2 |
| | 2.2.0 | 2.2.0.post2 | v2.2.0-6.0.rc2 |
| | 2.1.0 | 2.1.0.post6 | v2.1.0-6.0.rc2 |
| | 1.11.0 | 1.11.0.post14 | v1.11.0-6.0.rc2 |
| CANN 8.0.RC1 | 2.2.0 | 2.2.0 | v2.2.0-6.0.rc1 |
| | 2.1.0 | 2.1.0.post4 | v2.1.0-6.0.rc1 |
| | 1.11.0 | 1.11.0.post11 | v1.11.0-6.0.rc1 |
| CANN 7.0.0 | 2.1.0 | 2.1.0 | v2.1.0-5.0.0 |
| | 2.0.1 | 2.0.1.post1 | v2.0.1-5.0.0 |
| | 1.11.0 | 1.11.0.post8 | v1.11.0-5.0.0 |
| CANN 7.0.RC1 | 2.1.0 | 2.1.0.rc1 | v2.1.0-5.0.rc3 |
| | 2.0.1 | 2.0.1 | v2.0.1-5.0.rc3 |
| | 1.11.0 | 1.11.0.post4 | v1.11.0-5.0.rc3 |
| CANN 6.3.RC3.1 | 1.11.0 | 1.11.0.post3 | v1.11.0-5.0.rc2.2 |
| CANN 6.3.RC3 | 1.11.0 | 1.11.0.post2 | v1.11.0-5.0.rc2.1 |
| CANN 6.3.RC2 | 2.0.1 | 2.0.1.rc1 | v2.0.1-5.0.rc2 |
| | 1.11.0 | 1.11.0.post1 | v1.11.0-5.0.rc2 |
| | 1.8.1 | 1.8.1.post2 | v1.8.1-5.0.rc2 |
| CANN 6.3.RC1 | 1.11.0 | 1.11.0 | v1.11.0-5.0.rc1 |
| | 1.8.1 | 1.8.1.post1 | v1.8.1-5.0.rc1 |
| CANN 6.0.1 | 1.5.0 | 1.5.0.post8 | v1.5.0-3.0.0 |
| | 1.8.1 | 1.8.1 | v1.8.1-3.0.0 |
| | 1.11.0 | 1.11.0.rc2(beta) | v1.11.0-3.0.0 |
| CANN 6.0.RC1 | 1.5.0 | 1.5.0.post7 | v1.5.0-3.0.rc3 |
| | 1.8.1 | 1.8.1.rc3 | v1.8.1-3.0.rc3 |
| | 1.11.0 | 1.11.0.rc1(beta) | v1.11.0-3.0.rc3 |
| CANN 5.1.RC2 | 1.5.0 | 1.5.0.post6 | v1.5.0-3.0.rc2 |
| | 1.8.1 | 1.8.1.rc2 | v1.8.1-3.0.rc2 |
| CANN 5.1.RC1 | 1.5.0 | 1.5.0.post5 | v1.5.0-3.0.rc1 |
| | 1.8.1 | 1.8.1.rc1 | v1.8.1-3.0.rc1 |
| CANN 5.0.4 | 1.5.0 | 1.5.0.post4 | 2.0.4.tr5 |
| CANN 5.0.3 | 1.8.1 | 1.5.0.post3 | 2.0.3.tr5 |
| CANN 5.0.2 | 1.5.0 | 1.5.0.post2 | 2.0.2.tr5 |
## Hardware support
The Ascend training device includes the following models, all of which can be used as training environments for PyTorch models
| Product series | Product model |
|-----------------------|----------------------------------|
| Atlas Training series products | Atlas 800(model: 9000) |
| | Atlas 800(model:9010) |
| | Atlas 900 PoD(model:9000) |
| | Atlas 300T(model:9000) |
| | Atlas 300T Pro(model:9000) |
| Atlas A2 Training series products | Atlas 800T A2 |
| | Atlas 900 A2 PoD |
| | Atlas 200T A2 Box16 |
| | Atlas 300T A2 |
The Ascend inference device includes the following models, all of which can be used as inference environments for large models
| Product series | Product model |
|-----------------------|----------------------------------|
| Atlas 800I A2 Inference product | Atlas 800I A2 |
## Pipeline Status
Due to the asynchronous development mechanism of upstream and downstream, incompatible modifications in upstream may cause some functions of **torch_npu** to be unavailable (only upstream and downstream development branches are involved, excluding stable branches). Therefore, we built a set of daily tasks that make it easy to detect relevant issues in time and fix them within 48 hours (under normal circumstances), providing users with the latest features and stable quality.
| **OS** | **CANN Version(Docker Image)** | **Upstream Branch** | **Downstream Branch** | **Period** | **Status** |
| :---: | :---: | :---: | :---: | :---: | :---: |
| openEuler 22.03 SP2 | [CANN 7.1](https://hub.docker.com/r/ascendai/cann/tags) | [main](https://github.com/pytorch/pytorch/tree/main) | [master](https://github.com/Ascend/pytorch/tree/master) | UTC 1200 daily | [![Ascend NPU](https://github.com/Ascend/pytorch/actions/workflows/periodic.yml/badge.svg)](https://github.com/Ascend/pytorch/actions/workflows/periodic.yml) |
## Suggestions and Communication
Everyone is welcome to contribute to the community. If you have any questions or suggestions, you can submit [Github Issues](https://github.com/Ascend/pytorch/issues). We will reply to you as soon as possible. Thank you very much.
## Branch Maintenance Policies
The version branches of AscendPyTorch have the following maintenance phases:
| **Status** | **Duration** | **Description** |
|-------------------|--------------|--------------------------------------------------------------------------------------------------------------------------------|
| Planning | 1-3 months | Plan features. |
| Development | 6-12 months | Develop new features and fix issues, regularly release new versions. Different strategies are adopted for different versions of PyTorch, with a regular branch development cycle of 6 months and a long-term support branch development cycle of 12 months. |
| Maintained | 1 year/3.5 years | Regular Release branch for 1 year, Long Term Support branch maintenance for 3.5 years. Fix major issues, do not incorporate new features, and release patch versions based on the impact of fixed bugs. |
| End Of Life (EOL) | N/A | Do not accept any modification to a branch. |
## PyTorch Maintenance Policies
| **PyTorch** | **Maintenance Policies** | **Status** | **Launch Date** | **Subsequent Status** | **EOL Date** |
|-------------|--------------------------|-------------|-----------------|-------------------------------------------------------------------|--------------|
| 2.9.0 | Regular Release | Development | 2026/01/15 | Expected to enter maintenance status from July 15, 2026 | - |
| 2.8.0 | Regular Release | Development | 2025/10/15 | Expected to enter maintenance status from March 15, 2026 | - |
| 2.7.1 | Long Term Support | Development | 2025/10/15 | Expected to enter maintenance status from October 15, 2026 | |
| 2.6.0 | Regular Release | Development | 2025/07/25 | Expected to enter maintenance status from January 15, 2026 | - |
| 2.5.1 | Regular Release | Maintained | 2024/11/08 | Expected to enter maintenance free status from August 8, 2026 | |
| 2.4.0 | Regular Release | Maintained | 2024/10/15 | Expected to enter maintenance free status from June 15, 2026 | |
| 2.3.1 | Regular Release | Maintained | 2024/06/06 | Expected to enter maintenance free status from June 7, 2026 | |
| 2.2.0 | Regular Release | EOL | 2024/04/01 | | 2025/10/14 |
| 2.1.0 | Long Term Support | Maintained | 2023/10/15 | Expected to enter maintenance free status from December 30, 2026 | |
| 2.0.1 | Regular Release | EOL | 2023/7/19 | | 2024/3/14 |
| 1.11.0 | Long Term Support | EOL | 2023/4/19 | | 2025/10/25 |
| 1.8.1 | Long Term Support | EOL | 2022/4/10 | | 2023/4/10 |
| 1.5.0 | Long Term Support | EOL | 2021/7/29 | | 2022/7/29 |
## Reference Documents
For more detailed information on installation guides, model migration, training/inference tutorials, and API lists, please refer to the [Ascend Extension for PyTorch on the HiAI Community](https://www.hiascend.com/software/ai-frameworks?framework=pytorch).
| Document Name | Document Link |
|------------------------------------------|-------------------------------------------------------------------------------------------------------------------------|
| Installation Guide | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/configandinstg/instg/insg_0001.html) |
| Network Model Migration and Training | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/ptmoddevg/trainingmigrguide/PT_LMTMOG_0003.html) |
| Operator Adaptation | [link](https://www.hiascend.com/document/detail/zh/canncommercial/81RC1/operatordev/tbeaicpudevg/atlasopdev_10_0086.html) |
| API List (PyTorch and Custom Interfaces) | [link](https://www.hiascend.com/document/detail/zh/Pytorch/720/apiref/apilist/ptaoplist_000002.html) |
## License
Ascend Extension for PyTorch has a BSD-style license, as found in the [LICENSE](LICENSE) file.
+234 -78
View File
@@ -1,104 +1,260 @@
# Ascend Extension for PyTorch插件
# AscendPyTorch
## 简介
本项目开发了名为**torch_npu**的**Ascend Extension for PyTorch**插件,使昇腾NPU可以适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
# 项目简介
本项目开发了PyTorch Adapter插件,用于昇腾适配PyTorch框架,为使用PyTorch框架的开发者提供昇腾AI处理器的超强算力。
昇腾为基于华为昇腾处理器和软件的行业应用及服务提供全栈AI计算基础设施。您可以通过访问[昇腾社区](https://www.hiascend.com/zh/),了解关于昇腾的更多信息。
# 编译/执行约束
## 目录结构
gcc版本: 7.3.0(只在编译场景要求)
关键目录如下:
cmake版本:3.12.0以上版本(只在编译场景要求)
```ColdFusion
├─ci # 持续集成脚本目录
├─cmake # CMake构建配置目录
├─torch_npu # 核心适配目录
│ ├─csrc/ # 底层核心目录
│ ├─npu/ # NPU接口目录
│ ├─distributed/ # 分布式训练适配目录
│ ├─asd/ # Ascend Debug工具目录
├─docs # 项目文档目录
├─examples # 示例目录
├─torchnpugen/ # 代码生成模块目录
└─test # 测试目录
python版本:3.7.5 和 3.8.x(编译方法有差别,详见脚本编译章节)
# 系统依赖库
## CentOS & EulerOS
yum install -y cmake zlib-devel libffi-devel openssl-devel libjpeg-turbo-devel gcc-c++ sqlite-devel dos2unix openblas
## Ubuntu
apt-get install -y gcc 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 cmake dos2unix libopenblas-dev
# Ascend配套软件
| AscendPyTorch版本 | CANN版本 | 支持PyTorch版本 |
| :------------ | :----------- | :----------- |
| 2.0.2 | CANN 5.0.2 | 1.5.0 |
| 2.0.3 | CANN 5.0.3 | 1.5.0,1.8.1(仅支持resnet50模型) |
# 使用方式 --生成全量代码并编译
## 获取原生PyTorch源代码和third_party代码
当前支持pytorch 1.5.0和1.8.1的版本。根据需求,在当前仓库根目录pytorch/下获取原生PyTorch的源代码
```sh
//昇腾Pytorch
git clone -b 2.0.3.tr5 https://gitee.com/ascend/pytorch.git
cd pytorch
// 1.5.0 版本
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
// 1.8.1 版本
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git
```
## 版本说明
进入到pytorch/pytorch/目录下, 获取PyTorch被动依赖代码(获取时间较长,请耐心等待)。
Ascend Extension for PyTorch的版本说明包含版本配套说明、版本兼容性说明和更新说明等,具体请参见《[Ascend Extension for PyTorch 版本说明](https://gitcode.com/Ascend/pytorch/blob/v2.7.1/docs/zh/release_notes/release_notes.md)》。
```sh
git submodule sync
git submodule update --init --recursive
```
完成且没有报错之后就生成了PyTorch及其依赖的三方代码
## 生成适配昇腾AI处理器的PyTorch代码。
进入到pytorch/scripts目录,根据选择的版本执行,执行脚本(注意:下载原生Pytorch源代码和下面版本要对应,否则可能出错)
```sh
// 默认为1.5.0版本
bash gen.sh
// 对于1.8.1版本,则通过-v 参数指定
bash gen.sh -v 1.8.1
```
会在pytorch/pytorch/目录中生成npu适配全量代码
## 环境部署
## python依赖库
Ascend Extension for PyTorch插件的安装操作,具体请参见《[Ascend Extension for PyTorch 软件安装](https://gitcode.com/Ascend/pytorch/blob/v2.7.1/docs/zh/installation_guide/menu_installation_guide.md)》。
进入到pytorch/pytorch/目录,依赖库安装:
## 快速入门
以CNN模型为例,介绍将其迁移至昇腾NPU上进行训练的方法,具体操作请参见《[Ascend Extension for PyTorch 快速入门](https://gitcode.com/Ascend/pytorch/blob/v2.7.1/docs/zh/quick_start/quick_start.md)》。
## 特性介绍
Ascend Extension for PyTorch插件从内存资源优化、通信性能优化、计算性能优化、辅助报错定位等方面精心打造了一系列独特的特性,具体特性指导请参见《[PyTorch 框架特性指南](https://gitcode.com/Ascend/pytorch/blob/v2.7.1/docs/zh/framework_feature_guide_pytorch/menu_framework_feature.md)》。
## API参考
- 原生PyTorch API在昇腾NPU设备上的支持情况请参见《[PyTorch 原生API支持度](https://gitcode.com/Ascend/pytorch/blob/v2.7.1/docs/zh/native_apis/menu_pt_native_apis.md)》。
- Ascend Extension for PyTorch插件提供了部分自定义API接口,具体使用请参见《[Ascend Extension for PyTorch自定义API](https://gitcode.com/Ascend/op-plugin/blob/master/docs/zh/custom_APIs/menu_Pytorch_API.md)》。
## 分支维护策略
Ascend Extension for PyTorch版本分支的维护阶段如下:
```python3
pip3 install -r requirements.txt
```
| **状态** | **时间** | **说明** |
| ------------------- | -------- | ------------------------------------------------ |
| 计划 | 1—3 个月 | 计划特性 |
| 开发 | 6—12 个月 | 开发新特性并修复问题,定期发布新版本。针对不同的PyTorch版本采取不同的策略,常规分支的开发周期分别为6个月,长期支持分支的开发周期为12个月 |
| 维护 | 1年/3.5年 | 常规分支维护1年,长期支持分支维护3.5年。对重大BUG进行修复,不合入新特性,并视BUG的影响发布补丁版本 |
| 生命周期终止(EOL) | N/A | 分支不再接受任何修改 |
## 编译torch的二进制包
## PyTorch版本维护策略
进入到pytorch/pytorch/目录,执行
| **PyTorch版本** | **维护策略** | **当前状态** | **发布时间** | **后续状态** | **EOL日期** |
|---------------|----------|----------|------------|----------------------|-----------|
| 2.9.0 | 常规分支 | 开发 | 2026/01/15| 预计2026/07/15起进入维护状态 | - |
| 2.8.0 | 常规分支 | 开发 | 2025/10/15| 预计2026/03/15起进入维护状态 | - |
| 2.7.1 | 长期分支 | 开发 | 2025/10/15| 预计2026/10/15起进入维护状态 | - |
| 2.6.0 | 常规分支 | 开发 | 2025/07/25 | 预计2026/01/25起进入维护状态 | - |
| 2.5.1 | 常规分支 | 维护 | 2024/11/08 | 预计2026/08/08起进入无维护状态 | - |
| 2.4.0 | 常规分支 | 维护 | 2024/10/15 | 预计2026/06/15起进入无维护状态 | - |
| 2.3.1 | 常规分支 | 维护 | 2024/06/06 | 预计2026/06/07起进入无维护状态 | |
| 2.2.0 | 常规分支 | EOL | 2024/04/01 | | 2025/10/14 |
| 2.1.0 | 长期支持 | 维护 | 2023/10/15 | 预计2026/12/30起进入无维护状态 | |
| 2.0.1 | 常规分支 | EOL | 2023/7/19 | | 2024/3/14 |
| 1.11.0 | 长期支持 | EOL | 2023/4/19 | | 2025/10/25 |
| 1.8.1 | 长期支持 | EOL | 2022/4/10 | | 2023/4/10 |
| 1.5.0 | 长期支持 | EOL | 2021/7/29 | | 2022/7/29 |
```sh
# python3.7版本
bash build.sh
或者
bash build.sh --python=3.7(推荐)
## 贡献指导
介绍如何向Ascend Extension for PyTorch插件库贡献代码,具体请参见[Ascend Extension for PyTorch插件 贡献指南](CONTRIBUTING.md)。
# python3.8版本
bash build.sh --python=3.8
```
## 联系我们
生成的二进制包在pytorch/pytorch/dist/目录下
欢迎大家为社区做贡献。如果有任何疑问或建议,请提交[GitCode Issues](https://gitcode.com/Ascend/pytorch/issues),我们会尽快回复。感谢您的支持。
# 安装
## 安全声明
Ascend Extension for PyTorch的系统安全加固、运行用户建议和文件权限控制等内容,请参见[Ascend Extension for PyTorch插件 安全声明](SECURITYNOTE.md)。
### (以1.5.0版本为例,1.8.1版本同理)
## 免责声明
致Ascend Extension for PyTorch插件使用者
- 本插件仅供调试和开发使用,使用者需自行承担使用风险,并理解以下内容:
- 数据处理及删除:用户在使用本插件过程中产生的数据属于用户责任范畴。建议用户在使用完毕后及时删除相关数据,以防信息泄露。
- 数据保密与传播:使用者了解并同意不得将通过本插件产生的数据随意外发或传播。对于由此产生的信息泄露、数据泄露或其他不良后果,本插件及其开发者概不负责。
- 用户输入安全性:用户需自行保证输入的命令行的安全性,并承担因输入不当而导致的任何安全风险或损失。对于输入命令行不当所导致的问题,本插件及其开发者概不负责。
- 免责声明范围:本免责声明适用于所有使用本插件的个人或实体。使用本插件即表示您同意并接受本声明的内容,并愿意承担因使用该功能而产生的风险和责任,如有异议请停止使用本插件。
- 在使用本工具之前,请谨慎阅读并理解以上免责声明的内容。对于使用本插件所产生的任何问题或疑问,请及时联系开发者。
**x86_64:**
## License
torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_x86_64.whl)
Ascend Extension for PyTorch插件的使用许可证,具体请参见[LICENSE](LICENSE)文件。
```shell
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_x86_64.whl
```
## 致谢
感谢来自社区的每一个PR,欢迎贡献Ascend Extension for PyTorch插件!
**arm:**
torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl (实际可能附带小版本号例如torch-1.5.0.post2+ascend-cp37-cp37m-linux_aarch64.whl)
```shell
pip3 uninstall torch
pip3 install --upgrade torch-1.5.0+ascend-cp37-cp37m-linux_aarch64.whl
```
# 运行
## 运行环境变量
在当前仓库根目录中执行设置环境变量脚本
```
source pytorch/env.sh
```
## 自定义环境变量
以下环境变量为NPU场景下使用的功能类或可以提升性能的环境变量:
```
export TASK_QUEUE_ENABLE=1 # 使用异步任务下发,异步调用acl接口,建议默认开启,开启设置为1
export PTCOPY_ENABLE=1 # 使用PTCopy算子模式,加速转连续及copy等过程,建议默认开启,开启设置为1
```
可选的环境变量可能会对运行的模型产生影响:
```
export DYNAMIC_COMPILE_ENABLE=1 # 动态shape特性功能,针对shape变化场景,可选,开启设置为1
export COMBINED_ENABLE=1 # 非连续两个算子组合类场景优化,可选,开启设置为1
export TRI_COMBINED_ENABLE=1 # 非连续三个算子组合类场景优化,可选,开启设置为1
export ACL_DUMP_DATA=1 # 算子数据dump功能,调试时使用,可选,开启设置为1
export DYNAMIC_OP="ADD#MUL" # 算子实现,ADD和MUL算子在不同场景下有不同的性能表现。可选
```
## 执行单元测试脚本
验证运行, 输出结果OK
```shell
// 根据前述版本,选择对应的测试脚本,以下为1.5.0版本
python3 pytorch1.5.0/test/test_npu/test_div.py
// 以下为1.8.1版本
python3 pytorch1.8.1/test/test_npu/test_div.py
```
# 文档
有关安装指南、模型迁移和训练/推理教程和API列表等更多详细信息,请参考[用户文档](docs/zh)。
# 建议与交流
热忱希望各位在用户社区加入讨论,并贡献您的建议,我们会尽快给您回复。
# 分支维护策略
Ascend PyTorch的版本分支有以下几种维护阶段:
| **状态** | **持续时间** | **说明** |
|-------------|---------------|--------------------------------------------------|
| Planning | 1 - 3 months | 特性规划。 |
| Development | 3 months | 特性开发。 |
| Maintained | 6 - 12 months | 允许所有问题修复的合入,并发布版本。 |
| Unmaintained| 0 - 3 months | 允许所有问题修复的合入,无专人维护,不再发布版本。 |
| End Of Life (EOL) | N/A | 不再接受修改合入该分支。 |
# 现有分支维护状态
| **分支名** | **当前状态** | **上线时间** | **后续状态** | **EOL 日期**|
|------------|--------------|----------------------|----------------------------------------|------------|
| **v2.0.2** | Maintained | 2021-07-29 | Unmaintained <br> 2022-07-29 estimated | |
| **v2.0.3** | Maintained | 2021-10-15 | Unmaintained <br> 2022-10-15 estimated | |
# FAQ
## 编译过程执行bash build.sh报错no module named yaml/typing_extensions.
pytorch编译依赖 yaml库和typing_extensions库,需要手动安装。
pip3 install pyyaml
pip3 install typing_extensions
安装成功后,注意需要执行make clean在执行bash build.sh进行编译,否则可能因缓存出现未知编译错误。
## 运行遇到找不到te问题
开发态:
cd /urs/local/ascend-toolkit/latest/fwkacllib/lib64
用户态:
cd /urs/local/nnae/latest/fwkacllib/lib64
pip3 install --upgrade topi-0.4.0-py3-none-any.whl
pip3 install --upgrade te-0.4.0-py3-none-any.whl
## 编译cmake报错版本过低
cmake官网下载linux版本安装(当前3.18.0)
1. 使用yum命令安装: yum install -y cmake==3.18.0
2. 下载cmake sh脚本安装:(参考cmake官网)
X86_64环境推荐脚本安装: cmake-3.18.2-Linux-x86_64.sh
## GCC版本问题切换问题
目前存在测试环境从GCC4.8.5 切换到 GCC7.3.0。这个过程容易出现错误导致pytorch编译不过,以下是需要软连接的库
gcc, g++,c++(--version 必须是7.3.0)
libstdc++->libstdc++.so.6.0.24(7.3.0)
## 找不到libblas.so问题
环境缺少openblas库,需要安装openblas库
Centos,EulerOS环境
```sh
yum -y install openblas
```
Ubuntu环境
```sh
apt install libopenblas-dev
```
# 版本说明
版本说明请参阅[ReleseNote](docs/zh/RELEASENOTE)
-313
View File
@@ -1,313 +0,0 @@
# Ascend Extension for PyTorch插件 安全声明
## 系统安全加固
建议用户在系统中配置开启ASLR(级别2 ),又称**全随机地址空间布局随机化**,可参考以下方式进行配置:
echo 2 > /proc/sys/kernel/randomize_va_space
## 运行用户建议
出于安全性及权限最小化角度考虑,不建议使用root等管理员类型账户使用torch_npu。
## 文件权限控制
1. 建议用户对训练所需文件、训练过程中保存的文件、用户个人的隐私数据、商业资产等敏感文件做好权限控制等安全措施,例如多用户共享数据集场景下的数据集文件写权限控制、profiler等场景产生数据文件权限控制等,设定的权限建议参见[文件权限参考](#文件权限参考)进行设置。
2. torch_npu中profiler工具会生成性能记录文件,生成的文件权限为640,文件夹权限为750,用户可根据需要自行对生成后的相关文件进行权限控制。
3. 用户安装和使用过程需要做好权限控制,建议参见[文件权限参考](#文件权限参考)进行设置。如需要保存安装/卸载日志,可在安装/卸载命令后面加上参数--log <FILE>, 注意对<FILE>文件及目录做好权限管控。
4. PyTorch框架运行中所生成的文件权限依赖系统设定,如torch.save接口保存的文件。建议当前执行脚本的用户根据自身需要,对生成文件做好权限控制,设定的权限可参见[文件权限参考](#文件权限参考) 。可使用umask控制默认权限,降低提权等安全风险,建议用户将主机(包括宿主机)和容器中的umask设置为0027及其以上,提高安全性。
##### 文件权限参考
| 类型 | Linux权限参考最大值 |
|----------------------------------- |-----------------------|
| 用户主目录 | 750(rwxr-x---) |
| 程序文件(含脚本文件、库文件等) | 550(r-xr-x---) |
| 程序文件目录 | 550(r-xr-x---) |
| 配置文件 | 640(rw-r-----) |
| 配置文件目录 | 750(rwxr-x---) |
| 日志文件(记录完毕或者已经归档) | 440(r--r-----) |
| 日志文件(正在记录) | 640(rw-r-----) |
| 日志文件目录 | 750(rwxr-x---) |
| Debug文件 | 640(rw-r-----) |
| Debug文件目录 | 750(rwxr-x---) |
| 临时文件目录 | 750(rwxr-x---) |
| 维护升级文件目录 | 770(rwxrwx---) |
| 业务数据文件 | 640(rw-r-----) |
| 业务数据文件目录 | 750(rwxr-x---) |
| 密钥组件、私钥、证书、密文文件目录 | 700(rwx------) |
| 密钥组件、私钥、证书、加密密文 | 600(rw-------) |
| 加解密接口、加解密脚本 | 500(r-x------) |
## 调试工具声明
torch_npu内集成性能分析工具profiler:
- 集成原因:对标PyTorch原生支持能力,提供NPU PyTorch框架开发性能分析能力,加速性能分析调试过程。
- 使用场景:默认不采集,如用户需要进行性能分析时,可在模型训练脚本中添加Ascend Extension for PyTorch Profiler接口,执行训练的同时采集性能数据,完成训练后直接输出可视化的性能数据文件。
- 风险提示:使用该功能会在本地生成性能数据,用户需加强对相关性能数据的保护,请在需要模型性能分析时使用,分析完成后及时关闭。Profiler工具具体细节请参考[《PyTorch 性能分析工具介绍》](https://www.hiascend.com/document/detail/zh/Pytorch/710/ptmoddevg/trainingmigrguide/performance_tuning_0014.html)。
## 数据安全声明
1. PyTorch使用过程中需要加载和保存数据,部分接口使用风险模块pickle,可能存在数据风险,如torch.load、torch.jit.load、torch.distributed.scatter_object_list等接口,可参考[torch.load](https://pytorch.org/docs/main/generated/torch.load.html#torch.load)、[collective-functions](https://pytorch.org/docs/main/distributed.html#collective-functions)了解具体风险。
2. Ascend Extension for PyTorch依赖CANN的基础能力实现AOE性能调优、算子dump、日志记录等功能,用户需要关注上述功能生成文件的权限控制,加强对相关数据的保护。
## 构建安全声明
torch_npu支持源码编译安装,在编译时会下载依赖第三方库并执行构建shell脚本,在编译过程中会产生临时程序文件和编译目录。用户可根据需要自行对源代码目录内的文件进行权限管控降低安全风险。
## 运行安全声明
1. 建议用户结合运行环境资源状况编写对应训练脚本。若训练脚本与资源状况不匹配,如数据集加载内存大小超出内存容量限制、训练脚本在本地生成数据超过磁盘空间大小等情况,可能引发错误并导致进程意外退出。
2. PyTorch和torch_npu在运行异常时会退出进程并打印报错信息,属于正常现象。建议用户根据报错提示定位具体错误原因,包括设定算子同步执行、查看CANN日志、解析生成的Core Dump文件等方式。
3. PyTorch和torch_npu的分布式特性仅适用于内部通信。出于性能考虑,这些分布式特性不包含任何授权协议,并且会发送未加密的消息。关于PyTorch分布式特性的详细说明及安全注意事项,可参考[using-distributed-features](https://github.com/pytorch/pytorch/security#using-distributed-features)。
## 公网地址声明
在torch_npu的配置文件和脚本中存在[公网地址](#公网地址)
##### 公网地址
| 类型 | 开源代码地址 | 文件名 | 公网IP地址/公网URL地址/域名/邮箱地址 | 用途说明 |
|------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------|--------------------------------------------------------------------------------|--------------------------------|
| 自研 | 不涉及 | .gitmodules | https://gitcode.com/ascend/op-plugin.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/googletest.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/ascend/torchair.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitcode.com/ascend/Tensorpipe.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/fmt.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors/nlohmann-json.git | 依赖的开源代码仓 |
| 自研 | 不涉及 | .gitmodules | https://gitee.com/mirrors_llvm/torch-mlir.git | 依赖的开源代码仓 | |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://download.pytorch.org/whl/cpu | docker配置源,用于配置torch下载连接 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.huaweicloud.com/repository/pypi/simple | docker配置文件,用于配置pip源 |
| 自研 | 不涉及 | ci\docker\X86\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | ci\docker\ARM\Dockerfile | https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo | docker配置文件,用于配置yum源 |
| 自研 | 不涉及 | .github\workflows\\_build-and-test.yml | https://mirrors.huaweicloud.com/repository/pypi/simple | workflow配置文件,用于配置pip源 |
| 自研 | 不涉及 | setup.cfg | https://gitcode.com/ascend/pytorch | 用于打包whl的url入参 |
| 自研 | 不涉及 | setup.cfg | https://gitcode.com/ascend/pytorch/tags | 用于打包whl的download_url入参 |
| 自研 | 不涉及 | third_party\op-plugin\ci\build.sh | https://gitcode.com/ascend/pytorch.git | 编译脚本根据torch_npu仓库地址拉取代码进行编译 |
| 自研 | 不涉及 | third_party\op-plugin\ci\exec_ut.sh | https://gitcode.com/ascend/pytorch.git | UT脚本根据torch_npu仓库地址拉取代码进行UT测试 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/nn/test_convolution.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_mps.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_conv2d.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/legacy_serialized.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/gpu_tensors.pt | 用于test脚本下载相关pt文件 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/onnx/test_utility_funs.py | test\url.ini | https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml | issue的链接 |
| 开源引入 | https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_nn.py <br> https://github.com/pytorch/pytorch/blob/v2.8.0/test/test_serialization.py | test\url.ini | https://download.pytorch.org/test_data/linear.pt | 用于test脚本下载相关pt文件 |
| 自研 | 不涉及 | torch_npu\npu\config.yaml | https://raw.githubusercontent.com/brendangregg/FlameGraph/master/flamegraph.pl | 火焰图脚本下载路径 |
| 自研 | 不涉及 | test\requirements.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\requirements.txt | https://data.pyg.org/whl/torch-2.7.0+cpu.html | 下载链接,用于下载torch-scatter的cpu版本 |
| 自研 | 不涉及 | requirements.txt | https://download.pytorch.org/whl/cpu | 下载链接,用于下载torch-cpu版本 |
| 自研 | 不涉及 | test\get_synchronized_files.sh | https://github.com/pytorch/pytorch.git | 下载链接,用于下载PyTorch的测试用例 |
## 公开接口声明
Ascend Extension for PyTorch是PyTorch适配插件,支持用户使用PyTorch在昇腾设备上进行训练和推理。Ascend Extension for PyTorch适配后支持用户使用PyTorch原生接口。除了原生PyTorch接口外,Ascend Extension for PyTorch提供了部分自定义接口,包括自定义算子、亲和库和其他接口,支持PyTorch接口和自定义接口连接,具体可参见[《Ascend Extension for PyTorch自定义API参考》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/torchnpuCustomsapi/context/%E6%A6%82%E8%BF%B0.md)以及[《PyTorch原生接口清单》](https://www.hiascend.com/document/detail/zh/Pytorch/710/apiref/PyTorchNativeapi/ptaoplist_000003.html)。
参考[PyTorch社区公开接口规范](https://github.com/pytorch/pytorch/wiki/Public-API-definition-and-documentation),Ascend Extension for PyTorch提供了对外的自定义接口。如果一个函数看起来符合公开接口的标准且在文档中有展示,则该接口是公开接口。否则,使用该功能前可以在社区询问该功能是否确实是公开的或意外暴露的接口,因为这些未暴露接口将来可能会被修改或者删除。
Ascend Extension for PyTorch项目采用C++和Python联合开发,当前除Libtorch场景外正式接口只提供Python接口,在torch_npu的二进制包中动态库不直接提供服务,暴露的接口为内部使用,不建议用户使用。
## 通信安全加固
PyTorch分布式训练服务需要在设备间进行通信,通信开启的端口默认为全0侦听,为了降低安全风险,建议用户针对此场景进行安全加固,如使用iptables配置防火墙,在运行分布式训练开始前限制外部对分布式训练使用端口的访问,在运行分布式训练结束后清理防火墙规则。
1. 防火墙规则设定和移除参考脚本模板
- 防火墙规则设定,可参考如下脚本:
```
#!/bin/bash
set -x
# 要限制的端口号
port={端口号}
# 清除旧规则
iptables -D INPUT -p tcp -j {规则名}
iptables -F {规则名}
iptables -X {规则名}
# 创建新的规则链
iptables -t filter -N {规则名}
# 在多机场景下设定白名单,允许其他节点访问主节点的侦听端口
# 在规则链中添加允许特定IP地址范围的规则
iptables -t filter -A {规则名} -i eno1 -p tcp --dport $port -s {允许外部访问的IP} -j ACCEPT
# 屏蔽外部地址访问分布式训练端口
# 在PORT-LIMIT-RULE规则链中添加拒绝其他IP地址的规则
iptables -t filter -A {规则名} -i {要限制的网卡名} -p tcp --dport $port -j DROP
# 将流量传递给规则链
iptables -I INPUT -p tcp -j {规则名}
```
- 防火墙规则移除,可参考如下脚本:
```
#!/bin/bash
set -x
# 清除规则
iptables -D INPUT -p tcp -j {规则名}
iptables -F {规则名}
iptables -X {规则名}
```
2. 防火墙规则设定和移除参考脚本示例
1. 针对特定端口设定防火墙,脚本中端口号为要限制的端口,在PyTorch分布式训练中端口号请参考[通信矩阵信息](#通信矩阵信息);要限制的网卡名为服务器用于分布式通信使用的网卡,允许的外部访问的IP为分布式训练服务器的IP地址。网卡和服务器IP可以通过ifconfig查看,如下文回显的eth0为网卡名,192.168.1.1为服务器IP地址:
```
# ifconfig
eth0
inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::230:64ee:ef1a:c1a/64 Scope:Link
```
2. 假定服务器主节点地址192.168.1.1,另一台需要进行分布式训练的服务器为192.168.1.2,训练端口为29510。
- 防火墙规则设定,可参考如下脚本:
```
#!/bin/bash
set -x
# 设定侦听的端口
port=29510
# 清除旧规则
iptables -D INPUT -p tcp -j PORT-LIMIT-RULE
iptables -F PORT-LIMIT-RULE
iptables -X PORT-LIMIT-RULE
# 创建新的PORT-LIMIT-RULE规则链
iptables -t filter -N PORT-LIMIT-RULE
# 在多机场景下设定白名单,允许192.168.1.2访问主节点
# 在PORT-LIMIT-RULE规则链中添加允许特定IP地址范围的规则
iptables -t filter -A PORT-LIMIT-RULE -i eno1 -p tcp --dport $port -s 192.168.1.2 -j ACCEPT
# 屏蔽外部地址访问分布式训练端口
# 在PORT-LIMIT-RULE规则链中添加拒绝其他IP地址的规则
iptables -t filter -A PORT-LIMIT-RULE -i eth0 -p tcp --dport $port -j DROP
# 将流量传递给PORT-LIMIT-RULE规则链
iptables -I INPUT -p tcp -j PORT-LIMIT-RULE
```
- 防火墙规则移除,可参考如下脚本:
```
#!/bin/bash
set -x
# 清除规则
iptables -D INPUT -p tcp -j PORT-LIMIT-RULE
iptables -F PORT-LIMIT-RULE
iptables -X PORT-LIMIT-RULE
```
## 通信矩阵
PyTorch提供分布式训练能力,支持在单机和多机场景下进行训练,需要进行网络通信。其中PyTorch需要使用TCP进行通信,torch_npu使用CANN中HCCL在NPU设备间通信,通信端口见[通信矩阵信息](#通信矩阵信息)。用户需要注意并保障节点间通信网络安全,可以使用iptables等方式消减安全风险,可参考[通信安全加固](#通信安全加固)进行网络安全加固。
##### 通信矩阵信息
| 组件 | PyTorch | HCCL |
| --------------------- | ------------------------------------ | ------------------------------------ |
| 源设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
| 源IP | 设备地址IP | 设备地址IP |
| 源端口 | 操作系统自动分配,分配范围由操作系统的自身配置决定 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 目的设备 | 运行torch_npu进程的服务器 | 运行torch_npu进程的服务器 |
| 目的IP | 设备地址IP | 设备地址IP |
| 目的端口 (侦听) | 默认29500/29400,用户可以设定端口号 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 协议 | TCP | TCP |
| 端口说明 | 分布式场景下 <br> 1. torchrun/torch.distributed.launch <br> (1) backend为static时(默认该backend),目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 <br> (2) backend为c10d时,目的端口(默认29400)用于接收和发送数据,源端口用于接收和发送数据。使用rdzv_endpoint指定地址和端口号,格式为"地址:端口号" <br> 2. torch_npu_run:目的端口(默认29500)用于接收和发送数据,源端口用于接收和发送数据。使用master-addr指定地址,master-port指定端口 | 默认值为60000,取值范围[1024,65520]。用户可以通过HCCL_IF_BASE_PORT环境变量指定Host网卡起始端口号,配置后系统默认占用以该端口起始的16个端口 |
| 侦听端口是否可更改 | 是 | 是 |
| 认证方式 | 无认证方式 | 无认证方式 |
| 加密方式 | 无 | 无 |
| 所属平面 | 不涉及 | 不涉及 |
| 版本 | 所有版本 | 所有版本 |
| 特殊场景 | 无 | 无 |
| 备注 | 该通信过程由开源软件PyTorch控制,配置为PyTorch原生设置,可参考[PyTorch文档](https://pytorch.org/docs/stable/distributed.html#launch-utility)。源端口由操作系统自动分配,分配范围由操作系统的配置决定,例如ubuntu:采用/proc/sys/net/ipv4/ipv4_local_port_range文件指定,可通过cat /proc/sys/net/ipv4/ipv4_local_port_range或sysctl net.ipv4.ip_local_port_range查看 | 该通信过程由CANN中HCCL组件控制,torch_npu不进行控制,端口范围可参考[《环境变量参考》](https://www.hiascend.com/document/detail/zh/canncommercial/82RC1/maintenref/envvar/envref_07_0001.html)的“执行相关 > 集合通信 >HCCL_IF_BASE_PORT” |
## 漏洞机制说明
Ascend Extension for PyTorch 社区非常重视社区版本的安全性,专门设置了漏洞管理专员负责处理漏洞相关的事务,同时为了构建更安全的AI全流程工具链,我们也欢迎您一起参与。
### 漏洞处理流程
对于每一个安全漏洞,Ascend Extension for PyTorch 社区会安排人员进行跟踪和处理,漏洞处理的端到端流程如下图所示。
![漏洞处理流程](./figures/cve.png)
下面将重点解释漏洞上报、漏洞评估、漏洞披露的流程。
### 漏洞上报
您可以通过提交issue的方式联系 Ascend Extension for PyTorch 社区团队,我们将会第一时间安排安全漏洞专项人员向您联系。
注意,为了确保安全性,请不要在issue中描述涉及安全隐私的具体信息。
#### 上报响应
1. Ascend Extension for PyTorch 社区会在3个工作日内确认、分析、上报安全漏洞问题,同时启动安全处理流程。
2. Ascend Extension for PyTorch 安全团队在确认安全漏洞问题后,会对问题进行分发和跟进。
3. 在安全漏洞问题从分类、确定、修复和发布的过程中,我们会及时更新报告。
### 漏洞评估
业界普遍使用 CVSS 标准评估漏洞的严重性,Ascend Extension for PyTorch 在使用 CVSS v3.1 进行漏洞评估时,需要设定漏洞攻击场景,基于在该攻击场景下的实际影响进行评估。漏洞严重等级评估是指针对漏洞利用难易程度,以及利用后对机密性、完整性、可用性的影响进行评估,并生成一个评分值。
#### 漏洞评估标准
Ascend Extension for PyTorch 通过以下向量评估一个漏洞的严重等级:
- 攻击向量(AV):表示攻击的“远程性”以及如何利用此漏洞。
- 攻击复杂性(AC):讲述攻击执行的难度以及成功进行攻击需要哪些因素。
- 用户交互(UI):确定攻击是否需要用户参与。
- 所需的权限(PR):记录成功进行攻击所需的用户身份验证级别。
- 范围(S):确定攻击者是否可以影响具有不同权限级别的组件。
- 机密性(C):衡量信息泄露给非授权方后导致的影响程度。
- 完整性(I):衡量信息被篡改后导致的影响程度。
- 可用性(A):衡量用户在需要访问数据或服务时受影响的程度。
#### 评估原则
- 评估漏洞的严重等级,不是评估风险。
- 评估时必须基于攻击场景,且保证在该场景下,攻击者成功攻击后能对系统造成机密性、完整性、可用性影响。
- 当安全漏洞有多个攻击场景时,应以造成最大的影响,即 CVSS 评分最高的攻击场景为依据。
- 被嵌入调用的库存在漏洞,要根据该库在产品中的使用方式,确定漏洞的攻击场景后进行评估。
- 安全缺陷不能被触发或不影响 CIA(机密性、完整性、可用性),CVSS 评分为 0 分。
#### 评估步骤
评估漏洞严重等级时,可根据下述步骤进行操作:
1. 设定可能的攻击场景,基于攻击场景评分。
2. 确定漏洞组件(Vulnerable Component)和受影响组件(Impact Component)。
3. 选择基础指标的值。
- 可利用指标(攻击向量、攻击复杂度、所需权限、用户交互、范围)根据漏洞组件选择指标值。
- 影响指标(机密性、完整性、可用性)要么反映对漏洞组件的影响,要么反映对受影响组件影响,以结果最严重的为准。
#### 严重等级划分
| **严重等级(Severity Rating)** | **CVSS评分(Score)** | **漏洞修复时长** |
| ------------------------------- | --------------------- | ---------------- |
| 致命(Critical) | 9.0~10.0 | 7天 |
| 高(High) | 7.0~8.9 | 14天 |
| 中(Medium) | 4.0~6.9 | 30天 |
| 低(Low) | 0.1~3.9 | 30天 |
### 漏洞披露
安全漏洞修复后 Ascend Extension for PyTorch 社区会发布安全公告 (SA)以及安全说明(SN) ,安全公告内容包括该漏洞的技术细节、类型、上报人、CVE ID 以及受到该漏洞影响的版本和修复版本等信息。
为了保护 Ascend Extension for PyTorch 用户的安全,在进行调查、修复和发布安全公告之前, Ascend Extension for PyTorch 社区不会公开披露、讨论或确认 Ascend Extension for PyTorch 产品的安全问题。
### 附录
#### 安全公告(SA)
目前在维护版本,无安全漏洞
#### 安全说明(SN)
涉及第三方的开源组件部分漏洞说明:无
+85 -190
View File
@@ -1,190 +1,85 @@
OPEN SOURCE SOFTWARE NOTICE
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just "this product"). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
Warranty Disclaimer
THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
Copyright Notice and License Texts
Software: pytorch v2.6.0
Copyright notice:
Copyright (c) Advanced Micro Devices, Inc.
Copyright (c) Microsoft Corporation
Copyright (c) Bjorn Fahller
Copyright (c) 2001-2014 Python Software Foundation All Rights Reserved
Copyright (c) 2011-2013 NYU
Copyright (c) 1995-2011 by Fredrik Lundh
Copyright (c) Edward Z. Yang ezyang@mit.edu
Copyright (c) 2014- Facebook, Inc
Copyright (c) 2017 The Android Open Source Project
Copyright Python Software Foundation
Copyright (c) 2012 Massachusetts Institute of Technology
Copyright (c) 2018 Alex Rogozhnikov
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
Copyright (c) 2006 Idiap Research Institute
Copyright (c) 2011-2021, NVIDIA CORPORATION. All rights reserved
Copyright (c) 2015 Yangqing Jia All rights reserved
Copyright (c) Meta Platforms, Inc.
Copyright 2023-present Facebook. All Rights Reserved
Copyright (c) 2022 Apple Inc.
Copyright (c) 2005-2017, NumPy Developers. All rights reserved
Copyright (c) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, All rights reserved
Copyright (c) 2014, The Regents
Copyright (c) 2005-2010 ActiveState Software Inc.
Copyright Malte Skarupke 2017
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright 2005, Google Inc. All rights reserved
Copyright (c) Meta Platforms, Inc. and affiliates
Copyright (c) 2023, Advanced Micro Devices, Inc.
Copyright (c) 2022, Tri Dao
Copyright (c) 2005-2023 NVIDIA Corporation Built
Copyright (c) 2001-2002 Enthought, Inc. 2003-2019, SciPy Developers. All rights reserved
Copyright 2008 Google Inc. All rights reserved
Copyright (c) 2021, 2023-2024 Arm Limited
Copyright (c) 2003-2017 Josef Weidendorfer. All rights reserved
Copyright (c) 1997-2011 by Secret Labs AB
Copyright (c) 2016- Facebook, Inc
Copyright (c) 2014 Matthew Rocklin
Copyright (c) 2005-2022 NVIDIA Corporation Built
Copyright (c) Facebook, Inc.
Copyright 2019-2020 Kakao Brain
Copyright (c) 2000-2017 Julian Seward. All rights reserved
Copyright (c) 2005-2020 Rich Felker
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
Copyright (c) 2016 Facebook Inc.
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC All Rights Reserved
Copyright (c) 2012-2014 Deepmind Technologies
Copyright (c) 2012 Giovanni Garberoglio Interdisciplinary Laboratory
Copyright (c) 2024, Tri Dao
Copyright (c) Donald Stufft and individual contributors. All rights reserved
Copyright (c) 2018, Steven Moshier All rights reserved
Copyright (c) 2015 Google Inc. All rights reserved
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved
Copyright (c) 2010-2022 by Alex Clark and contributors
Copyright 2015 Google Inc. All Rights Reserved
Copyright (c) 2017 - 2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved
Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved
Copyright (c) 2016 manylinux
Copyright (c) 2017 - 2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright 2013-2014 RAD Game
Copyright (c) 2011-2019 Stephan Brumme. All rights reserved
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
Copyright (c) 2013 Eddy Petrisor
Copyright (c) 2023-2024 The ggml
Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation All Rights Reserved
Copyright 2004-present Facebook. All Rights Reserved
Copyright (c) 2010 ActiveState Software Inc.
Copyright (c) 2006 The Android Open Source Project
(c) Meta Platforms, Inc. and affiliates. All rights reserved
Copyright (c) 2023 Apple Inc.
Copyright (c) Microsoft Corporation. All rights reserved
Copyright 2015 The TensorFlow Authors. All Rights Reserved
Copyright (c) 2023, Tri Dao
Copyright 2022 Cruise LLC
Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved
Copyright (c) 2022 Cruise LLC. All rights reserved
Copyright (c) 2016-present, Facebook, Inc.
(c) Copyright John Maddock 2006
Copyright (c) 2011-2014 Idiap Research Institute
Copyright (c) 2014 Indiana University All rights reserved
copyright 2019 The TensorFlow Authors
Copyright (c) 2016-present, Facebook Inc. All rights reserved
License: BSD 3-Clause License
Copyright (c) ,
All rights reserved.
1. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
2. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
3. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
OPEN SOURCE SOFTWARE NOTICE
Please note we provide an open source software notice along with this product and/or this product firmware (in the following just “this product”). The open source software licenses are granted by the respective right holders. And the open source licenses prevail all other license information with regard to the respective open source software contained in the product, including but not limited to End User Software Licensing Agreement. This notice is provided on behalf of Huawei Technologies Co. Ltd. and any of its local subsidiaries which may have provided this product to you in your local country.
Warranty Disclaimer
THE OPEN SOURCE SOFTWARE IN THIS PRODUCT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE APPLICABLE LICENSES FOR MORE DETAILS.
Copyright Notice and License Texts
Software: pytorch 1.5.0
Copyright notice:
Copyright (c) 2016-present, Facebook, Inc.
Copyright (c) Facebook, Inc. and its affiliates.
Copyright 2006, Google Inc.
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
2017-2018 Advanced Micro Devices, Inc. and Facebook Inc. All rights reserved.
Copyright 2004-present Facebook. All Rights Reserved.
Copyright (c) 2018 MathInf GmbH, Thomas Viehmann
Copyright (c) 2014 Indiana University
Copyright (c) 2016, NVIDIA CORPORATION, All rights reserved
Copyright (C) 2012 Giovanni Garberoglio
Copyright 2015 Google Inc. All Rights Reserved.
Copyright (c) Facebook Inc. and Microsoft Corporation.
Copyright © 2001-2014 Python Software Foundation
All Rights Reserved
Copyright (c) 2014-2015 The Khronos Group Inc.
Copyright (c) 2006, Laurent Montel, montel@kde.org
Copyright 2013 Conrad Steenberg conrad.steenberg@gmail.com
Copyright (C) 2017 The Android Open Source Project
Copyright (c) 2010-2017 Benjamin Peterson
Copyright 2013-2014 RAD Game Tools and Valve Software
Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC
Copyright (c) 2008 - 2009 NVIDIA Corporation. All rights reserved.
Copyright (c) 2007-2009 Scientific Computing and Imaging Institute, University of Utah
(c) Facebook, Inc. and its affiliates. Confidential and proprietary.
Copyright (c) 2017 by Contributors
Copyright 2016 Facebook
Copyright (C) 2018 Marat Dukhan
Copyright (c) 2017-2018 Facebook Inc.
Copyright (c) 2017 Georgia Institute of Technology
Copyright (c) 2016 Microsoft
Copyright (c) 2014, 2015, The Regents of the University of California
Copyright (c) 2014, 2015, the respective contributors
Copyright (c) 2011-2014 Idiap Research Institute (Ronan Collobert)
Copyright (c) 2011-2012 NEC Laboratories America (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert,Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2006 Idiap Research Institute (Samy Bengio)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert,Samy Bengio, Johnny Mariethoz)
Copyright (c) 2016-2017, ARM Limited and Contributors
Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
Copyright (C) 2007-2017 Free Software Foundation, Inc.
Copyright Malte Skarupke 2017.
Copyright (C) 2011 - 2012 Andrzej Krzemienski.
Copyright (C) 2001-2019 Free Software Foundation, Inc.
Copyright (c) 1994 Hewlett-Packard Company
Copyright (c) 1996-1998 Silicon Graphics Computer Systems, Inc.
Copyright Michael Park, 2015-2017
Copyright (c) 2008 - 2012 The Khronos Group Inc.
Copyright (c) 2008-2013 The Khronos Group Inc.
Copyright (c) 2008-2012 The Khronos Group Inc.
Copyright (C) 2006 The Android Open Source Project
Copyright (c) 2016- Facebook, Inc (Adam Paszke)
Copyright (c) 2014- Facebook, Inc (Soumith Chintala)
Copyright (c) 2012-2014 Deepmind Technologies (Koray Kavukcuoglu)
Copyright (c) 2011-2013 NYU (Clement Farabet)
Copyright (c) 2006-2010 NEC Laboratories America (Ronan Collobert, Leon Bottou, Iain Melvin, Jason Weston)
Copyright (c) 2001-2004 Idiap Research Institute (Ronan Collobert, Samy Bengio, Johnny Mariethoz)
Copyright (c) 2016-present, Facebook Inc. All rights reserved.
Copyright (c) 2016 Facebook Inc.
Copyright (c) 2015 Google Inc.
Copyright (c) 2015 Yangqing Jia
Copyright(c) 2013, 2014, 2015, the respective contributors
Copyright(c) 2015, 2016 the respective contributors
Copyright (c) 2014, The Regents of the University of California (Regents)
Copyright (c) 2014, the respective contributors
Copyright (c) 2008-2015 The Khronos Group Inc.
Copyright (c) 2014-2017 The Regents of the University of California (Regents)
Copyright (c) 2014-2017, the respective contributors
Copyright (c) 2017 Microsoft
Copyright (c) 2017-present, Facebook, Inc.
Copyright (c) 2018-present, Facebook, Inc.
License: BSD 3-Clause License
Please see above.
-49
View File
@@ -1,49 +0,0 @@
# Benchmark output files (CSV results)
*.csv
# Profiler outputs
*.json
profile/
prof_output/
profiler_info.json
# Python cache
__pycache__/
*.py[cod]
*$py.class
*.so
# Torch/Inductor cache
traced_graph_cache/
# NPU/CUDA Profiler outputs
npu_profile/
cuda_profile/
profiling/
# fusion config
fusion_switch.cfg
# Temporary files
*.tmp
*.log
*.out
# IDE specific
.vscode/
.idea/
*.swp
*.swo
*~
# OS specific
.DS_Store
Thumbs.db
# External torchbenchmark dependency (cloned from GitHub)
# These directories are created by following the instructions in README.md:
# git clone https://github.com/pytorch/benchmark.git --depth=1
# The leading slash ensures we only ignore these directories in benchmarks/
# and not in other locations.
/benchmark/
/torchbenchmark/
-130
View File
@@ -1,130 +0,0 @@
# Torchbenchmark
## 简介
为了评测图模式能力,pytorch社区在CI HUD中提供了图模式应用在torchbench仓库的多个模型的加速效果。参考社区的实现,benchmarks提供了对部分指定模型的支持。用户可按照此README进行NPU图模式测试。
## Torchbench
## 准备环境
1. 安装requirements.txt中的依赖包
```shell
pip install -r requirements.txt
```
2. 下载pytorch/benchmark源码,并切换至指定commit id
```shell
git clone https://github.com/pytorch/benchmark.git --depth=1
cd benchmark
git remote set-branches origin '9910b31cc17d175a781412fd9ca6f18a4ee04610'
git fetch --depth 1 origin 9910b31cc17d175a781412fd9ca6f18a4ee04610
git checkout 9910b31cc17d175a781412fd9ca6f18a4ee04610
cd ..
```
## 准备数据集
1. 部分模型需要少量数据集,名单如下
```
INPUT_TARBALLS:
# index file for S3 storage of the input data
- pytorch_stargan_inputs.tar.gz
- LearningToPaint_inputs.tar.gz
- speech_transformer_inputs.tar.gz
```
2. 下载数据集可以使用下方URL
```
https://ossci-datasets.s3.amazonaws.com/torchbench/data/<TARBALL_NAME>
```
例如,下载pytorch_stargan_inputs数据集,可以使用
```
https://ossci-datasets.s3.amazonaws.com/torchbench/data/pytorch_stargan_inputs.tar.gz
```
3. 下载后的数据集放到指定目录下,以pytorch_stargan_inputs.tar.gz为例
```shell
# 创建.data/目录
cd ./benchmark/torchbenchmark/data/
mkdir .data/
# 将数据集移动到./benchmark/torchbenchmark/data/.data目录下
cd ../../../
cp your/path/to/dataset/pytorch_stargan_inputs.tar.gz ./benchmark/torchbenchmark/data/.data
# 解压数据集
cd ./benchmark/torchbenchmark/data/
tar -xvzf ./benchmark/torchbenchmark/data/.data/pytorch_stargan_inputs.tar.gz
```
## 运行测试
1. 精度和端到端总时间验证
```shell
# 不使能--only,默认运行torchbench_models_list.txt目录下的所有模型
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50
# 使能--only,运行指定模型
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --only BERT_pytorch --iterations 50
```
执行上述命令后,会在终端界面分别打印出模型执行(eager模式和图模式)的单步"端到端时间"、单步loss、"端到端时间"平均值以及eager模式和图模式精度比较的结果(pass_accuracy or fail_accuracy)
2. 编译总时间验证
```shell
# 添加参数--dump-compile-time,会在模型测试结束后输出编译时间的测量结果
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50 --dump-compile-time
```
执行上述命令后,会在终端界面打印出图模式下的算子编译时间
3. 算子总时间验证
算子时间验证需要开启profile工具,添加参数`--enable-profiler`,profile结果默认输出路径为`./profile`,用户指定输出路径可使用参数`--prof-output-path`。
```shell
# 不指定profile输出路径
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50 --enable-profiler
# 指定profile输出路径
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50 --enable-profiler --prof-output-path 'your/path/for/profile/output/'
```
`./profile`下的目录结构示例如下,`step_trace_time.csv`文件中记录了模型执行(eager模式和图模式)的单步算子时间
```
./profile
├── BERT_pytorch
│ ├── compile
│ │ └── localhost.localdomain_xxxx_ascend_pt
│ │ └── ASCEND_PROFILER_OUTPUT
| | └── step_trace_time.csv
│ └── eager
│ └── localhost.localdomain_xxxx_ascend_pt
│ └── ASCEND_PROFILER_OUTPUT
| └── step_trace_time.csv
| ······
```
4. NPU图模式后端指定
当前NPU图模式后端通过`--npu-backend`参数指定,支持`mlir`、`dvm`、`triton`(triton-ascend)三种模式,不显示指定会默认选择三种模式中端到端时间加速比最大的图模式后端,使用示例如下
```shell
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --npu-backend mlir --only BERT_pytorch --iterations 50
```
## 结果展示
1. 执行下述命令,测试精度、编译时间、端到端总时间,并保存日志
```shell
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50 --dump-compile-time 2>&1 | tee models.log
```
2. 执行下述命令,打开profile,获取算子总时间
```shell
python3 torchbench.py --accuracy --cold-start-latency --train --float32 --backend inductor --iterations 50 --enable-profiler
```
3. 执行下述命令,获得模型的测试结果,默认输出到`./analysis.xlsx`文件中
```shell
python3 extract_log.py --log_file models.log
```
4. `./analysis.xlsx`文件的基本内容如下,展示了模型名称,图模式与eager模式的精度比较结果,算子编译时间(ms),eager模式的端到端时间(ms),图模式的端到端时间(ms),端到端时间加速比,eager模式的算子时间(ms),图模式的算子时间(ms),算子时间加速比
| model_name | accuracy | op_compile_time | eager_E2E_avg_time | compile_E2E_avg_time | E2E_speed_up_rate | eager_OP_avg_time | compile_OP_avg_time | OP_speed_up_rate |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| BERT_pytorch | pass_accuracy | 41055.906 | 48.49 | 20.26 | 2.393385982 | 20.399543 | 17.4955115 | 1.16598723 |
File diff suppressed because it is too large Load Diff
-196
View File
@@ -1,196 +0,0 @@
import argparse
from collections import defaultdict
from pathlib import Path
import re
import pandas as pd
def extract_log_info(log_file, profile_dir='./profile', output_file='log_analysis.xlsx'):
"""
提取日志文件中各模型的训练时间信息和profile数据
Args:
log_file: 日志文件路径
profile_dir: profile数据目录路径
output_file: 输出Excel文件路径
"""
# 模式匹配
# 修改1: 同时支持npu和cuda
model_pattern = r'(npu|cuda)\s+train\s+(\S+)'
eager_pattern = r'eager.*avg step time:\s*([\d\.]+)\s*ms'
compile_pattern = r'compile.*avg step time:\s*([\d\.]+)\s*ms'
# 模式匹配:算子编译时间
op_compile_time_pattern = r'op_compile_time:\s*([\d\.]+)\s*ms'
# 存储结果
data = defaultdict(lambda: {
'accuracy': None, # 修改2: 存储完整的精度校验日志
'eager_E2E_avg_time': None,
'compile_E2E_avg_time': None,
'op_compile_time': None,
'eager_OP_avg_time': None,
'compile_OP_avg_time': None
})
current_model = None
in_compile_block = False
compile_block_lines = []
with open(log_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
for _, line in enumerate(lines):
# 匹配模型名
model_match = re.search(model_pattern, line)
if model_match:
# 处理上一个模型的compile块日志
if current_model and in_compile_block and compile_block_lines:
# 提取pass_accuracy日志
for log_line in compile_block_lines:
if 'pass_accuracy' in log_line:
data[current_model]['accuracy'] = log_line.strip()
break
# 提取op_compile_time
for log_line in compile_block_lines:
op_compile_match = re.search(op_compile_time_pattern, log_line)
if op_compile_match:
data[current_model]['op_compile_time'] = float(op_compile_match.group(1))
break
# 重置状态
current_model = model_match.group(2) # 第二个分组是模型名
in_compile_block = False
compile_block_lines = []
continue
# 匹配eager模式时间
if current_model:
eager_match = re.search(eager_pattern, line)
if eager_match:
data[current_model]['eager_E2E_avg_time'] = float(eager_match.group(1))
# 匹配compile模式时间
compile_match = re.search(compile_pattern, line)
if compile_match:
data[current_model]['compile_E2E_avg_time'] = float(compile_match.group(1))
in_compile_block = True
compile_block_lines = [] # 开始收集compile块日志
# 收集compile块的日志
if current_model and in_compile_block:
compile_block_lines.append(line)
# 处理最后一个模型的compile块日志
if current_model and in_compile_block and compile_block_lines:
for log_line in compile_block_lines:
if 'pass_accuracy' in log_line:
data[current_model]['accuracy'] = log_line.strip()
break
for log_line in compile_block_lines:
op_compile_match = re.search(op_compile_time_pattern, log_line)
if op_compile_match:
data[current_model]['op_compile_time'] = float(op_compile_match.group(1))
break
# 需求3: 读取profile目录中的step_trace_time.csv文件
profile_path = Path(profile_dir)
if profile_path.exists():
for model_dir in profile_path.iterdir():
if model_dir.is_dir():
model_name = model_dir.name
# 读取eager模式下的step_trace_time.csv
# 修改3: 自动获取下一级目录
eager_dir = model_dir / 'eager'
if eager_dir.exists() and eager_dir.is_dir():
# 获取eager目录下的第一个子目录
eager_subdirs = list(eager_dir.iterdir())
if eager_subdirs:
eager_subdir = eager_subdirs[0] # 假设只有一个子目录
eager_csv_path = eager_subdir / 'ASCEND_PROFILER_OUTPUT' / 'step_trace_time.csv'
if eager_csv_path.exists():
try:
eager_df = pd.read_csv(eager_csv_path, sep=',')
if 'Computing' in eager_df.columns:
data[model_name]['eager_OP_avg_time'] = eager_df['Computing'].mean() / 1e3
else:
print(f"警告: {eager_csv_path} 中没有Computing列")
except Exception as e:
print(f"读取{eager_csv_path}时出错: {e}")
# 读取compile模式下的step_trace_time.csv
compile_dir = model_dir / 'compile'
if compile_dir.exists() and compile_dir.is_dir():
# 获取compile目录下的第一个子目录
compile_subdirs = list(compile_dir.iterdir())
if compile_subdirs:
compile_subdir = compile_subdirs[0] # 假设只有一个子目录
compile_csv_path = compile_subdir / 'ASCEND_PROFILER_OUTPUT' / 'step_trace_time.csv'
if compile_csv_path.exists():
try:
compile_df = pd.read_csv(compile_csv_path, sep=',')
if 'Computing' in compile_df.columns:
data[model_name]['compile_OP_avg_time'] = compile_df['Computing'].mean() / 1e3
else:
print(f"警告: {compile_csv_path} 中没有Computing列")
except Exception as e:
print(f"读取{compile_csv_path}时出错: {e}")
else:
print(f"警告: profile目录不存在: {profile_dir}")
# 转换为DataFrame
df = pd.DataFrame.from_dict(data, orient='index')
df.index.name = 'model_name'
df.reset_index(inplace=True)
# 计算速度提升率
# 1. 计算E2E_speed_up_rate = eager_E2E_avg_time / compile_E2E_avg_time
# 2. 计算OP_speed_up_rate = eager_OP_avg_time / compile_OP_avg_time
df['E2E_speed_up_rate'] = df.apply(
lambda row: row['eager_E2E_avg_time'] / row['compile_E2E_avg_time']
if row['compile_E2E_avg_time'] and row['compile_E2E_avg_time'] != 0 else None,
axis=1
)
df['OP_speed_up_rate'] = df.apply(
lambda row: row['eager_OP_avg_time'] / row['compile_OP_avg_time']
if row['compile_OP_avg_time'] and row['compile_OP_avg_time'] != 0 else None,
axis=1
)
# 重排列顺序,使相关列更清晰
column_order = [
'model_name', 'accuracy', 'op_compile_time',
'eager_E2E_avg_time', 'compile_E2E_avg_time', 'E2E_speed_up_rate',
'eager_OP_avg_time', 'compile_OP_avg_time', 'OP_speed_up_rate'
]
existing_columns = [col for col in column_order if col in df.columns]
df = df[existing_columns + [col for col in df.columns if col not in existing_columns]]
# 保存到Excel
df.to_excel(output_file, index=False)
return df
def main():
parser = argparse.ArgumentParser(description='提取日志文件中的训练时间信息和profile数据')
parser.add_argument('--log_file', required=True, help='日志文件路径')
parser.add_argument('--profile_dir', default='./profile', help='profile数据目录路径,默认为./profile')
parser.add_argument('--output_file', default='analysis.xlsx', help='输出Excel文件路径,默认为log_analysis.xlsx')
args = parser.parse_args()
result = extract_log_info(
log_file=args.log_file,
profile_dir=args.profile_dir,
output_file=args.output_file
)
print(f"提取完成,共找到{len(result)}个模型")
print("\n提取结果:")
print(result.head())
# 使用示例
if __name__ == "__main__":
main()
@@ -1,170 +0,0 @@
[
{
"model": "BERT_pytorch",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 4.697522816166884
},
{
"model": "LearningToPaint",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 2.2519754170324844
},
{
"model": "alexnet",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 1.544836956521739
},
{
"model": "dcgan",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.6366279069767442
},
{
"model": "densenet121",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 4.018036529680366
},
{
"model": "hf_Albert",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 3.03486083778465
},
{
"model": "hf_Bart",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.1046712802768166
},
{
"model": "hf_Bert",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 2.2436246595692
},
{
"model": "hf_DistilBert",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.006595218466612
},
{
"model": "hf_T5_large",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.9116852286789403
},
{
"model": "lennard_jones",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.3333333333333333
},
{
"model": "mobilenet_v2",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.623713305375524
},
{
"model": "nvidia_deeprecommender",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.2717948717948715
},
{
"model": "phlippe_densenet",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 4.225296442687747
},
{
"model": "phlippe_resnet",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.7964743589743586
},
{
"model": "pytorch_stargan",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.235414534288639
},
{
"model": "pytorch_unet",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 1.0518394648829432
},
{
"model": "resnet152",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 4.565473209814722
},
{
"model": "resnet18",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.358640636297903
},
{
"model": "resnet50",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.446224256292906
},
{
"model": "resnext50_32x4d",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 6.718421052631579
},
{
"model": "shufflenet_v2_x1_0",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 3.387612387612388
},
{
"model": "squeezenet1_1",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 2.1103965702036445
},
{
"model": "timm_resnest",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.334689134224288
},
{
"model": "timm_vision_transformer",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 3.878102189781022
},
{
"model": "timm_vovnet",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 2.2661481230977345
},
{
"model": "tts_angular",
"hardware": "npu",
"mode": "mlir",
"E2E_speed_up_rate": 0.9578480310593456
},
{
"model": "vgg16",
"hardware": "npu",
"mode": "dvm",
"E2E_speed_up_rate": 1.1957267211817464
}
]
-659
View File
@@ -1,659 +0,0 @@
import importlib
import json
import logging
import os
import sys
from typing import Optional, Tuple, Type, Union
import torch
import torch.nn as nn
import torchair
import common
import torch_npu
from torch_npu.dynamo.torchair._utils.path_manager import PathManager
log = logging.getLogger(__name__)
_patch_table = {}
def register_patch(*model_names):
def meta_decorator(fn):
for model_name in model_names:
_patch_table[model_name] = fn
return fn
return meta_decorator
def check_transformers_version(required_version):
import transformers
if transformers.__version__ != required_version:
log.warning(f"transformers.__version__ is not equal to {required_version}, which may cause error patch.")
def use_aclnn():
os.environ["USE_ACLOP"] = "0"
def _hf_t5_mt5_conditionalgeneration_forward_new(
self,
hidden_states,
mask=None,
key_value_states=None,
position_bias=None,
past_key_value=None,
layer_head_mask=None,
query_length=None,
use_cache=False,
output_attentions=False,
):
batch_size, seq_length = hidden_states.shape[:2]
real_seq_length = seq_length
if past_key_value is not None:
if len(past_key_value) != 2:
raise ValueError(f"past_key_value should have 2 past states. Got {len(past_key_value)} past states")
real_seq_length += past_key_value[0].shape[2] if query_length is None else query_length
key_length = real_seq_length if key_value_states is None else key_value_states.shape[1]
def shape(states):
return states.view(batch_size, -1, self.n_heads, self.key_value_proj_dim).transpose(1, 2)
def unshape(states):
return states.transpose(1, 2).contiguous().view(batch_size, -1, self.inner_dim)
def project(hidden_states, proj_layer, key_value_states, past_key_value):
if key_value_states is None:
hidden_states = shape(proj_layer(hidden_states))
elif past_key_value is None:
hidden_states = shape(proj_layer(key_value_states))
if past_key_value is not None:
if key_value_states is None:
hidden_states = torch.cat([past_key_value, hidden_states], dim=2)
elif past_key_value.shape[2] != key_value_states.shape[1]:
hidden_states = shape(proj_layer(key_value_states))
else:
hidden_states = past_key_value
return hidden_states
query_states = shape(self.q(hidden_states))
key_states = project(
hidden_states, self.k, key_value_states, past_key_value[0] if past_key_value is not None else None
)
value_states = project(
hidden_states, self.v, key_value_states, past_key_value[1] if past_key_value is not None else None
)
scores = torch.matmul(query_states, key_states.transpose(3, 2))
def process_position_bias():
if not self.has_relative_attention_bias:
position_bias = torch.zeros(
(1, self.n_heads, real_seq_length, key_length), device=scores.device, dtype=scores.dtype
)
if self.gradient_checkpointing and self.training:
position_bias.requires_grad = True
else:
position_bias = self.compute_bias(real_seq_length, key_length, device=scores.device)
if past_key_value is not None:
position_bias = position_bias[:, :, -hidden_states.size(1):, :]
if mask is not None:
position_bias = position_bias + mask
return position_bias
if position_bias is None:
position_bias = process_position_bias()
if self.pruned_heads:
mask = torch.ones(position_bias.shape[1])
mask[list(self.pruned_heads)] = 0
position_bias_masked = position_bias[:, mask.bool()]
else:
position_bias_masked = position_bias
# Only patch here, src code: [scores += position_bias_masked]
# Prevent from two continuous _to_copy.
scores = scores.float() + position_bias_masked
attn_weights = nn.functional.softmax(scores.float(), dim=-1).type_as(scores)
attn_weights = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
if layer_head_mask is not None:
attn_weights = attn_weights * layer_head_mask
attn_output = unshape(torch.matmul(attn_weights, value_states))
attn_output = self.o(attn_output)
present_key_value_state = (key_states, value_states) if (self.is_decoder and use_cache) else None
outputs = (attn_output,) + (present_key_value_state,) + (position_bias,)
if output_attentions:
outputs = outputs + (attn_weights,)
return outputs
@register_patch("LearningToPaint")
def _patch_model_1():
# For model LearningToPaint.
from torchbenchmark.models import LearningToPaint
USE_DEVICE = torch.cuda.is_available() or torch_npu.npu.is_available()
LearningToPaint.baseline.utils.util.USE_CUDA = USE_DEVICE
@register_patch("hf_T5", "hf_T5_base")
def _patch_model_3():
# For model hf_T5 and hf_T5_base.
# In these models, accuracy check will fail because in the model's block [T5Attention],
# two continuous _to_copy are invoked: the first _to_copy converts Tensor to half
# and the second converts it to float. In eager, there will be a loss of precision.
# But in graph, there will be a fusion pass to prevent it happens, causing acc check fail.
try:
from transformers.models.t5.modeling_t5 import T5Attention
except ImportError:
log.warning("Import transformers failed or could not get T5Attention "
"from module transformers.models.t5.modeling_t5")
return
check_transformers_version("4.36.0")
T5Attention.forward = _hf_t5_mt5_conditionalgeneration_forward_new
@register_patch("fastNLP_Bert")
def _patch_model_5():
os.environ['BREAK_GRAPH_OP_LIST'] = 'NN.LINEAR'
# None-public interface, just for test.
# This env is added after torchair's init,
# so need to call break_graph patch again,
torchair._utils.npu_patch_break_graph()
@register_patch("hf_Longformer")
def _patch_model_6():
"""
Hf_Longformer failed accurazy test because of discontiguous memory.
Solving the problem by adding .contiguous() after .view() and .as_strided in LongformerSelfAttention._chunk.
This patch would be removed in the near future.
"""
# close AddLayerNormFusionPass
close_view_optimise()
module_spec = importlib.util.find_spec("transformers")
if module_spec is None:
return
from transformers.models.longformer import LongformerSelfAttention
src_chunk = LongformerSelfAttention._chunk
def _chunk(cls, hidden_states, window_overlap, onnx_export: bool = False):
if not onnx_export:
hidden_states = hidden_states.view(
hidden_states.size(0),
torch.div(hidden_states.size(1), (window_overlap * 2), rounding_mode="trunc"),
window_overlap * 2,
hidden_states.size(2),
).contiguous()
chunk_size = list(hidden_states.size())
chunk_size[1] = chunk_size[1] * 2 - 1
chunk_stride = list(hidden_states.stride())
chunk_stride[1] = chunk_stride[1] // 2
return hidden_states.as_strided(size=chunk_size, stride=chunk_stride).contiguous()
return src_chunk(hidden_states, window_overlap, True)
LongformerSelfAttention._chunk = _chunk
@register_patch("soft_actor_critic")
def _patch_model_7():
"""
soft_actor_critic failed accurazy test because of discontiguous memory.
Solving the problem by adding .contiguous() in soft_actor_critic/net.py line:242 SquashedNormal.__init__
This patch would be removed in the near future.
"""
from torchbenchmark.models.soft_actor_critic.nets import StochasticActor, SquashedNormal, BetaDist
import torch.nn.functional as F
def new_forward(self, state):
x = F.relu(self.fc1(state))
x = F.relu(self.fc2(x))
out = self.fc3(x)
mu, log_std = out.chunk(2, dim=1)
if self.dist_impl == "pyd":
log_std = torch.tanh(log_std)
log_std = self.log_std_low + 0.5 * (
self.log_std_high - self.log_std_low
) * (log_std + 1)
std = log_std.exp()
dist = SquashedNormal(mu.contiguous(), std.contiguous())
elif self.dist_impl == "beta":
out = 1.0 + F.softplus(out)
alpha, beta = out.chunk(2, dim=1)
dist = BetaDist(alpha, beta)
return dist
StochasticActor.forward = new_forward
@register_patch("dcgan", "mobilenet_v2", "phlippe_resnet", "shufflenet_v2_x1_0", "squeezenet1_1", "vgg16",
"alexnet", "densenet121", "maml_omniglot")
def _patch_model_8():
"""
close conv amp for some model only in accuracy mode.
This patch would be removed in the near future.
"""
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
from torch.nn.modules.conv import Conv2d
def conv2d_amp_disabled(self, x):
with torch.npu.amp.autocast(enabled=False):
return self._conv_forward(x, self.weight, self.bias)
Conv2d.forward = conv2d_amp_disabled
@register_patch("timm_nfnet")
def _patch_model_9():
# close conv amp for timm_nfnet only in accuracy mode.
# Increase the batch_size to a larger size 16,
# to mitigate the impact of BatchNorm's tolerance on convolution
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
try:
import timm
import torch.nn.functional as F
from timm.layers.std_conv import ScaledStdConv2dSame
from timm.layers.padding import pad_same
except ImportError:
log.warning("Import timm failed or could not get ScaledStdConv2dSame"
"from module timm.layers.std_conv.ScaledStdConv2dSame")
return
if timm.__version__ != '0.9.16':
log.warning("timm.__version__ is not equal to 0.9.16, which may cause error patch.")
def new_forward(self, x):
if self.same_pad:
x = pad_same(x, self.kernel_size, self.stride, self.dilation)
weight = F.batch_norm(
self.weight.reshape(1, self.out_channels, -1), None, None,
weight=(self.gain * self.scale).view(-1),
training=True, momentum=0., eps=self.eps).reshape_as(self.weight)
with torch.npu.amp.autocast(enabled=False):
return F.conv2d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)
ScaledStdConv2dSame.forward = new_forward
try:
from torchbenchmark.models.timm_nfnet import Model
except ImportError:
log.warning("Import Model failed or could not find timm_nfnet"
"from module torchbenchmark.models.timm_nfnet.Model")
return
def new__init(self, test, device, jit=False, batch_size=None, extra_args=None):
super(Model, self).__init__(test=test, model_name='dm_nfnet_f0',
device=device, batch_size=16, extra_args=extra_args)
Model.__init__ = new__init
@register_patch("nvidia_deeprecommender")
def _patch_model_10():
try:
from torch_npu.contrib import transfer_to_npu
import torch_npu._inductor
except ImportError:
log.warning("NPU_FlAG is False!")
return
try:
from torchbenchmark.models.nvidia_deeprecommender.nvtrain import DeepRecommenderTrainBenchmark
except ImportError:
log.warning("Import nvidia_deeprecommender failed or could not get DeepRecommenderTrainBenchmark"
"from module torchbenchmark.models.nvidia_deeprecommender.nvtrain.DeepRecommenderTrainBenchmark")
return
def new_init(self, device="cpu", jit=False, batch_size=256, process_command_line=False):
self.TrainInit("cuda", jit, batch_size, process_command_line)
DeepRecommenderTrainBenchmark.__init__ = new_init
@register_patch("functorch_dp_cifar10")
def _patch_model_11():
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
try:
from torchbenchmark.models.functorch_dp_cifar10 import Model
import torchvision.models as models
except ImportError:
log.warning("import torchvision fail or could not get Model from module "
"torchbenchmark.models.functorch_dp_cifar10")
return
def new_init(self, test, device, batch_size=None, extra_args=None):
if extra_args is None:
extra_args = []
super(Model, self).__init__(test=test, device=device, batch_size=32, extra_args=extra_args)
self.model = models.__dict__['resnet18'](
pretrained=False, norm_layer=(lambda c: nn.GroupNorm(min(c, 32), c)))
self.model = self.model.to(device)
self.example_inputs = (
torch.randn((self.batch_size, 3, 32, 32), device=self.device),
)
self.example_target = torch.randint(0, 10, (self.batch_size,), device=self.device)
self.optimizer = torch.optim.Adam(self.model.parameters(), lr=0.001)
self.criterion = nn.CrossEntropyLoss()
Model.__init__ = new_init
def create_fusion_switch_file():
fusion_config = {}
fusion_config.setdefault("Switch", {}).setdefault("GraphFusion", {})["AddLayerNormFusionPass"] = "off"
fusion_config_file = os.path.join(os.getcwd(), "fusion_switch.cfg")
PathManager.check_path_writeable_and_safety(fusion_config_file)
with os.fdopen(os.open(fusion_config_file, os.O_WRONLY | os.O_CREAT, mode=600), 'w') as f:
json.dump(fusion_config, f)
config = torchair.CompilerConfig()
config.fusion_config.fusion_switch_file = fusion_config_file
def clean_fusion_config_file():
PathManager.remove_file_safety(fusion_config_file)
from common import register_callback
register_callback(clean_fusion_config_file)
return config
def close_view_optimise():
config = create_fusion_switch_file()
config.experimental_config.enable_view_optimize = False
npu_backend = torchair.get_npu_backend(compiler_config=config)
def compile_with_view_switch(args):
return torch._dynamo.optimize(npu_backend, nopython=args.nopython)
common.compile_with_backend = compile_with_view_switch
def close_add_layer_norm_fusion_pass():
npu_backend = torchair.get_npu_backend(compiler_config=create_fusion_switch_file())
def compile_with_fusion_switch(args):
return torch._dynamo.optimize(npu_backend, nopython=args.nopython)
common.compile_with_backend = compile_with_fusion_switch
@register_patch("moco")
def _patch_model_13():
from argparse import Namespace
import torch.distributed as dist
try:
from torch_npu.contrib import transfer_to_npu
except ImportError:
log.warning("NPU_FlAG is False!")
return
try:
import torchvision.models as models
from torchbenchmark.models.moco import Model
from torchbenchmark.models.moco.moco.builder import MoCo
except ImportError:
log.warning("import torchvision fail or could not get Model,MoCo from module torchbenchmark.models.moco ")
return
def new_init(self, test, device, batch_size=None, extra_args=None):
if extra_args is None:
extra_args = []
super(Model, self).__init__(test=test, device=device, batch_size=batch_size, extra_args=extra_args)
self.opt = Namespace(**{
"arch": "resnet50", "epochs": 2, "start_epoch": 0, "lr": 0.03, "schedule": [120, 160], "momentum": 0.9,
"weight_decay": 1e-4, "gpu": None, "moco_dim": 128, "moco_k": 32000, "moco_m": 0.999, "moco_t": 0.07,
"mlp": False, "aug_plus": False, "cos": False, "fake_data": True, "distributed": True,
})
try:
dist.init_process_group(backend="nccl", init_method="tcp://localhost:10001", world_size=1, rank=0)
except RuntimeError:
pass # already initialized?
if device == "cpu":
raise NotImplementedError("DistributedDataParallel/allgather requires npu")
self.model = MoCo(
models.__dict__[self.opt.arch],
self.opt.moco_dim,
self.opt.moco_k,
self.opt.moco_m,
self.opt.moco_t,
self.opt.mlp,
)
self.model.to(self.device)
# Define loss function (criterion) and optimizer
self.criterion = nn.CrossEntropyLoss().to(self.device)
self.optimizer = torch.optim.SGD(
self.model.parameters(),
self.opt.lr,
momentum=self.opt.momentum,
weight_decay=self.opt.weight_decay,
)
def collate_train_fn(data):
ind = data[0]
return [batches[2 * ind], batches[2 * ind + 1]], 0
batches = []
for _ in range(4):
batches.append(torch.randn(self.batch_size, 3, 224, 224).to(self.device))
self.example_inputs = torch.utils.data.DataLoader(range(2), collate_fn=collate_train_fn)
if torch.cuda.is_available():
for _, (images, _) in enumerate(self.example_inputs):
images[0] = images[0].cuda(device=0, non_blocking=True)
images[1] = images[1].cuda(device=0, non_blocking=True)
else:
for _, (images, _) in enumerate(self.example_inputs):
images[0] = images[0].npu(device=0, non_blocking=True)
images[1] = images[1].npu(device=0, non_blocking=True)
Model.__init__ = new_init
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
try:
import torchvision
from torchvision.models.resnet import ResNet
except ImportError:
log.warning("Import torchvision failed or could not get ResNet "
"from module torchvision.models.resnet")
return
def _new_forward_impl(self, x):
# See note [TorchScript super()]
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
@torch.compiler.disable(recursive=False)
def avgpool(x):
x = self.avgpool(x)
return x
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
ResNet._forward_impl = _new_forward_impl
@register_patch("timm_vovnet")
def _patch_model_14():
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
import torch.nn.functional as F
from torch.nn.modules.conv import Conv2d
from torch.nn.modules.pooling import AdaptiveAvgPool2d
from torch.nn.modules.linear import Linear
def conv2d_amp_disabled(self, x):
with torch.npu.amp.autocast(enabled=False):
return self._conv_forward(x, self.weight, self.bias)
Conv2d.forward = conv2d_amp_disabled
def adaptive_avgpool_amp_disabled(self, x):
with torch.npu.amp.autocast(enabled=False):
return F.adaptive_avg_pool2d(x.float(), self.output_size)
AdaptiveAvgPool2d.forward = adaptive_avgpool_amp_disabled
def linear_amp_disabled(self, x):
with torch.npu.amp.autocast(enabled=False):
return F.linear(x, self.weight, self.bias)
Linear.forward = linear_amp_disabled
@register_patch("resnet50", "resnet152", "resnext50_32x4d")
def _patch_model_18():
if {"--only", "--amp", "--accuracy"} <= set(sys.argv):
try:
import torchvision.models as models
except ImportError:
log.warning("Import torchvision failed or could not get models "
"from module torchvision.models")
return
if 'resnet50' in sys.argv:
from torchbenchmark.models.resnet50 import Model
model = 'resnet50'
weight = models.ResNet50_Weights.IMAGENET1K_V1
elif 'resnet152' in sys.argv:
from torchbenchmark.models.resnet152 import Model
model = 'resnet152'
weight = models.ResNet152_Weights.IMAGENET1K_V1
elif 'resnext50_32x4d' in sys.argv:
from torchbenchmark.models.resnext50_32x4d import Model
model = 'resnext50_32x4d'
weight = models.ResNeXt50_32X4D_Weights.IMAGENET1K_V1
else:
raise RuntimeError("args.only expect model resnet50, resnet152 or resnext50_32x4d")
def new_init(self, test, device, batch_size=None, extra_args=None):
if extra_args is None:
extra_args = []
super(Model, self).__init__(model_name=model, test=test, device=device,
batch_size=32, weights=weight,
extra_args=extra_args)
Model.__init__ = new_init
@register_patch("torch_multimodal_clip")
def _patch_model_19():
try:
from torchmultimodal.models.clip.text_encoder import CLIPTextEncoder
except ImportError:
log.warning("from torchmultimodal.models.clip.text_encoder import CLIPTextEncoder failed")
return
def new_forward(self, text, return_hidden_state: bool = False):
if text.size(1) != self.context_length:
raise ValueError(
f"length of input should be {self.context_length} but found {text.size(1)}"
)
embeddings = self.token_embedding(text)
embeddings = embeddings + self.positional_embedding
embeddings = embeddings.permute(1, 0, 2)
embeddings = self.encoder(embeddings, mask=self.mask, is_causal=True)
# [n_ctx, bs, transformer.width] -> [bs, n_ctx, transformer.width]
embeddings = torch.permute(embeddings, (1, 0, 2))
hidden_state = self.ln_final(embeddings)
hidden_state = hidden_state * 1 # pass
if return_hidden_state:
return hidden_state
projected_embeddings = self.projection(
hidden_state[torch.arange(hidden_state.shape[0], device="npu"), text.argmax(dim=-1)]
)
return projected_embeddings
CLIPTextEncoder.forward = new_forward
def patch_remove_ops_from_generate_list(op_names=None):
try:
import torch
from torch_npu._inductor.ascend_npu_ir.ascend_npu_ir import config as anir_config
if not op_names:
print("[patch] No op names provided, nothing to do.")
return
for name in op_names:
parts = name.split(".")
op = torch.ops
for p in parts:
op = getattr(op, p)
if op in anir_config.GENERATE_LIST:
anir_config.GENERATE_LIST.remove(op)
print(f"[patch] Successfully removed {name} from GENERATE_LIST.")
else:
print(f"[patch] {name} not found in GENERATE_LIST (maybe already removed).")
except Exception as e:
print(f"[patch] Failed to modify GENERATE_LIST: {e}")
@register_patch("speech_transformer")
def _patch_model_20():
import numpy as np
try:
from torchbenchmark.models.speech_transformer.speech_transformer.transformer.attention import MultiHeadAttention, ScaledDotProductAttention
except ImportError:
log.warning("import torchvision fail or could not get MultiHeadAttention or ScaledDotProductAttention from module "
"torchbenchmark.models.speech_transformer.transformer.attention")
return
def new_init(self, n_head, d_model, d_k, d_v, dropout=0.1):
super(MultiHeadAttention, self).__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_model, n_head * d_k)
self.w_ks = nn.Linear(d_model, n_head * d_k)
self.w_vs = nn.Linear(d_model, n_head * d_v)
nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))
# fix two different devices npu, cpu
self.temperature = d_k ** 0.5
self.attention = ScaledDotProductAttention(temperature=self.temperature,
attn_dropout=dropout)
self.layer_norm = nn.LayerNorm(d_model)
self.fc = nn.Linear(n_head * d_v, d_model)
nn.init.xavier_normal_(self.fc.weight)
self.dropout = nn.Dropout(dropout)
MultiHeadAttention.__init__ = new_init
patch_remove_ops_from_generate_list(["aten.cat", "aten.full"])
def patch_model(model_name):
if model_name not in _patch_table.keys():
return
# do patch
_patch_table[model_name]()
-102
View File
@@ -1,102 +0,0 @@
import torch
class CUDAProfiler:
def __init__(self, enable=False, warmup=10, active=20, with_stack=False, with_memory=False, record_shapes=False, save_path="./profile"):
self.enable = enable
self.sp_with_stack = with_stack
self.sp_with_memory = with_memory
self.sp_record_shapes = record_shapes
self.warmup = warmup
self.active = active
self.sp_save_path = save_path
activites = [torch.profiler.ProfilerActivity.CUDA,
torch.profiler.ProfilerActivity.CPU]
self.prof = torch.profiler.profile(
with_stack=self.sp_with_stack,
record_shapes=self.sp_record_shapes,
profile_memory=self.sp_with_memory,
activities=activites,
schedule=torch.profiler.schedule(wait=0, warmup=self.warmup, active=self.active, repeat=1),
on_trace_ready=torch.profiler.tensorboard_trace_handler(self.sp_save_path))
def start(self):
if self.enable:
self.prof.start()
def step(self):
if self.enable:
self.prof.step()
def stop(self):
if self.enable:
self.prof.stop()
try:
import torch_npu
class NPUProfiler:
def __init__(self, enable=False, warmup=10, active=20, level="level0", with_stack=False, with_memory=False, record_shapes=False, save_path="./profile"):
self.enable = enable
self.sp_level = level
self.sp_with_stack = with_stack
self.sp_with_memory = with_memory
self.sp_record_shapes = record_shapes
self.warmup = warmup
self.active = active
self.sp_save_path = save_path
if self.sp_level == 'level0':
profiler_level = torch_npu.profiler.ProfilerLevel.Level0
elif self.sp_level == 'level1':
profiler_level = torch_npu.profiler.ProfilerLevel.Level1
elif self.sp_level == 'level2':
profiler_level = torch_npu.profiler.ProfilerLevel.Level2
else:
raise ValueError(f"profiler_level only supports level0,"
f" 1, and 2, but gets {self.sp_level}")
experimental_config = torch_npu.profiler._ExperimentalConfig(
export_type=[
torch_npu.profiler.ExportType.Text,
torch_npu.profiler.ExportType.Db
],
profiler_level=profiler_level,
msprof_tx=False,
aic_metrics=torch_npu.profiler.AiCMetrics.AiCoreNone,
l2_cache=False,
op_attr=False,
data_simplification=False,
record_op_args=False,
gc_detect_threshold=None
)
activites = [torch_npu.profiler.ProfilerActivity.NPU,
torch_npu.profiler.ProfilerActivity.CPU]
self.prof = torch_npu.profiler.profile(
with_stack=self.sp_with_stack,
record_shapes=self.sp_record_shapes,
profile_memory=self.sp_with_memory,
activities=activites,
schedule=torch_npu.profiler.schedule(wait=0, warmup=self.warmup, active=self.active, repeat=1),
on_trace_ready=torch_npu.profiler.tensorboard_trace_handler(self.sp_save_path),
experimental_config=experimental_config)
def start(self):
if self.enable:
self.prof.start()
def step(self):
if self.enable:
self.prof.step()
def stop(self):
if self.enable:
self.prof.stop()
except ImportError:
# ignore the error if torch_npu is not installed
pass
-18
View File
@@ -1,18 +0,0 @@
numpy
gym
# 计算机视觉库
opencv-python-headless
# 深度学习与NLP
transformers==4.36.0
timm
# 语音处理
kaldi_io
# 日志与可视化
tensorboardX
# 多模态库(需要从源码安装)
git+https://github.com/facebookresearch/multimodal.git
-457
View File
@@ -1,457 +0,0 @@
#!/usr/bin/env python3
# BSD 3-Clause License
# Copyright (c) 2019, pytorch
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# 3. Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gc
import importlib
import logging
import os
import re
import sys
import warnings
from os.path import abspath, exists
import torch
from common import BenchmarkRunner, main
from torch._dynamo.testing import collect_results, reduce_to_scalar_loss
from torch._dynamo.utils import clone_inputs
try:
import torch_npu
except ImportError:
pass
from benchmark.userbenchmark.dynamo.dynamobench.torchbench import (
USE_SMALL_BATCH_SIZE, ONLY_TRAINING_MODE, REQUIRE_HIGHER_TOLERANCE, REQUIRE_EVEN_HIGHER_TOLERANCE,
NONDETERMINISTIC, VERY_SLOW_BENCHMARKS, SLOW_BENCHMARKS, DONT_CHANGE_BATCH_SIZE,
MAX_BATCH_SIZE_FOR_ACCURACY_CHECK, FORCE_AMP_FOR_FP16_BF16_MODELS,
)
# We are primarily interested in tf32 datatype
torch.backends.cuda.matmul.allow_tf32 = True
torch.npu.config.allow_internal_format = False
def setup_torchbench_cwd():
original_dir = abspath(os.getcwd())
os.environ["KALDI_ROOT"] = "/tmp" # avoids some spam
search_dirs = [
"./benchmark",
"./torchbenchmark",
"../torchbenchmark",
"../torchbench",
"../benchmark",
"../../torchbenchmark",
"../../torchbench",
"../../benchmark",
]
torchbench_dir = None
for path in search_dirs:
if exists(path):
torchbench_dir = abspath(path)
break
if torchbench_dir:
os.chdir(torchbench_dir)
sys.path.append(torchbench_dir)
return original_dir
SKIP = {
"detectron2_maskrcnn",
"fambench_xlmr",
"tacotron2",
"hf_Bert_large", # Error: RelaxedUnspecConstraint(L['input_ids'].size()[0]) - inferred constant (4)
# takes too long, extreme slowdown (< .001)
"maml",
}
CHECK_NUMPY_VERSION = {
"soft_actor_critic"
}
REQUIRE_HIGHER_FP16_TOLERANCE = {
"drq",
}
NPU_REQUIRE_HIGHER_TOLERANCE = {
"dcgan",
"mobilenet_v2",
"shufflenet_v2_x1_0",
"timm_vovnet",
"phlippe_resnet",
}
NPU_REQUIRE_HIGHER_FP16_TOLERANCE = {
"timm_vision_transformer",
"functorch_dp_cifar10",
"moco",
"speech_transformer",
"timm_vovnet",
}
REQUIRE_HIGHER_FP16_TOLERANCE.update(NPU_REQUIRE_HIGHER_FP16_TOLERANCE)
# models in canary_models that we should run anyway
CANARY_MODELS = {
"torchrec_dlrm",
}
NPU_REQUIRE_LEARNING_RATE = {
"alexnet",
"dcgan",
"nvidia_deeprecommender",
}
NPU_REQUIRE_LOWER_LEARNING_RATE = {
"phlippe_densenet",
"phlippe_resnet",
"resnet50",
"resnet152",
"resnext50_32x4d",
"densenet121",
"vgg16",
}
NPU_REUQIRE_EVEN_LOWER_LEARNING_RATE = {
"mobilenet_v2",
"resnet18",
"shufflenet_v2_x1_0",
"timm_vovnet",
}
NPU_DVM_NO_ACLGRAPH = {
}
NPU_MLIR_NO_ACLGRAPH = {
}
class TorchBenchmarkRunner(BenchmarkRunner):
def __init__(self):
super().__init__()
self.suite_name = "torchbench"
self.optimizer = None
@property
def skip_models(self):
return SKIP
@property
def slow_models(self):
return SLOW_BENCHMARKS
@property
def very_slow_models(self):
return VERY_SLOW_BENCHMARKS
@property
def non_deterministic_models(self):
return NONDETERMINISTIC
@property
def force_amp_for_fp16_bf16_models(self):
return FORCE_AMP_FOR_FP16_BF16_MODELS
def load_model(
self,
device,
model_name,
batch_size=None,
part=None,
):
is_training = self.args.training
dynamic_shapes = self.args.dynamic_shapes
candidates = [
f"torchbenchmark.models.{model_name}",
f"torchbenchmark.canary_models.{model_name}",
f"torchbenchmark.models.fb.{model_name}",
]
for c in candidates:
try:
module = importlib.import_module(c)
break
except ModuleNotFoundError as e:
if e.name != c:
raise
else:
raise ImportError(f"could not import any of {candidates}")
benchmark_cls = getattr(module, "Model", None)
if not hasattr(benchmark_cls, "name"):
benchmark_cls.name = model_name
cant_change_batch_size = (
not getattr(benchmark_cls, "ALLOW_CUSTOMIZE_BSIZE", True)
or model_name in DONT_CHANGE_BATCH_SIZE
)
if cant_change_batch_size:
batch_size = None
if batch_size is None and is_training and model_name in USE_SMALL_BATCH_SIZE:
batch_size = USE_SMALL_BATCH_SIZE[model_name]
# Control the memory footprint for few models
if self.args.accuracy and model_name in MAX_BATCH_SIZE_FOR_ACCURACY_CHECK:
batch_size = min(batch_size, MAX_BATCH_SIZE_FOR_ACCURACY_CHECK[model_name])
# workaround "RuntimeError: not allowed to set torch.backends.cudnn flags"
torch.backends.__allow_nonbracketed_mutation_flag = True
extra_args = []
if part:
extra_args = ["--part", part]
if model_name == "vision_maskrcnn" and is_training:
# Output of vision_maskrcnn model is a list of bounding boxes,
# sorted on the basis of their scores. This makes accuracy
# comparison hard with torch.compile. torch.compile can cause minor
# divergences in the output because of how fusion works for amp in
# TorchInductor compared to eager. Therefore, instead of looking at
# all the bounding boxes, we compare only top 5.
model_kwargs = {"box_detections_per_img": 5}
benchmark = benchmark_cls(
test="train",
device=device,
batch_size=batch_size,
extra_args=extra_args,
model_kwargs=model_kwargs,
)
elif is_training:
benchmark = benchmark_cls(
test="train",
device=device,
batch_size=batch_size,
extra_args=extra_args,
)
else:
benchmark = benchmark_cls(
test="eval",
device=device,
batch_size=batch_size,
extra_args=extra_args,
)
model, example_inputs = benchmark.get_module()
# Models that must be in train mode while training
if is_training and model_name in ONLY_TRAINING_MODE:
model.train()
else:
model.eval()
gc.collect()
batch_size = benchmark.batch_size
self.validate_model(model, example_inputs)
return device, benchmark.name, model, example_inputs, batch_size
def _get_models_from_file(self, file_path):
"""Read model names from a file, one per line."""
if not os.path.exists(file_path):
return set()
with open(file_path, 'r') as f:
models = {line.strip() for line in f if line.strip()}
return models
def _get_models_from_directory(self, directory):
"""Get model names from subdirectories in the given directory."""
if not os.path.exists(directory):
return set()
models = set()
for item in os.listdir(directory):
item_path = os.path.join(directory, item)
if os.path.isdir(item_path):
models.add(item)
return models
def _filter_models_by_numpy_version(self, model_names, max_version="2.0"):
import numpy as np
from packaging import version
filtered_models = set(model_names)
numpy_version = np.__version__
# 检查是否需要过滤
models_to_check = model_names & CHECK_NUMPY_VERSION
if not models_to_check:
return filtered_models
# 解析当前numpy版本
current_version = version.parse(numpy_version)
max_allowed_version = version.parse(max_version)
# 如果当前版本大于等于2.0,需要过滤
if current_version > max_allowed_version:
models_to_remove = set()
for model_name in models_to_check:
if model_name in filtered_models:
models_to_remove.add(model_name)
logging.warning(
f"Model {model_name} has been skipped because it requires numpy version < 2.0, but current version is {numpy_version}."
)
# 从集合中移除不兼容的模型
filtered_models -= models_to_remove
return filtered_models
def iter_model_names(self, args):
from torchbenchmark import _list_canary_model_paths, _list_model_paths
# Get models from torchbenchmark repository
torchbenchmark_models = _list_model_paths()
torchbenchmark_models += [
f
for f in _list_canary_model_paths()
if os.path.basename(f) in CANARY_MODELS
]
torchbenchmark_model_names = {os.path.basename(m) for m in torchbenchmark_models}
# Get models from torchbench_models_list.txt file
script_dir = os.path.dirname(os.path.abspath(__file__))
list_file = os.path.join(script_dir, "torchbench_models_list.txt")
file_model_names = self._get_models_from_file(list_file)
# Find intersection between torchbenchmark and file list
torchbench_intersection = torchbenchmark_model_names & file_model_names
# Log models that are in file but not in torchbenchmark
models_not_in_torchbench = file_model_names - torchbenchmark_model_names
if models_not_in_torchbench:
logging.warning(
"The following models from torchbench_models_list.txt are not available "
"in the torchbenchmark repository and will be skipped: %s",
", ".join(sorted(models_not_in_torchbench))
)
# Get models from benchmarks/models directory
models_dir = os.path.join(script_dir, "models")
custom_model_names = self._get_models_from_directory(models_dir)
# Combine: intersection of torchbenchmark + file, union with custom models
final_model_names = torchbench_intersection | custom_model_names
# Apply numpy version filter
final_model_names = self._filter_models_by_numpy_version(final_model_names)
# Apply skip_models filter
final_model_names -= self.skip_models
# Sort for consistent ordering
sorted_models = sorted(final_model_names)
for _, model_name in enumerate(sorted_models):
yield model_name
def pick_grad(self, name, is_training):
if is_training or name in ("maml",):
return torch.enable_grad()
else:
return torch.no_grad()
def get_tolerance_and_cosine_flag(self, is_training, current_device, name):
tolerance = 1e-4
cosine = self.args.cosine
# Increase the tolerance for torch allclose
if self.args.float16 or self.args.amp:
if name in REQUIRE_HIGHER_FP16_TOLERANCE:
return 1e-2, cosine
return 1e-3, cosine
if is_training and current_device == "cuda":
tolerance = 1e-3
if name in REQUIRE_HIGHER_TOLERANCE:
tolerance = 1e-3
elif name in REQUIRE_EVEN_HIGHER_TOLERANCE:
tolerance = 8 * 1e-2
if is_training and current_device == "npu":
tolerance = 1e-3
if name in NPU_REQUIRE_HIGHER_TOLERANCE:
tolerance = 1e-2
return tolerance, cosine
def get_learning_rate(self, is_training, current_device, name):
learning_rate = 1e-2
if is_training and current_device == "cuda":
learning_rate = 1e-2
if name in NPU_REQUIRE_LEARNING_RATE:
learning_rate = 1e-3
elif name in NPU_REQUIRE_LOWER_LEARNING_RATE:
learning_rate = 1e-4
elif name in NPU_REUQIRE_EVEN_LOWER_LEARNING_RATE:
learning_rate = 1e-5
if is_training and current_device == "npu":
learning_rate = 1e-2
if name in NPU_REQUIRE_LEARNING_RATE:
learning_rate = 1e-3
elif name in NPU_REQUIRE_LOWER_LEARNING_RATE:
learning_rate = 1e-4
elif name in NPU_REUQIRE_EVEN_LOWER_LEARNING_RATE:
learning_rate = 1e-5
return learning_rate
def compute_loss(self, pred):
return reduce_to_scalar_loss(pred)
def forward_pass(self, mod, inputs, collect_outputs=True):
with self.autocast():
return mod(*inputs)
def forward_and_backward_pass(self, mod, inputs, collect_outputs=True):
cloned_inputs = clone_inputs(inputs)
self.optimizer_zero_grad(mod)
with self.autocast():
pred = mod(*cloned_inputs)
loss = self.compute_loss(pred)
self.grad_scaler.scale(loss).backward()
self.optimizer_step()
if collect_outputs:
return collect_results(mod, pred, loss, cloned_inputs)
return loss.item()
def torchbench_main():
original_dir = setup_torchbench_cwd()
logging.basicConfig(level=logging.WARNING)
warnings.filterwarnings("ignore")
main(TorchBenchmarkRunner(), original_dir)
if __name__ == "__main__":
torchbench_main()
@@ -1,34 +0,0 @@
alexnet
BERT_pytorch
dcgan
densenet121
hf_Albert
hf_Bart
hf_Bert
hf_DistilBert
hf_GPT2_large
hf_T5_base
hf_T5_large
LearningToPaint
lennard_jones
mobilenet_v2
nvidia_deeprecommender
phlippe_densenet
phlippe_resnet
pytorch_stargan
pytorch_unet
resnet152
resnet18
resnet50
resnext50_32x4d
shufflenet_v2_x1_0
soft_actor_critic
speech_transformer
squeezenet1_1
timm_regnet
timm_resnest
timm_vision_transformer
timm_vovnet
torch_multimodal_clip
tts_angular
vgg16
-288
View File
@@ -1,288 +0,0 @@
import multiprocessing
import glob
import os
import re
import shutil
import subprocess
import sys
import traceback
import platform
from pathlib import Path
from sysconfig import get_paths
from distutils.version import LooseVersion
from distutils import file_util
# Disable autoloading before running 'import torch' to avoid circular dependencies
os.environ["TORCH_DEVICE_BACKEND_AUTOLOAD"] = "0"
from torchnpugen.utils import PathManager
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
PathManager.check_directory_path_readable(os.path.join(BASE_DIR, "version.txt"))
with open(os.path.join(BASE_DIR, "version.txt")) as version_f:
VERSION = version_f.read().strip()
def which(thefile):
path = os.environ.get("PATH", os.defpath).split(os.pathsep)
for d in path:
fname = os.path.join(d, thefile)
fnames = [fname]
if sys.platform == 'win32':
exts = os.environ.get('PATHEXT', '').split(os.pathsep)
fnames += [fname + ext for ext in exts]
for name in fnames:
if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name):
return name
return None
def get_cmake_command():
def _get_version(cmd):
for line in subprocess.check_output([cmd, '--version']).decode('utf-8').split('\n'):
if 'version' in line:
return LooseVersion(line.strip().split(' ')[2])
raise RuntimeError('no version found')
"Returns cmake command."
cmake_command = 'cmake'
if platform.system() == 'Windows':
return cmake_command
cmake3 = which('cmake3')
cmake = which('cmake')
if cmake3 is not None and _get_version(cmake3) >= LooseVersion("3.18.0"):
cmake_command = 'cmake3'
return cmake_command
elif cmake is not None and _get_version(cmake) >= LooseVersion("3.18.0"):
return cmake_command
else:
raise RuntimeError('no cmake or cmake3 with version >= 3.18.0 found')
def get_build_type():
build_type = 'Release'
if os.getenv('DEBUG', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'Debug'
if os.getenv('REL_WITH_DEB_INFO', default='0').upper() in ['ON', '1', 'YES', 'TRUE', 'Y']:
build_type = 'RelWithDebInfo'
return build_type
def get_pytorch_dir():
try:
import torch
return os.path.dirname(os.path.abspath(torch.__file__))
except Exception:
_, _, exc_traceback = sys.exc_info()
frame_summary = traceback.extract_tb(exc_traceback)[-1]
return os.path.dirname(frame_summary.filename)
def generate_bindings_code(base_dir):
python_execute = sys.executable
generate_code_cmd = ["bash", os.path.join(base_dir, 'generate_code.sh'), python_execute, VERSION]
if subprocess.call(generate_code_cmd) != 0:
print(
'Failed to generate ATEN bindings: {}'.format(generate_code_cmd),
file=sys.stderr)
sys.exit(1)
def build_stub(base_dir):
build_stub_cmd = ["sh", os.path.join(base_dir, 'third_party/acl/libs/build_stub.sh')]
if subprocess.call(build_stub_cmd) != 0:
print(
'Failed to build stub: {}'.format(build_stub_cmd),
file=sys.stderr)
sys.exit(1)
def clean_generated_files():
f_ignore = open(os.path.join(BASE_DIR, '.gitignore'), 'r')
ignores = f_ignore.read()
pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
for wildcard in filter(None, ignores.split('\n')):
match = pat.match(wildcard)
if match:
if match.group(1):
# Marker is found and stop reading .gitignore.
break
# Ignore lines which begin with '#'.
else:
for filename in glob.glob(wildcard):
shutil.rmtree(filename, ignore_errors=True)
f_ignore.close()
clean_files = ['torch_npu/csrc/aten/RegisterCPU.cpp', 'torch_npu/csrc/aten/RegisterNPU.cpp',
'torch_npu/csrc/aten/RegisterAutogradNPU.cpp', 'torch_npu/csrc/aten/NPUNativeFunctions.h']
for file in clean_files:
if os.path.exists(os.path.join(BASE_DIR, file)):
os.remove(os.path.join(BASE_DIR, file))
if os.path.exists(os.path.join(BASE_DIR, "libtorch")):
shutil.rmtree(os.path.join(BASE_DIR, "libtorch"))
def check_gtest_valid(base_dir):
# validation of GoogleTest path.
gtest_path = os.path.join(base_dir, 'third_party/googletest/CMakeLists.txt')
return os.path.exists(gtest_path)
def generate_dbg_files_and_strip():
library_dir = Path(BASE_DIR).joinpath("build/packages/torch_npu")
dbg_dir = Path(BASE_DIR).joinpath("build/dbg_libtorch")
os.makedirs(dbg_dir, exist_ok=True)
library_files = [Path(i) for i in library_dir.rglob('*.so')]
for library_file in library_files:
subprocess.check_call(["eu-strip", library_file, "-f",
str(dbg_dir.joinpath(library_file.name)) + ".debug"], cwd=BASE_DIR) # Compliant
def run_cmake():
cmake = get_cmake_command()
if cmake is None:
raise RuntimeError(
"CMake must be installed to build the following extensions: ")
build_dir = os.path.join(BASE_DIR, "build")
build_type_dir = os.path.join(build_dir)
output_lib_path = os.path.join(build_type_dir, "packages/torch_npu/lib")
os.makedirs(build_type_dir, exist_ok=True)
os.makedirs(output_lib_path, exist_ok=True)
cmake_args = [
'-DCMAKE_BUILD_TYPE=' + get_build_type(),
'-DCMAKE_INSTALL_PREFIX=' + os.path.abspath(output_lib_path),
'-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=' + os.path.abspath(output_lib_path),
'-DTORCHNPU_INSTALL_LIBDIR=' + os.path.abspath(output_lib_path),
'-DPYTHON_INCLUDE_DIR=' + get_paths().get('include'),
'-DPYTORCH_INSTALL_DIR=' + get_pytorch_dir(),
'-DTORCH_VERSION=' + VERSION,
'-DBUILD_LIBTORCH=' + "ON"]
if check_opplugin_valid(BASE_DIR):
cmake_args.append('-DBUILD_OPPLUGIN=on')
cmake_args.append('-DBUILD_NEW_HEADER=on')
if check_tensorpipe_valid(BASE_DIR):
cmake_args.append('-DBUILD_TENSORPIPE=on')
if os.getenv('_GLIBCXX_USE_CXX11_ABI') is not None:
cmake_args.append('-DGLIBCXX_USE_CXX11_ABI=' + os.getenv('_GLIBCXX_USE_CXX11_ABI'))
if os.getenv('_ABI_VERSION') is not None:
cmake_args.append('-DABI_VERSION=' + os.getenv('_ABI_VERSION'))
build_args = ['-j', str(multiprocessing.cpu_count())]
subprocess.check_call([cmake, BASE_DIR] + cmake_args, cwd=build_type_dir, env=os.environ)
subprocess.check_call(['make'] + build_args, cwd=build_type_dir, env=os.environ)
if which('eu-strip') is not None:
generate_dbg_files_and_strip()
def check_opplugin_valid(base_dir):
# build with submodule of op_plugin, if path of op-plugin is valid
op_plugin_path = os.path.join(base_dir, 'third_party/op-plugin/op_plugin')
return os.path.exists(op_plugin_path)
def check_tensorpipe_valid(base_dir):
tensorpipe_path = os.path.join(base_dir, 'third_party/Tensorpipe/tensorpipe')
return os.path.exists(tensorpipe_path)
def copy_file(infile, outfile, preserve_mode=1, preserve_times=1, link=None, level=1):
"""Copy a file respecting verbose, dry-run and force flags. (The
former two default to whatever is in the Distribution object, and
the latter defaults to false for commands that don't define it.)
"""
return file_util.copy_file(infile, outfile, preserve_mode, preserve_times, True, link)
def move_special_hpp(ret):
hpp_name = "torch_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():
ret = []
header_files = [
"torch_npu/csrc/aten/*.h",
"torch_npu/csrc/aten/*/*.h",
"torch_npu/csrc/aten/*/*/*.h",
"torch_npu/csrc/core/*.h",
"torch_npu/csrc/core/*/*.h",
"torch_npu/csrc/core/*/*/*.h",
"torch_npu/csrc/framework/*.h",
"torch_npu/csrc/framework/*/*.h",
"torch_npu/csrc/framework/*/*/*.h",
"torch_npu/csrc/libs/*.h",
"torch_npu/csrc/inductor/**/*.h",
"torch_npu/csrc/distributed/*.h",
"torch_npu/csrc/distributed/*.hpp",
"third_party/acl/inc/*/*.h",
"third_party/acl/inc/*/*/*.h",
"third_party/hccl/inc/*/*.h",
]
glob_header_files = []
for regex_pattern in header_files:
glob_header_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
for src in glob_header_files:
dst = os.path.join(
os.path.join(BASE_DIR, "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))
return ret
ret = get_src_py_and_dst()
for src, dst in ret:
copy_file(src, dst)
move_special_hpp(ret)
def copy_lib():
lib_file = ["build/packages/torch_npu/lib/*.*"]
glob_lib_files = []
for regex_pattern in lib_file:
glob_lib_files += glob.glob(os.path.join(BASE_DIR, regex_pattern), recursive=True)
dst_path = os.path.join(BASE_DIR, "libtorch_npu/lib")
os.makedirs(dst_path, exist_ok=True)
for src in glob_lib_files:
_, src_file_name = os.path.split(src)
copy_file(src, os.path.join(dst_path, src_file_name))
def copy_cmake():
cmake_file = os.path.join(BASE_DIR, "build/Torch_npuConfig.cmake")
dst_path = os.path.join(BASE_DIR, "libtorch_npu/share/cmake/Torch_npu")
os.makedirs(dst_path, exist_ok=True)
copy_file(cmake_file, dst_path)
def build_libtorch_npu():
clean_generated_files()
generate_bindings_code(BASE_DIR)
if Path(BASE_DIR).joinpath("third_party/Tensorpipe/third_party/acl/libs").exists():
build_stub(Path(BASE_DIR).joinpath("third_party/Tensorpipe"))
build_stub(BASE_DIR)
run_cmake()
copy_hpp()
copy_lib()
copy_cmake()
if __name__ == "__main__":
build_libtorch_npu()
-5
View File
@@ -1,5 +0,0 @@
from .constants import (
BASE_DIR, TEST_DIR, NETWORK_OPS_DIR,
SLOW_TEST_BLOCKLIST, NOT_RUN_DIRECTLY, INCLUDE_FILES, EXEC_TIMEOUT
)
from .test_manager import TestMgr
-37
View File
@@ -1,37 +0,0 @@
import os
from pathlib import Path
BASE_DIR = Path(__file__).absolute().parent.parent.parent
TEST_DIR = BASE_DIR / 'test'
NETWORK_OPS_DIR = BASE_DIR / 'third_party/op-plugin/test'
SLOW_TEST_BLOCKLIST = [
'test_ops',
'test_modules',
'test_binary_ufuncs',
'test_ops_fwd_gradients',
'test_ops_gradients',
'test_reductions',
'test_unary_ufuncs',
'test_ops_jit',
'test_jit_fuser_te',
"onnx/test_op_consistency",
'onnx/test_pytorch_onnx_onnxruntime'
]
# exclude some not run directly test files
NOT_RUN_DIRECTLY = {
"jit": "test_jit.py",
}
# include some files
INCLUDE_FILES = [
'jit/test_complexity.py',
]
# default ut cmd execution timeout is 2000s
EXEC_TIMEOUT = os.getenv("PTA_UT_EXEC_TIMEOUT", 2000)
try:
EXEC_TIMEOUT = int(EXEC_TIMEOUT)
except ValueError:
EXEC_TIMEOUT = 2000
-5
View File
@@ -1,5 +0,0 @@
from .copy_opt import CopyOptStrategy
from .core import CoreTestStrategy
from .directory_mapping import DirectoryMappingStrategy
from .op import OpStrategy
from .test_file import TestFileStrategy
-30
View File
@@ -1,30 +0,0 @@
import os
import subprocess
from abc import ABCMeta, abstractmethod
from ..constants import BASE_DIR
class AccurateTest(metaclass=ABCMeta):
base_dir = BASE_DIR
test_dir = base_dir / 'test'
@abstractmethod
def identify(self, modify_file):
"""
该接口提供代码对应的UT的路径信息
"""
raise Exception("abstract method. Subclasses should implement it.")
@classmethod
def find_ut_by_regex(cls, regex):
ut_files = []
cmd = "find {} -name {}".format(str(cls.test_dir), regex)
status, output = subprocess.getstatusoutput(cmd)
# 对于找不到的暂不作处理
if not(status or not output):
files = output.split('\n')
for ut_file in files:
ut_file_basename = os.path.basename(ut_file)
if ut_file_basename.startswith("test") and ut_file.endswith(".py"):
ut_files.append(ut_file)
return ut_files
-13
View File
@@ -1,13 +0,0 @@
from .base import AccurateTest
class CopyOptStrategy(AccurateTest):
"""
通过识别非连续转连续的测试用例
"""
def identify(self, modify_file):
if modify_file.find('contiguous') > 0:
regex = '*contiguous*'
return AccurateTest.find_ut_by_regex(regex)
return []
-18
View File
@@ -1,18 +0,0 @@
from pathlib import Path
from .base import AccurateTest
class CoreTestStrategy(AccurateTest):
"""
Determine whether the core tests should be runned
"""
def __init__(self):
super().__init__()
self.block_list = ['test', 'docs']
self.core_test_cases = [str(i) for i in (self.base_dir / 'test/npu').rglob('test_*.py')]
def identify(self, modify_file):
modified_module = str(Path(modify_file).parts[0])
if modified_module not in self.block_list:
return self.core_test_cases
return []
@@ -1,52 +0,0 @@
from pathlib import Path
from .base import AccurateTest
class DirectoryMappingStrategy(AccurateTest):
"""
Map the modified files to the corresponding test cases
"""
mapping_list = {
'contrib': 'test/contrib',
'cpp_extension': 'test/cpp_extensions',
'distributed': 'test/distributed',
'fx': 'test/test_fx.py',
'optim': 'test/optim',
'profiler': 'test/profiler',
'onnx': 'test/onnx',
'utils': 'test/test_utils.py',
'testing': 'test/test_testing.py',
'jit': 'test/test_jit.py',
'rpc': 'test/distributed/rpc',
'meta': 'test/test_fake_tensor.py',
}
@staticmethod
def get_module_name(modify_file):
module_name = str(Path(modify_file).parts[1])
if module_name == 'csrc':
module_name = str(Path(modify_file).parts[2])
for part in Path(modify_file).parts:
if part == 'rpc':
module_name = 'rpc'
if module_name == 'utils' and Path(modify_file).parts[2] == 'cpp_extension.py':
module_name = 'cpp_extension'
return module_name
def identify(self, modify_file):
current_all_ut_path = []
if str(Path(modify_file).parts[0]) == 'torch_npu':
mapped_ut_path = []
module_name = self.get_module_name(modify_file)
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(self.base_dir.joinpath(mapped_path)):
current_all_ut_path.append(str(self.base_dir.joinpath(mapped_path)))
else:
current_all_ut_path += [str(i) for i in (self.base_dir.joinpath(mapped_path)).glob('test_*.py')]
return current_all_ut_path
-25
View File
@@ -1,25 +0,0 @@
import re
from pathlib import Path
from .base import AccurateTest
class OpStrategy(AccurateTest):
"""
通过对适配层的代码的识别
"""
def identify(self, modify_file):
"""
通过对于算子实现文件的文件名解析获取其单元测试的名字,比如:
BinaryCrossEntropyWithLogitsBackwardKernelNpu.cpp
针对这个文件,先识别关键字BinaryCrossEntropyWithLogitsBackward
然后,获取其正则表达式*binary*cross*entropy*with*logits*backward*识别到符合要求的测试用例
具体方法:通过大写字母切分关键字,再识别包含所有这些关键字的测试文件名。
"""
filename = Path(modify_file).name
if filename.find('KernelNpu') >= 0:
feature_line = filename.split('KernelNpu')[0]
features = re.findall('[A-Z][^A-Z]*', feature_line)
regex = '*' + '*'.join([f"{feature.lower()}" for feature in features]) + '*'
return AccurateTest.find_ut_by_regex(regex)
return []
-14
View File
@@ -1,14 +0,0 @@
import re
from pathlib import Path
from .base import AccurateTest
class TestFileStrategy(AccurateTest):
"""
Determine whether the modified files are test cases
"""
def identify(self, modify_file):
is_test_file = str(Path(modify_file).parts[0]) == "test" \
and re.match("test_(.+).py", Path(modify_file).name)
return [(str(self.base_dir.joinpath(modify_file)))] if is_test_file else []
-161
View File
@@ -1,161 +0,0 @@
import os
import re
from pathlib import Path
import torch_npu
from .strategy import (
TestFileStrategy,
CopyOptStrategy,
OpStrategy,
DirectoryMappingStrategy,
CoreTestStrategy
)
from .constants import (
BASE_DIR, TEST_DIR, SLOW_TEST_BLOCKLIST, INCLUDE_FILES
)
def get_test_torch_version_path():
torch_npu_version = torch_npu.__version__
version_list = torch_npu_version.split('.')
if len(version_list) > 2:
return f'test_v{version_list[0]}r{version_list[1]}_ops'
else:
raise RuntimeError("Invalid torch_npu version.")
class TestMgr:
def __init__(self):
self.modify_files = []
self.test_files = {
'ut_files': [],
'op_ut_files': []
}
def load(self, modify_files, world_size):
with open(modify_files) as f:
for line in f:
if world_size != 0 and ("test/_inductor/" in line):
continue
line = line.strip()
self.modify_files.append(line)
def analyze(self):
for modify_file in self.modify_files:
self.test_files['ut_files'] += TestFileStrategy().identify(modify_file)
self.test_files['ut_files'] += CopyOptStrategy().identify(modify_file)
self.test_files['ut_files'] += OpStrategy().identify(modify_file)
self.test_files['ut_files'] += DirectoryMappingStrategy().identify(modify_file)
self.test_files['op_ut_files'] += OpStrategy().identify(modify_file)
self.test_files['ut_files'] += CoreTestStrategy().identify(modify_file)
unique_files = sorted(set(self.test_files['ut_files']))
exist_ut_file = [
changed_file
for changed_file in unique_files
if Path(changed_file).exists()
]
self.test_files['ut_files'] = exist_ut_file
self.exclude_test_files(slow_files=SLOW_TEST_BLOCKLIST)
def load_core_ut(self):
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/npu').rglob('test_*.py')]
def load_distributed_ut(self):
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/distributed').rglob('test_*.py')]
def load_inductor_ut(self):
self.test_files['ut_files'] += [str(i) for i in (BASE_DIR / 'test/_inductor').rglob('test_*.py')]
def load_op_plugin_ut(self):
if not os.path.exists(BASE_DIR / 'third_party/op-plugin/test'):
raise Exception("The path of op-plugin did not exist, check whether it had been pulled.")
version_path = get_test_torch_version_path()
file_hash = {}
for file_path in (BASE_DIR / 'third_party/op-plugin/test').rglob('test_*.py'):
if str(file_path.parts[-2]) in [version_path, "test_custom_ops", "test_base_ops"]:
file_name = str(file_path.name)
if file_name in file_hash:
if str(file_path.parts[-2]) == version_path:
self.test_files['ut_files'].remove(file_hash[file_name])
file_hash[file_name] = str(file_path)
self.test_files['ut_files'].append(str(file_path))
else:
file_hash[file_name] = str(file_path)
self.test_files['ut_files'].append(str(file_path))
def load_all_ut(self, include_distributed_case=False, include_op_plugin_case=False):
all_files = [str(i) for i in (BASE_DIR / 'test').rglob('test_*.py') if 'distributed' not in str(i)]
self.test_files['ut_files'] = all_files
if include_distributed_case:
self.load_distributed_ut()
if include_op_plugin_case:
self.load_op_plugin_ut()
def split_test_files(self, rank, world_size):
if rank > world_size:
raise Exception(f'rank {rank} is greater than world_size {world_size}')
def ordered_split(files, start, step):
return sorted(files)[start::step] if files else []
# node rank starts from 1
self.test_files['ut_files'] = ordered_split(self.test_files['ut_files'], rank - 1, world_size)
self.test_files['op_ut_files'] = ordered_split(self.test_files['op_ut_files'], rank - 1, world_size)
def exclude_test_files(self, slow_files=None, not_run_files=None, mode="slow_test"):
"""
Args:
slow_files: slow test files.
not_run_files: not_run_directly test files.
mode: "slow_test" or "not_run_directly". Default: "slow_test".
Returns:
"""
def remove_test_files(key):
block_list = not_run_files.keys() if mode == "not_run_directly" else slow_files
for test_name in block_list:
test_files_copy = self.test_files.get(key, [])[:]
for test_file in test_files_copy:
is_remove = False
if mode == "slow_test" and test_name + ".py" in test_file:
print(f'Excluding slow test: {test_name}')
is_remove = True
if mode == "not_run_directly":
# remove not run directly files
is_folder_in = not test_name.endswith(".py") and "/" + test_name + "/" in test_file
is_file_in = test_name.endswith(".py") and test_name in test_file
if is_folder_in or is_file_in:
if test_name in ["jit"] and re.search("|".join(INCLUDE_FILES), test_file):
continue
is_remove = True
# add instead file
instead_files.add(str(TEST_DIR.joinpath(not_run_files[test_name])))
if is_remove:
test_files = self.test_files.get(key, [])
if test_file in test_files:
test_files.remove(test_file)
for test_files_key in self.test_files.keys():
instead_files = set()
remove_test_files(test_files_key)
for instead_file in instead_files:
if instead_file not in self.test_files[test_files_key]:
self.test_files[test_files_key].append(instead_file)
def get_test_files(self):
return self.test_files
def print_modify_files(self):
print("modify files:")
for modify_file in self.modify_files:
print(modify_file)
def print_ut_files(self):
print("ut files:")
for ut_file in self.test_files.get('ut_files', []):
print(ut_file)
def print_op_ut_files(self):
print("op ut files:")
for op_ut_file in self.test_files.get('op_ut_files', []):
print(op_ut_file)
-154
View File
@@ -1,154 +0,0 @@
# -*- coding: UTF-8 -*-
import os
import sys
import subprocess
import threading
import queue
import argparse
from pathlib import Path
import random
import psutil
from access_control import (
TestMgr,
BASE_DIR, TEST_DIR, SLOW_TEST_BLOCKLIST, NOT_RUN_DIRECTLY, EXEC_TIMEOUT, NETWORK_OPS_DIR
)
def exec_ut(files):
"""
执行单元测试文件,其中存在失败,则标识异常并打印相关信息
"""
def get_op_name(ut_file):
op_name = str(ut_file.split('/')[-1].split('.')[0])
return op_name[5:] if op_name.startswith("test_") else op_name
def get_ut_name(ut_file):
if 'op-plugin' in str(Path(ut_file)):
return str(Path(ut_file).relative_to(NETWORK_OPS_DIR))[:-3]
return str(Path(ut_file).relative_to(TEST_DIR))[:-3]
def get_ut_cmd(ut_type, ut_file):
cmd = [sys.executable, "run_test.py", "-v"]
if ut_type == "op_ut_files":
# do not skip ops related test entries
return cmd + ["-e"] + SLOW_TEST_BLOCKLIST[1:] + ["-i", "test_ops", "--", "-k", "_" + get_op_name(ut_file)]
if 'op-plugin' in str(Path(ut_file)):
cmd = [sys.executable, NETWORK_OPS_DIR / "run_test.py", "-v"]
return cmd + ["-i", get_ut_name(ut_file)]
def wait_thread(process, event_timer):
process.wait()
event_timer.set()
def enqueue_output(out, log_queue):
for line in iter(out.readline, b''):
log_queue.put(line.decode('utf-8', errors='ignore'))
out.close()
return
def start_thread(fn, *args):
stdout_t = threading.Thread(target=fn, args=args)
stdout_t.daemon = True
stdout_t.start()
def print_subprocess_log(log_queue):
while not log_queue.empty():
print((log_queue.get()).strip())
def run_cmd_with_timeout(cmd):
os.chdir(str(TEST_DIR))
stdout_queue = queue.Queue()
event_timer = threading.Event()
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)
start_thread(wait_thread, p, event_timer)
start_thread(enqueue_output, p.stdout, stdout_queue)
try:
event_timer.wait(EXEC_TIMEOUT)
ret = p.poll()
if ret:
print_subprocess_log(stdout_queue)
if not event_timer.is_set():
ret = 1
parent_process = psutil.Process(p.pid)
for children_process in parent_process.children(recursive=True):
children_process.kill()
p.kill()
p.terminate()
print("Timeout: Command '{}' timed out after {} seconds".format(" ".join(cmd), EXEC_TIMEOUT))
print_subprocess_log(stdout_queue)
except Exception as err:
ret = 1
print(err)
return ret
def run_tests(test_files):
test_infos = []
has_failed = 0
init_method = random.randint(1, 2)
for ut_type, ut_files in test_files.items():
for ut_file in ut_files:
cmd = get_ut_cmd(ut_type, ut_file)
ut_info = str(cmd[-1])
if ut_type == "op_ut_files":
ut_info = "test_ops " + ut_info
else:
cmd = cmd if 'op-plugin' in str(Path(ut_file)) else cmd + ["--init_method={}".format(init_method)]
ret = run_cmd_with_timeout(cmd)
if ret:
has_failed = ret
test_infos.append("exec ut {} failed.".format(ut_info))
else:
test_infos.append("exec ut {} success.".format(ut_info))
init_method = 2 if init_method == 1 else 1
return has_failed, test_infos
ret_status, exec_infos = run_tests(files)
print("***** Total result:")
for exec_info in exec_infos:
print(exec_info)
return ret_status
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Control needed ut cases')
parser.add_argument('--all', action="store_true", help='Run all testcases')
parser.add_argument('--distributed', action="store_true", help='Run distributed testcases')
parser.add_argument('--inductor', action="store_true", help='Run inductor testcases')
parser.add_argument('--rank', default=0, type=int, help='Index of current ut nodes')
parser.add_argument('--world_size', default=0, type=int, help='Number of ut nodes')
parser.add_argument('--network_ops', action="store_true", help='Run network_ops testcases in the op-plugin repo')
options = parser.parse_args()
print(f"options: {options}")
cur_modify_files = str(BASE_DIR / 'modify_files.txt')
test_mgr = TestMgr()
if options.all:
test_mgr.load_all_ut(options.distributed, options.network_ops)
elif options.distributed:
test_mgr.load_distributed_ut()
elif options.network_ops:
test_mgr.load_op_plugin_ut()
elif options.inductor:
test_mgr.load_inductor_ut()
elif os.path.exists(cur_modify_files):
test_mgr.load(cur_modify_files, world_size=options.world_size)
test_mgr.analyze()
else:
test_mgr.load_core_ut()
test_mgr.exclude_test_files(not_run_files=NOT_RUN_DIRECTLY, mode="not_run_directly")
if options.rank > 0 and options.world_size > 0:
test_mgr.split_test_files(options.rank, options.world_size)
cur_test_files = test_mgr.get_test_files()
test_mgr.print_modify_files()
test_mgr.print_ut_files()
test_mgr.print_op_ut_files()
ret_ut = exec_ut(cur_test_files)
sys.exit(ret_ut)
-115
View File
@@ -1,115 +0,0 @@
#!/bin/bash
set -e
CUR_DIR=$(dirname $(readlink -f $0))
SUPPORTED_PY_VERSION=(3.9 3.10 3.11 3.12 3.13)
# Default supported python version is 3.9
PY_VERSION="3.9"
# Parse arguments inside script
function parse_script_args() {
local args_num=0
if [[ "x${1}" = "x" ]]; then
# default: bash build.sh (python3.9)
return 0
fi
args_num=$#
while true; do
case "${1}" in
--python=*)
PY_VERSION=$(echo "${1}"|cut -d"=" -f2)
args_num=$((args_num-1))
shift
;;
--disable_torchair)
export DISABLE_INSTALL_TORCHAIR=TRUE
args_num=$((args_num-1))
shift
;;
--disable_rpc)
export DISABLE_RPC_FRAMEWORK=TRUE
args_num=$((args_num-1))
shift
;;
--enable_lto)
export ENABLE_LTO=TRUE
args_num=$((args_num-1))
shift
;;
--enable_pgo=*)
pgo_mode=$(echo "${1}"|cut -d"=" -f2)
case $pgo_mode in
1)
export PGO_MODE=1
args_num=$((args_num-1))
;;
2)
export PGO_MODE=2
args_num=$((args_num-1))
;;
*)
echo "ERROR Unsupported parameters: ${1}"
return 1
;;
esac
shift
;;
-*)
echo "ERROR Unsupported parameters: ${1}"
return 1
;;
*)
if [ "x${1}" != "x" ]; then
echo "ERROR Unsupported parameters: ${1}"
return 1
fi
break
;;
esac
done
# if some "--param=value" are not parsed correctly, throw an error.
if [[ ${args_num} -ne 0 ]]; then
return 1
fi
}
function check_python_version() {
matched_py_version="false"
for ver in ${SUPPORTED_PY_VERSION[*]}; do
if [ "${PY_VERSION}" = "${ver}" ]; then
matched_py_version="true"
return 0
fi
done
if [ "${matched_py_version}" = "false" ]; then
echo "${PY_VERSION} is an unsupported python version, we suggest ${SUPPORTED_PY_VERSION[*]}"
exit 1
fi
}
function main()
{
if ! parse_script_args "$@"; then
echo "Failed to parse script args. Please check your inputs."
exit 1
fi
check_python_version
cd ${CUR_DIR}/..
# if you add or delete file/files in the project, you need to remove the following comment
# make clean
python"${PY_VERSION}" setup.py build bdist_wheel
if [ $? != 0 ]; then
echo "Failed to compile the wheel file. Please check the source code by yourself."
exit 1
fi
exit 0
}
main "$@"
-57
View File
@@ -1,57 +0,0 @@
FROM pytorch/manylinux2_28_aarch64-builder:cpu-aarch64-2.8
ENV PATH /usr/local/bin:$PATH
RUN echo "alias ll='ls -l --color=auto'" >> /root/.bashrc
# Set pip&python
RUN cd /usr/local/bin \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/pip3.10 pip3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/pip3.11 pip3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/python3.10 python3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/python3.11 python3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.huaweicloud.com/repository/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=repo.huaweicloud.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
ARG CONFIG_FOR_LCOV=0
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
mkdir -p /etc/yum.repos.d/backup && \
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ && \
curl -o /etc/yum.repos.d/Centos7-aliyun.repo https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo -k && \
yum clean all && \
yum makecache; \
fi
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
yum install -y perl-Module-Load-Conditional && \
yum install -y perl-Digest-MD5 && \
yum install -y "perl(DateTime)" && \
yum install -y perl-CPAN*; \
fi
RUN yum install -y vim-common
# Install pip package(build)
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.8.0 \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.8.0 \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.8.0 \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
-37
View File
@@ -1,37 +0,0 @@
## Ascend Pytorch Dockerfile Repository
This folder hosts the `Dockerfile` to build docker images with various platforms.
### Build torch_npu from Docker container
**Clone torch-npu**
```Shell
git clone https://gitcode.com/ascend/pytorch.git --depth 1
```
**Build docker image**
```Shell
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 .
```
If you want to configure the environment of LCOV, please build docker image like this:
```Shell
cd pytorch/ci/docker/{arch} # {arch} for X86 or ARM
docker build -t manylinux-builder:v1 --build-arg CONFIG_FOR_LCOV=1 .
```
**Enter docker Container**
```Shell
docker run -it -v /{code_path}/pytorch:/home/pytorch manylinux-builder:v1 bash
# {code_path} is the torch_npu source code path
```
**Compile torch_npu**
Take Python 3.9 as an example
```Shell
cd /home/pytorch
bash ci/build.sh --python=3.9
```
-57
View File
@@ -1,57 +0,0 @@
FROM pytorch/manylinux2_28-builder:cpu-2.8
ENV PATH /usr/local/bin:$PATH
RUN echo "alias ll='ls -l --color=auto'" >> /root/.bashrc
# Set pip&python
RUN cd /usr/local/bin \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/pip3.10 pip3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/pip3.11 pip3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/pip3.9 pip3 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3.9 \
&& ln -sf /opt/_internal/cpython-3.10.18/bin/python3.10 python3.10 \
&& ln -sf /opt/_internal/cpython-3.11.13/bin/python3.11 python3.11 \
&& ln -sf /opt/_internal/cpython-3.9.23/bin/python3.9 python3
# Set pip source
RUN mkdir /root/.pip \
&& echo "[global]" > /root/.pip/pip.conf \
&& echo "index-url=https://mirrors.huaweicloud.com/repository/pypi/simple" >> /root/.pip/pip.conf \
&& echo "trusted-host=repo.huaweicloud.com" >> /root/.pip/pip.conf \
&& echo "timeout=120" >> /root/.pip/pip.conf
ARG CONFIG_FOR_LCOV=0
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
mkdir -p /etc/yum.repos.d/backup && \
mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/ && \
curl -o /etc/yum.repos.d/Centos7-aliyun.repo https://mirrors.wlnmp.com/centos/Centos7-aliyun-altarch.repo -k && \
yum clean all && \
yum makecache; \
fi
RUN if [ "$CONFIG_FOR_LCOV" = "1" ]; then \
yum install -y perl-Module-Load-Conditional && \
yum install -y perl-Digest-MD5 && \
yum install -y "perl(DateTime)" && \
yum install -y perl-CPAN*; \
fi
RUN yum install -y vim-common
# Install pip package(build)
RUN pip3.9 install pyyaml \
&& pip3.9 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.9 install numpy==1.21.3
RUN pip3.10 install pyyaml \
&& pip3.10 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.10 install numpy==1.21.3
RUN pip3.11 install pyyaml \
&& pip3.11 install torch==2.8.0+cpu --index-url https://download.pytorch.org/whl/cpu \
&& pip3.11 install numpy==1.23.2
WORKDIR /home
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
py_execute=${1-python3}
CUR_DIR=$(dirname $(readlink -f $0))
cd ${CUR_DIR}/../examples/libtorch_resnet
if [ -f ./resnet_model.pt ]; then
rm ./resnet_model.pt
fi
$py_execute 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=`$py_execute -c 'import torch;print(torch.utils.cmake_prefix_path)'` .. && \
make && ./libtorch_resnet ../resnet_model.pt > out.log
if grep -q "resnet_model run success!" out.log; then
echo "Success."
exit 0
else
echo "Failed."
exit 1
fi
-31
View File
@@ -1,31 +0,0 @@
include(FindPackageHandleStandardArgs)
if(DEFINED ENV{TORCH_NPU_INSTALL_PREFIX})
set(TORCH_NPU_INSTALL_PREFIX $ENV{TORCH_NPU_INSTALL_PREFIX})
else()
# Assume we are in <install-prefix>/share/cmake/Torch_npu/Torch_npuConfig.cmake
get_filename_component(CMAKE_CURRENT_LIST_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(TORCH_NPU_INSTALL_PREFIX "${CMAKE_CURRENT_LIST_DIR}/../../../" ABSOLUTE)
endif()
# Include directories.
if(EXISTS "${TORCH_NPU_INSTALL_PREFIX}/include")
set(TORCH_NPU_INCLUDE_DIRS
${TORCH_NPU_INSTALL_PREFIX}/include)
else()
set(TORCH_NPU_INCLUDE_DIRS
${TORCH_NPU_INSTALL_PREFIX}/include)
endif()
# Library dependencies.
find_library(TORCH_NPU_LIBRARY torch_npu PATHS "${TORCH_NPU_INSTALL_PREFIX}/lib")
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
set(TORCH_NPU_CXX_FALGS "-D_GLIBCXX_USE_CXX11_ABI=@GLIBCXX_USE_CXX11_ABI@")
endif()
include_directories(${TORCH_NPU_INCLUDE_DIRS})
set(TORCH_NPU_LIBRARIES ${TORCH_NPU_LIBRARY})
find_package_handle_standard_args(Torch_npu DEFAULT_MSG TORCH_NPU_LIBRARY TORCH_NPU_INCLUDE_DIRS)
-728
View File
@@ -1,728 +0,0 @@
# FrameworkPTAdapter 3.0.RC2 Release Notes
- [FrameworkPTAdapter 3.0.RC2 Release Notes](#frameworkptadapter-30rc2-release-notes)
- [FrameworkPTAdapter 3.0.RC2](#frameworkptadapter-30rc2)
- [Before You Start](#before-you-start)
- [New Features](#new-features)
- [Modified Features](#modified-features)
- [Resolved Issues](#resolved-issues)
- [Known Issues](#known-issues)
- [Compatibility](#compatibility)
- [FrameworkPTAdapter 3.0.RC1](#frameworkptadapter-30rc1)
- [Before You Start](#before-you-start-1)
- [New Features](#new-features-1)
- [Modified Features](#modified-features-1)
- [Resolved Issues](#resolved-issues-1)
- [Known Issues](#known-issues-1)
- [Compatibility](#compatibility-1)
- [FrameworkPTAdapter 2.0.4](#frameworkptadapter-204)
- [Before You Start](#before-you-start-2)
- [New Features](#new-features-2)
- [Modified Features](#modified-features-2)
- [Resolved Issues](#resolved-issues-2)
- [Known Issues](#known-issues-2)
- [Compatibility](#compatibility-2)
- [FrameworkPTAdapter 2.0.3](#frameworkptadapter-203)
- [Before You Start](#before-you-start-3)
- [New Features](#new-features-3)
- [Modified Features](#modified-features-3)
- [Resolved Issues](#resolved-issues-3)
- [Known Issues](#known-issues-3)
- [Compatibility](#compatibility-3)
- [FrameworkPTAdapter 2.0.2](#frameworkptadapter-202)
- [Before You Start](#before-you-start-4)
- [New Features](#new-features-4)
- [Modified Features](#modified-features-4)
- [Resolved Issues](#resolved-issues-4)
- [Known Issues](#known-issues-4)
- [Compatibility](#compatibility-4)
## FrameworkPTAdapter 3.0.RC2
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 uses plug-in adaptation and is completely decoupled from the native PyTorch framework. The current functions and performance of PyTorch 1.8.1 are basically the same as those of PyTorch 1.5.0, providing good development experience for backend operator adaptation.
AOE-based tuning is supported.
### New Features
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
</tr>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Fixed a few bugs.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled as plugins</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Decoupled the torch_npu plugin from the native PyTorch framework completely.</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Performance optimization</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Optimized the single-operator delivery and collective communication functions.</p>
</td>
</tr>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>API satisfaction</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Added more APIs. (For details, see the API list.)</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 3.0.RC1
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 adopts the plugin adaptation mode and inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation. It supports AOE-based tuning.
### New Features
**Table 1** Features supported by PyTorch
<a name="t76c34275cbb74753970f7c5a9eb594fa"></a>
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AOE-based tuning</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the AOE auto tuning tool to improve the model performance.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a> Added the function of adapted operator development. For details, see the API list.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Plugin decoupling</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Decoupled the NPU-adapted code and ported it to the **torch_npu** plugin to decouple the Ascend-adapted code from the native PyTorch code.</p>
</td>
<tr>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AOE-based tuning</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the AOE auto tuning tool to improve the model performance.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Improvement of framework API satisfaction</p>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported APIs that have been adapted to Ascend PyTorch 1.5.0. For details, see the API list.</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Symptom</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.4
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 and 1.8.1 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 inherits the features of PyTorch 1.5.0. Their functions are basically the same, but PyTorch 1.8.1 provides better development experience for backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row7979351559"><td class="cellrowborder" rowspan="3" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.5.0 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>Optimization of Model Accuracy Analyzer</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported mapping between IR and TBE operators and enabled the NPU dump data to be loaded to the GPU side for comparison.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>E2E prof</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Integrated the profile data obtained by the native PyTorch Profiling tool and CANN prof tool to implement end-to-end model and operator performance analysis.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch 1.8.1 features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>AMP</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported the native training with automatic mixed precision (AMP) of PyTorch.</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Profiling</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported the native profiling function of PyTorch.</p>
</td>
</tr>
<tr id="row7979351559"><td class="cellrowborder" rowspan="2" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Supported Ubuntu 20.04 (x86 and ARM) and EulerOS 2.10 (ARM).</p>
</td>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Python version compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported compilation and use of Python 3.9 (only in PyTorch 1.8.1).</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04/2.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Ubuntu 18.04/2.04, EulerOS 2.8/2.10, Kylin V10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.3
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
PyTorch 1.8.1 is supported by this version and later, and this version inherits the features of PyTorch 1.5.0 and provides the same functions, except for the Profiling tool. In addition, it optimizes the backend operator adaptation. Currently, PyTorch 1.8.1 supports only the ResNet-50 network model.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.459999999999999%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.27%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.27%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row7979351559"><td class="cellrowborder" rowspan="5" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p69836331553"><a name="p69836331553"></a><a name="p69836331553"></a>PyTorch features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p149831333357"><a name="p149831333357"></a><a name="p149831333357"></a>PyTorch 1.8.1</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p1398313336511"><a name="p1398313336511"></a><a name="p1398313336511"></a>Added PyTorch 1.8.1. Currently, only the ResNet-50 network is supported, including the training scenario for distributed data parallel (DDP).</p>
</td>
</tr>
<tr id="row109719353511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18983183315515"><a name="p18983183315515"></a><a name="p18983183315515"></a>Python 3.8</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p836221112812"><a name="p836221112812"></a><a name="p836221112812"></a>Supported compilation and use of Python 3.8.</p>
</td>
</tr>
<tr id="row13971435754"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p79831331353"><a name="p79831331353"></a><a name="p79831331353"></a>Operator overflow/underflow detection tool</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p109832331055"><a name="p109832331055"></a><a name="p109832331055"></a>Supported IR-level operator overflow/underflow detection in the PyTorch framework. When an AI Core operator overflow/underflow occurs, the IR information is displayed.</p>
</td>
</tr>
<tr id="row185381431133610"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p953883153611"><a name="p953883153611"></a><a name="p953883153611"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p13538203153618"><a name="p13538203153618"></a><a name="p13538203153618"></a>Supported UOS 20 1020e ARM.</p>
</td>
</tr>
<tr id="row91681125173610"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p2168172519364"><a name="p2168172519364"></a><a name="p2168172519364"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1416815259367"><a name="p1416815259367"></a><a name="p1416815259367"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row11970351050"><td class="cellrowborder" rowspan="26" valign="top" width="10.459999999999999%" headers="mcps1.2.4.1.1 "><p id="p298314333514"><a name="p298314333514"></a><a name="p298314333514"></a>Model training</p>
</td>
<td class="cellrowborder" valign="top" width="26.27%" headers="mcps1.2.4.1.2 "><p id="p19984193312511"><a name="p19984193312511"></a><a name="p19984193312511"></a>CenterFace</p>
</td>
<td class="cellrowborder" valign="top" width="63.27%" headers="mcps1.2.4.1.3 "><p id="p7517351258"><a name="p7517351258"></a><a name="p7517351258"></a>-</p>
</td>
</tr>
<tr id="row9965351254"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1984033458"><a name="p1984033458"></a><a name="p1984033458"></a>PCBU</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p298411338513"><a name="p298411338513"></a><a name="p298411338513"></a>-</p>
</td>
</tr>
<tr id="row14966351959"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p198414331957"><a name="p198414331957"></a><a name="p198414331957"></a>Net++</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1798413331756"><a name="p1798413331756"></a><a name="p1798413331756"></a>-</p>
</td>
</tr>
<tr id="row20966351454"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p4984183317518"><a name="p4984183317518"></a><a name="p4984183317518"></a>FCN8S</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1698453311519"><a name="p1698453311519"></a><a name="p1698453311519"></a>-</p>
</td>
</tr>
<tr id="row19653517518"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1298483319512"><a name="p1298483319512"></a><a name="p1298483319512"></a>OSNetRetinaFace</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1798423312519"><a name="p1798423312519"></a><a name="p1798423312519"></a>-</p>
</td>
</tr>
<tr id="row39619351751"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1298414331513"><a name="p1298414331513"></a><a name="p1298414331513"></a>PSPnet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p10984633254"><a name="p10984633254"></a><a name="p10984633254"></a>-</p>
</td>
</tr>
<tr id="row496335654"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19984433351"><a name="p19984433351"></a><a name="p19984433351"></a>EDSR</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p898473314517"><a name="p898473314517"></a><a name="p898473314517"></a>-</p>
</td>
</tr>
<tr id="row17953357517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p14984123312515"><a name="p14984123312515"></a><a name="p14984123312515"></a>Tsm</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p159841033855"><a name="p159841033855"></a><a name="p159841033855"></a>-</p>
</td>
</tr>
<tr id="row16951435551"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19984933457"><a name="p19984933457"></a><a name="p19984933457"></a>pnasnet5large</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p89846335512"><a name="p89846335512"></a><a name="p89846335512"></a>-</p>
</td>
</tr>
<tr id="row2095113520514"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1798416331952"><a name="p1798416331952"></a><a name="p1798416331952"></a>Gaitset</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p098417336516"><a name="p098417336516"></a><a name="p098417336516"></a>-</p>
</td>
</tr>
<tr id="row89516351511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p11985153312516"><a name="p11985153312516"></a><a name="p11985153312516"></a>fcn</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p169858331155"><a name="p169858331155"></a><a name="p169858331155"></a>-</p>
</td>
</tr>
<tr id="row5953353513"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p18985103311514"><a name="p18985103311514"></a><a name="p18985103311514"></a>Albert</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p2098513334519"><a name="p2098513334519"></a><a name="p2098513334519"></a>-</p>
</td>
</tr>
<tr id="row119533516513"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p598511336511"><a name="p598511336511"></a><a name="p598511336511"></a>AdvancedEast</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p119850331513"><a name="p119850331513"></a><a name="p119850331513"></a>-</p>
</td>
</tr>
<tr id="row39511356512"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p698553311512"><a name="p698553311512"></a><a name="p698553311512"></a>ReidStrongBaseline</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1198514331659"><a name="p1198514331659"></a><a name="p1198514331659"></a>-</p>
</td>
</tr>
<tr id="row129463518517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p99851633158"><a name="p99851633158"></a><a name="p99851633158"></a>Fast-scnn</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1298514331359"><a name="p1298514331359"></a><a name="p1298514331359"></a>-</p>
</td>
</tr>
<tr id="row9942035757"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p109854331151"><a name="p109854331151"></a><a name="p109854331151"></a>RDN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1198583317511"><a name="p1198583317511"></a><a name="p1198583317511"></a>-</p>
</td>
</tr>
<tr id="row79415357517"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6985833351"><a name="p6985833351"></a><a name="p6985833351"></a>SRFlow</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p29851033350"><a name="p29851033350"></a><a name="p29851033350"></a>-</p>
</td>
</tr>
<tr id="row12947357514"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p149859334518"><a name="p149859334518"></a><a name="p149859334518"></a>MGN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19851833850"><a name="p19851833850"></a><a name="p19851833850"></a>-</p>
</td>
</tr>
<tr id="row3941735855"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p898533316518"><a name="p898533316518"></a><a name="p898533316518"></a>Roberta</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p998553318518"><a name="p998553318518"></a><a name="p998553318518"></a>-</p>
</td>
</tr>
<tr id="row1093335856"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1985533451"><a name="p1985533451"></a><a name="p1985533451"></a>RegNetY</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p59851033355"><a name="p59851033355"></a><a name="p59851033355"></a>-</p>
</td>
</tr>
<tr id="row49373518516"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p19986173311512"><a name="p19986173311512"></a><a name="p19986173311512"></a>VoVNet-39</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p798683310515"><a name="p798683310515"></a><a name="p798683310515"></a>-</p>
</td>
</tr>
<tr id="row5930351357"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p189862336515"><a name="p189862336515"></a><a name="p189862336515"></a>RegNetX</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1398618331651"><a name="p1398618331651"></a><a name="p1398618331651"></a>-</p>
</td>
</tr>
<tr id="row169312351655"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p149863337513"><a name="p149863337513"></a><a name="p149863337513"></a>RefineNet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p2098615331959"><a name="p2098615331959"></a><a name="p2098615331959"></a>-</p>
</td>
</tr>
<tr id="row11931235957"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1198616331657"><a name="p1198616331657"></a><a name="p1198616331657"></a>RefineDet</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1698611332518"><a name="p1698611332518"></a><a name="p1698611332518"></a>-</p>
</td>
</tr>
<tr id="row189215359511"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p16986183319512"><a name="p16986183319512"></a><a name="p16986183319512"></a>AlignedReID</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1898715331055"><a name="p1898715331055"></a><a name="p1898715331055"></a>-</p>
</td>
</tr>
<tr id="row89213351858"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p119878330511"><a name="p119878330511"></a><a name="p119878330511"></a>FaceBoxes</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p129878331158"><a name="p129878331158"></a><a name="p129878331158"></a>-</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization of CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6, Ubuntu 18.04, BC-Linux 7.6, Debian 9.9, Debian 10, openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6, Euler 2.8, Kylin v10, BC-Linux 7.6, openEuler 20.03 LTS, UOS 20 1020e
## FrameworkPTAdapter 2.0.2
### Before You Start
This framework is modified based on the open-source PyTorch 1.5.0 primarily developed by Facebook, inherits native PyTorch features, and uses NPUs for dynamic image training. Models are adapted by operator granularity, code can be reused, and current networks can be ported and used on NPUs with only device types or data types modified.
### New Features
**Table 1** Features supported by PyTorch
<table><thead align="left"><tr id="r0c10e7163bf54fe8816ab5ca2d77ccc4"><th class="cellrowborder" valign="top" width="10.489999999999998%" id="mcps1.2.4.1.1"><p id="a7888762cf8294977b7d114b1c898d1bd"><a name="a7888762cf8294977b7d114b1c898d1bd"></a><a name="a7888762cf8294977b7d114b1c898d1bd"></a>Level-1 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="26.3%" id="mcps1.2.4.1.2"><p id="a4581ffde4a5f455faadfba144243a9d4"><a name="a4581ffde4a5f455faadfba144243a9d4"></a><a name="a4581ffde4a5f455faadfba144243a9d4"></a>Level-2 Feature</p>
</th>
<th class="cellrowborder" valign="top" width="63.21%" id="mcps1.2.4.1.3"><p id="a2a1562364b09433a83133fa10b3cf2b3"><a name="a2a1562364b09433a83133fa10b3cf2b3"></a><a name="a2a1562364b09433a83133fa10b3cf2b3"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row171322953713"><td class="cellrowborder" rowspan="7" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p10237517181"><a name="p10237517181"></a><a name="p10237517181"></a>Adapted training models</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p6134294377"><a name="p6134294377"></a><a name="p6134294377"></a>YOLOv4</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p314533811397"><a name="p314533811397"></a><a name="p314533811397"></a>-</p>
</td>
</tr>
<tr id="row15990182233714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p399019224374"><a name="p399019224374"></a><a name="p399019224374"></a>YOLOv3</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1714553816396"><a name="p1714553816396"></a><a name="p1714553816396"></a>-</p>
</td>
</tr>
<tr id="row5301255373"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1530325123719"><a name="p1530325123719"></a><a name="p1530325123719"></a>DB</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p5146193819390"><a name="p5146193819390"></a><a name="p5146193819390"></a>-</p>
</td>
</tr>
<tr id="row274203413712"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p197423343379"><a name="p197423343379"></a><a name="p197423343379"></a>RFCN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p15828941153919"><a name="p15828941153919"></a><a name="p15828941153919"></a>-</p>
</td>
</tr>
<tr id="row78671918163714"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p188671318183713"><a name="p188671318183713"></a><a name="p188671318183713"></a>CRNN</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p10828241123917"><a name="p10828241123917"></a><a name="p10828241123917"></a>-</p>
</td>
</tr>
<tr id="row16912221171"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p6913132676"><a name="p6913132676"></a><a name="p6913132676"></a>Densenset161</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p209131221474"><a name="p209131221474"></a><a name="p209131221474"></a>-</p>
</td>
</tr>
<tr id="row1016073314719"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p3160153320717"><a name="p3160153320717"></a><a name="p3160153320717"></a>Densenset191</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p1516012331173"><a name="p1516012331173"></a><a name="p1516012331173"></a>-</p>
</td>
</tr>
<tr id="row9627165910386"><td class="cellrowborder" rowspan="4" valign="top" width="10.489999999999998%" headers="mcps1.2.4.1.1 "><p id="p1561535993811"><a name="p1561535993811"></a><a name="p1561535993811"></a>PyTorch features adapted to NPUs</p>
</td>
<td class="cellrowborder" valign="top" width="26.3%" headers="mcps1.2.4.1.2 "><p id="p136151659163819"><a name="p136151659163819"></a><a name="p136151659163819"></a>Basic framework functions</p>
</td>
<td class="cellrowborder" valign="top" width="63.21%" headers="mcps1.2.4.1.3 "><p id="p1661535983813"><a name="p1661535983813"></a><a name="p1661535983813"></a>Added the function of adapted operator development. For details, see the operator list.</p>
</td>
</tr>
<tr id="row7627155917380"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p1561525916383"><a name="p1561525916383"></a><a name="p1561525916383"></a>Model Accuracy Analyzer</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p19616115953816"><a name="p19616115953816"></a><a name="p19616115953816"></a>Added the Model Accuracy Analyzer and supported training accuracy demarcation.</p>
</td>
</tr>
<tr id="row46269593383"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p0616559163819"><a name="p0616559163819"></a><a name="p0616559163819"></a>Ascend 710 AI Processor</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p186161459193813"><a name="p186161459193813"></a><a name="p186161459193813"></a>Supported the online inference on Ascend 710 AI Processors.</p>
</td>
</tr>
<tr id="row76261059153817"><td class="cellrowborder" valign="top" headers="mcps1.2.4.1.1 "><p id="p11616175953812"><a name="p11616175953812"></a><a name="p11616175953812"></a>OS compatibility</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.4.1.2 "><p id="p8935115971714"><a name="p8935115971714"></a><a name="p8935115971714"></a>Supported Ubuntu 18.04.5 and openEuler 20.03 LTS.</p>
</td>
</tr>
</tbody>
</table>
### Modified Features
N/A
### Resolved Issues
N/A
### Known Issues
<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>Known Issue</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>Description</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>Data type support</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>NPUs do not support the input or output of the inf/nan data of the float16 type.</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>Data 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>Dimensions cannot be reduced when the format larger than 4D is used.</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>Restrictions on collective communication</p>
<p id="p0465121912402"><a name="p0465121912402"></a><a name="p0465121912402"></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>The graphs executed on different devices in a training job must be the same.</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>Allocation at only 1, 2, 4, or 8 processors is supported.</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>Only the int8, int32, float16, and float32 data types are supported.</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 function</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>In the current version, Apex is implemented mainly using Python, and the customized optimization CUDA kernel in Apex is not supported.</p>
</td>
</tr>
</tbody>
</table>
### Compatibility
Atlas 800 (model 9010): CentOS 7.6/Ubuntu 18.04/BC-Linux 7.6/Debian 9.9/Debian 10/openEuler 20.03 LTS
Atlas 800 (model 9000): CentOS 7.6/EulerOS 2.8/Kylin v10/BC-Linux 7.6/openEuler 20.03 LTS
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff

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

File diff suppressed because it is too large Load Diff

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

@@ -0,0 +1,555 @@
# PyTorch Installation Guide
- [Overview](#overviewmd)
- [Manual Build and Installation](#manual-build-and-installationmd)
- [Prerequisites](#prerequisitesmd)
- [Installing the PyTorch Framework](#installing-the-pytorch-frameworkmd)
- [Configuring Environment Variables](#configuring-environment-variablesmd)
- [Installing the Mixed Precision Module](#installing-the-mixed-precision-modulemd)
- [References](#referencesmd)
- [Installing CMake](#installing-cmakemd)
- [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0md)
- [What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?](#what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installedmd)
<h2 id="overviewmd">Overview</h2>
When setting up the environment for PyTorch model development and running, you can manually build and install the modules adapted to the PyTorch framework on a server.
**Figure 1** Environment setup process<a name="en-us_topic_0000001119176876_fig1938918396117"></a>
![](figures/210926103326800.png)
<h2 id="manual-build-and-installationmd">Manual Build and Installation</h2>
- **[Prerequisites](#prerequisitesmd)**
- **[Installing the PyTorch Framework](#installing-the-pytorch-frameworkmd)**
- **[Configuring Environment Variables](#configuring-environment-variablesmd)**
- **[Installing the Mixed Precision Module](#installing-the-mixed-precision-modulemd)**
<h3 id="prerequisitesmd">Prerequisites</h3>
#### Prerequisites<a name="en-us_topic_0000001105856382_en-us_topic_0275872734_section108914373254"></a>
- The development or operating environment of CANN has been installed. For details, see the _CANN Software Installation Guide_.
- CMake 3.12.0 or later has been installed. For details about how to install CMake, see [Installing CMake](#installing-cmakemd).
- GCC 7.3.0 or later has been installed. For details about how to install and use GCC 7.3.0, see [How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0md).
- Python 3.7.5 or 3.8 has been installed.
- The Patch and Git tools have been installed in the environment. To install the tools for Ubuntu and CentOS, run the following commands:
- Ubuntu
```
apt-get install patch
apt-get install git
```
- CentOS
```
yum install patch
yum install git
```
<h3 id="installing-the-pytorch-frameworkmd">Installing the PyTorch Framework</h3>
#### Installation Process<a name="en-us_topic_0000001152776301_section1611810384557"></a>
1. Log in to the server as the **root** user or a non-root user.
2. Run the following commands in sequence to install the PyTorch dependencies.
If you install Python and its dependencies as a non-root user, add **--user** at the end of each command in this step. Example command: **pip3.7 install pyyaml --user**.
```
pip3 install pyyaml
pip3 install wheel
```
3. Obtain the PyTorch source code.
1. Run the following command to obtain the PyTorch source code adapted to Ascend AI Processors:
```
git clone https://gitee.com/ascend/pytorch.git
```
The directory structure of the downloaded source code is as follows:
```
├── patch # Directory of the patch adapted to Ascend AI Processors
│ ├── pytorch1.5.0_npu.patch # Patch for PyTorch 1.5.0
│ └── pytorch1.8.1_npu.patch # Patch for PyTorch 1.8.1
├── pytorch1.5.0 # Source code and test directory for PyTorch 1.5.0
│ ├── access_control_test.py
│ ├── src # Source code directory
│ └── test # Directory for storing test cases
├── pytorch1.8.1 # Source code and test directory for PyTorch 1.8.1
│ ├── access_control_test.py
│ ├── src # Source code directory
│ └── test # Directory for storing test cases
└── scripts # Build and create a directory.
```
2. Obtain the native PyTorch source code from the root directory **/pytorch** of the current repository.
- If PyTorch 1.5.0 is installed, run the following command:
```
git clone -b v1.5.0 --depth=1 https://github.com/pytorch/pytorch.git
```
- If PyTorch 1.8.1 is installed, run the following command:
```
git clone -b v1.8.1 --depth=1 https://github.com/pytorch/pytorch.git
```
3. Run the following commands to go to the native PyTorch code directory **pytorch** and obtain the PyTorch passive dependency code:
```
cd pytorch
git submodule sync
git submodule update --init --recursive
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Due to network fluctuation, it may take a long time to obtain the source code. If no error is reported after the download is complete, the PyTorch and third-party code on which PyTorch depends are generated.
4. Generate the PyTorch installation package adapted to Ascend AI Processors.
1. Go to the **pytorch/scripts** directory and run the conversion script to generate full code adapted to Ascend AI Processors.
```
cd ../scripts
# If PyTorch 1.5.0 is installed:
bash gen.sh
# If PyTorch 1.8.1 is installed:
bash gen.sh -v 1.8.1
```
The full code adapted to Ascend AI Processors is generated in the **pytorch/pytorch** directory.
2. Go to the **pytorch/pytorch/** directory and install the dependency library.
```
cd ../pytorch
pip3 install -r requirements.txt
```
3. Build and generate the binary installation package of PyTorch.
```
bash build.sh --python=3.7
or
bash build.sh --python=3.8
```
Specify the Python version in the environment for build. The generated binary package is stored in the current dist directory **pytorch/pytorch/dist**.
5. <a name="en-us_topic_0000001152776301_li49671667141"></a>Install PyTorch.
Go to the **pytorch/pytorch/dist** directory and run the following command to install PyTorch:
```
pip3 install --upgrade torch-1.5.0+ascend.post3-cp37-cp37m-linux_{arch}.whl
```
_\{**arch\}**_ indicates the architecture information. The value can be **aarch64** or **x86\_64**.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade PyTorch in the environment, uninstall the PyTorch software package installed in the environment and then perform [Step 5 Install PyTorch](#en-us_topic_0000001152776301_li49671667141). Run the following command to check whether PyTorch has been installed:
>**pip3 list | grep torch**
<h3 id="configuring-environment-variablesmd">Configuring Environment Variables</h3>
After the software packages are installed, configure environment variables to use Ascend PyTorch. For details about the environment variables, see [Table 1](#en-us_topic_0000001152616261_table42017516135).
1. Configure the operating environment variables by running the following command in the **root** directory of the PyTorch source code adapted to Ascend AI Processors:
```
source pytorch/env.sh
```
2. Select a proper HCCL initialization mode based on the actual scenario and configure the corresponding environment variables.
```
# Scenario 1: Single-node scenario
export HCCL_WHITELIST_DISABLE=1 # Disable the HCCL trustlist.
# Scenario 2: Multi-node scenario
export HCCL_WHITELIST_DISABLE=1 # Disable the HCCL trustlist.
export HCCL_IF_IP="1.1.1.1" # 1.1.1.1 is the NIC IP address of the host. Change it based on the site requirements. Ensure that the NIC IP addresses in use can communicate with each other in the cluster.
```
3. \(Optional\) Configure function or performance environment variables in the NPU scenario. The variables are disabled by default.
```
export DYNAMIC_COMPILE_ENABLE=1 # (Optional) Dynamic shape feature, which is used when the shape changes. To enable this function, set the value to 1. (PyTorch 1.8.1 does not support this environment variable.)
export COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to 1.
export TRI_COMBINED_ENABLE=1 # (Optional) Optimizes the scenario where three inconsecutive operators are combined. To enable this function, set the value to 1.
export ACL_DUMP_DATA=1 # (Optional) Operator data dump function, which is used for debugging. To enable this function, set the value to 1.
export DYNAMIC_OP="ADD#MUL" # (Optional) Operator implementation. The performance of the ADD and MUL operators varies depending on the scenarios.
```
4. \(Optional\) If the system is openEuler or its inherited OS, such as UOS, run the following command to cancel CPU core binding.
```
# unset GOMP_CPU_AFFINITY
```
**Table 1** Description of environment variables
<a name="en-us_topic_0000001152616261_table42017516135"></a>
<table><thead align="left"><tr id="en-us_topic_0000001152616261_row16198951191317"><th class="cellrowborder" valign="top" width="55.48%" id="mcps1.2.3.1.1"><p id="en-us_topic_0000001152616261_p51981251161315"><a name="en-us_topic_0000001152616261_p51981251161315"></a><a name="en-us_topic_0000001152616261_p51981251161315"></a>Environment Variable</p>
</th>
<th class="cellrowborder" valign="top" width="44.519999999999996%" id="mcps1.2.3.1.2"><p id="en-us_topic_0000001152616261_p9198135114133"><a name="en-us_topic_0000001152616261_p9198135114133"></a><a name="en-us_topic_0000001152616261_p9198135114133"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="en-us_topic_0000001152616261_row6882121917329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p688241953218"><a name="en-us_topic_0000001152616261_p688241953218"></a><a name="en-us_topic_0000001152616261_p688241953218"></a>LD_LIBRARY_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p1888291915322"><a name="en-us_topic_0000001152616261_p1888291915322"></a><a name="en-us_topic_0000001152616261_p1888291915322"></a>Dynamic library search path. Set this variable based on the preceding example.</p>
<p id="p1292181892120"><a name="p1292181892120"></a><a name="p1292181892120"></a>If you need to upgrade GCC in OSs such as CentOS, Debian, and BC-Linux, add <strong id="b6163826603"><a name="b6163826603"></a><a name="b6163826603"></a><em id="i161631926505"><a name="i161631926505"></a><a name="i161631926505"></a>${install_path}</em>/lib64</strong> to the <span class="parmname" id="parmname161637265015"><a name="parmname161637265015"></a><a name="parmname161637265015"></a><b>LD_LIBRARY_PATH</b></span> variable of the dynamic library search path. Replace <em id="i01649261704"><a name="i01649261704"></a><a name="i01649261704"></a><strong id="b1216317261109"><a name="b1216317261109"></a><a name="b1216317261109"></a>{install_path}</strong></em> with the GCC installation path. For details, see <a href="#how-do-i-install-gcc-7-3-0md#en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li9745165315131">5</a>.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row16194175523010"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p16195185523019"><a name="en-us_topic_0000001152616261_p16195185523019"></a><a name="en-us_topic_0000001152616261_p16195185523019"></a>PYTHONPATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p19637083322"><a name="en-us_topic_0000001152616261_p19637083322"></a><a name="en-us_topic_0000001152616261_p19637083322"></a>Python search path. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row2954102119329"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p195452113218"><a name="en-us_topic_0000001152616261_p195452113218"></a><a name="en-us_topic_0000001152616261_p195452113218"></a>PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p964914893211"><a name="en-us_topic_0000001152616261_p964914893211"></a><a name="en-us_topic_0000001152616261_p964914893211"></a>Executable program search path. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row58592816294"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p1886016892913"><a name="en-us_topic_0000001152616261_p1886016892913"></a><a name="en-us_topic_0000001152616261_p1886016892913"></a>ASCEND_OPP_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p28608892915"><a name="en-us_topic_0000001152616261_p28608892915"></a><a name="en-us_topic_0000001152616261_p28608892915"></a>Operator package (OPP) root directory. Set this variable based on the preceding example.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row144592037903"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p104601373014"><a name="en-us_topic_0000001152616261_p104601373014"></a><a name="en-us_topic_0000001152616261_p104601373014"></a>OPTION_EXEC_EXTERN_PLUGIN_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p1046013716017"><a name="en-us_topic_0000001152616261_p1046013716017"></a><a name="en-us_topic_0000001152616261_p1046013716017"></a>Path of the operator information library.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row16184379493"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p131851873492"><a name="en-us_topic_0000001152616261_p131851873492"></a><a name="en-us_topic_0000001152616261_p131851873492"></a>ASCEND_AICPU_PATH</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p181851575497"><a name="en-us_topic_0000001152616261_p181851575497"></a><a name="en-us_topic_0000001152616261_p181851575497"></a>Path of the AI CPU operator package.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row234714854615"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p2034724894619"><a name="en-us_topic_0000001152616261_p2034724894619"></a><a name="en-us_topic_0000001152616261_p2034724894619"></a>TASK_QUEUE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p53477489462"><a name="en-us_topic_0000001152616261_p53477489462"></a><a name="en-us_topic_0000001152616261_p53477489462"></a>Whether to asynchronously deliver tasks and call the ACL APIs. You are advised to set this parameter to <strong id="en-us_topic_0000001152616261_b186701714141819"><a name="en-us_topic_0000001152616261_b186701714141819"></a><a name="en-us_topic_0000001152616261_b186701714141819"></a>1</strong> to enable this function.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row1680820246202"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p4809112415207"><a name="en-us_topic_0000001152616261_p4809112415207"></a><a name="en-us_topic_0000001152616261_p4809112415207"></a>HCCL_WHITELIST_DISABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p952814428206"><a name="en-us_topic_0000001152616261_p952814428206"></a><a name="en-us_topic_0000001152616261_p952814428206"></a>Whether to enable the communication trustlist when the HCCL is used.</p>
<a name="ul928845132310"></a><a name="ul928845132310"></a><ul id="ul928845132310"><li><strong id="b12793231525"><a name="b12793231525"></a><a name="b12793231525"></a>0</strong>: enable the trustlist. The HCCL communication trustlist does not need to be verified.</li><li><strong id="b1146142619212"><a name="b1146142619212"></a><a name="b1146142619212"></a>1</strong>: disable the trustlist. The HCCL communication trustlist needs to be verified.</li></ul>
<p id="en-us_topic_0000001152616261_p5809162416201"><a name="en-us_topic_0000001152616261_p5809162416201"></a><a name="en-us_topic_0000001152616261_p5809162416201"></a>The default value is <strong id="en-us_topic_0000001152616261_b1270332516435"><a name="en-us_topic_0000001152616261_b1270332516435"></a><a name="en-us_topic_0000001152616261_b1270332516435"></a>0</strong>, indicating that the trustlist is enabled by default.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row0671137162115"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p4671203792114"><a name="en-us_topic_0000001152616261_p4671203792114"></a><a name="en-us_topic_0000001152616261_p4671203792114"></a>HCCL_IF_IP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p1822165982114"><a name="en-us_topic_0000001152616261_p1822165982114"></a><a name="en-us_topic_0000001152616261_p1822165982114"></a>IP address of the NIC for initializing communication in the HCCL.</p>
<a name="ul2676102292415"></a><a name="ul2676102292415"></a><ul id="ul2676102292415"><li>The IP address is in dotted decimal notation.</li><li>Currently, only the host NIC is supported.</li></ul>
<p id="en-us_topic_0000001152616261_p1167163719217"><a name="en-us_topic_0000001152616261_p1167163719217"></a><a name="en-us_topic_0000001152616261_p1167163719217"></a>By default, the host communication NICs are selected in the following sequence: NICs other than Docker/local NICs (in ascending alphabetical order of NIC names) &gt; Docker NICs &gt; local NICs.</p>
</td>
</tr>
<tr id="en-us_topic_0000001152616261_row1371356152313"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p15106173103120"><a name="p15106173103120"></a><a name="p15106173103120"></a>PTCOPY_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p71055317311"><a name="p71055317311"></a><a name="p71055317311"></a>Use the PTCopy operator mode to accelerate the operation of converting non-contiguous tensors to contiguous tensors and copy process. You are advised to set the value to <strong id="b114621515513"><a name="b114621515513"></a><a name="b114621515513"></a>1</strong> to enable this function. </p>
</td>
</tr>
<tr id="row743212132309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p17433111312307"><a name="p17433111312307"></a><a name="p17433111312307"></a>ASCEND_SLOG_PRINT_TO_STDOUT</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p6433151393018"><a name="p6433151393018"></a><a name="p6433151393018"></a>(Optional) Whether to enable the log printing function.</p>
<a name="ul760201917473"></a><a name="ul760201917473"></a><ul id="ul760201917473"><li><strong id="b1955232216215"><a name="b1955232216215"></a><a name="b1955232216215"></a>0</strong>: uses the default log output mode.</li><li><strong id="b22913272211"><a name="b22913272211"></a><a name="b22913272211"></a>1</strong>: prints the logs to the screen.</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row19237171814300"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p14238161893019"><a name="p14238161893019"></a><a name="p14238161893019"></a>ASCEND_GLOBAL_LOG_LEVEL</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p223841810303"><a name="p223841810303"></a><a name="p223841810303"></a>Sets the global log level of app logs.</p>
<a name="ul175714586453"></a><a name="ul175714586453"></a><ul id="ul175714586453"><li><strong id="b94698561835"><a name="b94698561835"></a><a name="b94698561835"></a>0</strong>: DEBUG</li><li><strong id="b1612516597314"><a name="b1612516597314"></a><a name="b1612516597314"></a>1</strong>: INFO</li><li><strong id="b82051911547"><a name="b82051911547"></a><a name="b82051911547"></a>2</strong>: WARNING</li><li><strong id="b04351021945"><a name="b04351021945"></a><a name="b04351021945"></a>3</strong>: ERROR</li><li><strong id="b116153316418"><a name="b116153316418"></a><a name="b116153316418"></a>4</strong>: NULL (no log output)</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row1348192313303"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1734815235305"><a name="p1734815235305"></a><a name="p1734815235305"></a>ASCEND_GLOBAL_EVENT_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p12348202373018"><a name="p12348202373018"></a><a name="p12348202373018"></a>Whether to enable event logging for apps.</p>
<a name="ul416352114610"></a><a name="ul416352114610"></a><ul id="ul416352114610"><li><strong id="b425610311940"><a name="b425610311940"></a><a name="b425610311940"></a>0</strong>: disabled</li><li><strong id="b198984321741"><a name="b198984321741"></a><a name="b198984321741"></a>1</strong>: enabled</li><li>Other values: invalid</li></ul>
</td>
</tr>
<tr id="row17878184693015"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p1878194683016"><a name="p1878194683016"></a><a name="p1878194683016"></a>DYNAMIC_COMPILE_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p1887894620304"><a name="p1887894620304"></a><a name="p1887894620304"></a>(Optional) Dynamic shape feature, which is used when the shape changes. To enable this function, set the value to <strong id="b11281447194117"><a name="b11281447194117"></a><a name="b11281447194117"></a>1</strong>. (PyTorch 1.8.1 does not support this environment variable.)</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) Optimizes the scenario where two inconsecutive operators are combined. To enable this function, set the value to <strong id="b19824817612"><a name="b19824817612"></a><a name="b19824817612"></a>1</strong>.</p>
</td>
</tr>
<tr id="row17630155212342"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p66309527341"><a name="p66309527341"></a><a name="p66309527341"></a>RI_COMBINED_ENABLE</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p19630185220345"><a name="p19630185220345"></a><a name="p19630185220345"></a>(Optional) Optimizes the scenario where three inconsecutive operators are combined. To enable this function, set the value to <strong id="b10522121418612"><a name="b10522121418612"></a><a name="b10522121418612"></a>1</strong>.</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 <strong id="b1861154419918"><a name="b1861154419918"></a><a name="b1861154419918"></a>1</strong>.</p>
</td>
</tr>
<tr id="row27481914203518"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="p674813144357"><a name="p674813144357"></a><a name="p674813144357"></a>DYNAMIC_OP</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="p974891414353"><a name="p974891414353"></a><a name="p974891414353"></a>(Optional) Operator implementation. The performance of the ADD and MUL operators varies depending on the scenarios. This parameter is not set by default.</p>
</td>
</tr>
<tr id="row19173161510309"><td class="cellrowborder" valign="top" width="55.48%" headers="mcps1.2.3.1.1 "><p id="en-us_topic_0000001152616261_p16711563237"><a name="en-us_topic_0000001152616261_p16711563237"></a><a name="en-us_topic_0000001152616261_p16711563237"></a>unset GOMP_CPU_AFFINITY</p>
</td>
<td class="cellrowborder" valign="top" width="44.519999999999996%" headers="mcps1.2.3.1.2 "><p id="en-us_topic_0000001152616261_p0711356152317"><a name="en-us_topic_0000001152616261_p0711356152317"></a><a name="en-us_topic_0000001152616261_p0711356152317"></a>(Optional) If the system is openEuler or its inherited OS, such as UOS, run this command to cancel CPU core binding.</p>
</td>
</tr>
</tbody>
</table>
<h3 id="installing-the-mixed-precision-modulemd">Installing the Mixed Precision Module</h3>
#### Prerequisites<a name="en-us_topic_0000001106176190_section3225481020"></a>
1. Ensure that the PyTorch framework adapted to Ascend AI Processors in the operating environment can be used properly.
2. Before building and installing Apex, you have configured the environment variables on which the build depends. See [Configuring Environment Variables](#configuring-environment-variablesmd).
#### Installation Process<a name="en-us_topic_0000001106176190_section11880164819567"></a>
1. Log in to the server as the **root** user or a non-root user.
2. Obtain the Apex source code.
1. Run the following command to obtain the Apex source code adapted to Ascend AI Processors:
```
git clone -b 2.0.3.tr5 https://gitee.com/ascend/apex.git
```
The directory structure of the downloaded source code is as follows:
```
apex
│ ├─patch # Directory of the patch adapted to Ascend AI Processors
│ ├─npu.patch
│ ├─scripts # Build and create a directory.
│ ├─gen.sh
│ ├─src # Source code directory
│ ├─tests # Directory for storing test cases
```
2. Run the following commands to go to the **apex** directory and obtain the native Apex source code:
```
cd apex
git clone https://github.com/NVIDIA/apex.git
```
After the native Apex source code is downloaded, the main directory structure of the code is as follows:
```
apex
│ ├─apex # Directory for storing the native Apex code
│ ├─patch # Directory of the patch adapted to Ascend AI Processors
│ ├─npu.patch
│ ├─scripts # Build and create a directory.
│ ├─gen.sh
│ ├─src # Source code directory
│ ├─tests # Directory for storing test cases
```
3. Go to the native Apex code directory, that is, **apex/apex**. Switch to the code branch whose commit ID is 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a.
```
cd apex
git checkout 4ef930c1c884fdca5f472ab2ce7cb9b505d26c1a
```
>![](public_sys-resources/icon-note.gif) **NOTE:**
>Due to network fluctuation, it may take a long time to obtain the source code.
3. Generate the Apex installation package adapted to Ascend AI Processors.
1. Go to the **apex/scripts** directory and run the conversion script to generate full code adapted to Ascend AI Processors.
```
cd ../scripts
bash gen.sh
```
The full code adapted to Ascend AI Processors is generated in the **apex/apex** directory.
2. Go to the full code directory **apex/apex**, and compile and generate the binary installation package of Apex.
```
cd ../apex
python3 setup.py --cpp_ext --npu_float_status bdist_wheel
```
The Python version must be the same as that used by PyTorch. The generated binary package is stored in the current **dist** directory, that is, **apex/apex/dist**.
4. <a name="en-us_topic_0000001106176190_li425495374416"></a>Install Apex.
Go to the **apex/apex/dist** directory and run the following command to install Apex:
```
pip3 install --upgrade apex-0.1+ascend-cp37-cp37m-linux_{arch}.whl
```
_\{**arch\}**_ indicates the architecture information. The value can be **aarch64** or **x86\_64**.
>![](public_sys-resources/icon-note.gif) **NOTE:**
>To upgrade PyTorch in the environment, uninstall the PyTorch software package installed in the environment and then perform [Step 4 Install Apex](#en-us_topic_0000001106176190_li425495374416). Run the following command to check whether PyTorch has been installed:
>**pip3 list | grep apex**
<h2 id="referencesmd">References</h2>
- **[Installing CMake](#installing-cmakemd)**
- **[How Do I Install GCC 7.3.0?](#how-do-i-install-gcc-7-3-0md)**
- **[What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?](#what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installedmd)**
<h3 id="installing-cmakemd">Installing CMake</h3>
Procedure for upgrading CMake to 3.12.1
1. Obtain the CMake software package.
```
wget https://cmake.org/files/v3.12/cmake-3.12.1.tar.gz --no-check-certificate
```
2. Decompress the package and go to the software package directory.
```
tar -xf cmake-3.12.1.tar.gz
cd cmake-3.12.1/
```
3. Run the configuration, build, 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.1" is displayed, the installation is successful.
<h3 id="how-do-i-install-gcc-7-3-0md">How Do I Install GCC 7.3.0?</h3>
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. Build 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 run the following command to 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 validation fails, check whether the dependency packages are repeatedly downloaded. The packages should be downloaded at a time.
3. <a name="en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li1649343041310"></a>Run the configuration, build, 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.
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**.
5. Set the environment variable.
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](#en-us_topic_0000001135347812_en-us_topic_0000001173199577_en-us_topic_0000001172534867_en-us_topic_0276688294_li1649343041310). In this example, the GCC 7.3.0 installation path is **/usr/local/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.
<h3 id="what-do-i-do-if-torch-1-5-0xxxx-and-torchvision-do-not-match-when-torch--whl-is-installedmd">What Do I Do If "torch 1.5.0xxxx" and "torchvision" Do Not Match When torch-\*.whl Is Installed?</h3>
#### Symptom<a name="en-us_topic_0000001105856364_en-us_topic_0175549220_section197270431505"></a>
During the 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.
![](figures/en-us_image_0000001190081735.png)
#### Possible Causes<a name="en-us_topic_0000001105856364_en-us_topic_0175549220_section169499490501"></a>
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.
#### Solution<a name="en-us_topic_0000001105856364_section108142031907"></a>
This problem has no impact on the actual result, and no action is required.
Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 946 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 946 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 356 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 329 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 607 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

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