已合并
add test_nn upstream npu patch #35671
dinglaiping创建于 5月14日
add test_nn upstream npu patch #35671
已合并
dinglaiping创建于 5月14日
从已删除 :addpatchfiles-2.11.0合入到Ascend/pytorchv2.11.0
dinglaiping成员
5月14日

【合入来源】

https://gitcode.com/Ascend/pytorch/issues/1945\

【修改方案】

请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列
如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)

2.9 2.10 2.11版本版本新增 test/test_nn.py 的 upstream NPU 适配 patch。此前这些版本在 torch-npu 中没有对应的 test_nn.py.patch,因此 test_nn.py 中部分 nn.Module 基础能力测试、CUDA-only 测试以及 CUDA 设备假设逻辑无法在 NPU 后端上有效覆盖或运行。

本次新增的 patch 主要包含以下修改:

  1. 引入 torch-npu 兼容能力

新增:
import torch_npu
from torch_npu.contrib import transfer_to_npu
这样可以在 upstream 测试中启用 torch-npu 相关兼容逻辑,使部分 CUDA 风格的测试代码能够迁移到 NPU 后端执行。

  1. 增加 NPU 环境下 CUDA capability / TF32 兼容处理
    新增:
    if (acc := torch.accelerator.current_accelerator()) and acc.type == "npu":
    torch.cuda.get_device_capability = lambda *args, **kwargs: (0, 0)
    torch.cuda.is_tf32_supported = lambda: False

原因是 test_nn.py 中存在 CUDA capability 和 TF32 相关判断。NPU 环境下这些 CUDA/TF32 能力不适用,如果不做兼容,
测试可能会错误进入 CUDA/TF32 分支,或者因访问 CUDA 专有能力接口导致异常。这里在 NPU 环境下显式关闭 TF32 能力判
断,避免生成或执行不适合 NPU 的测试路径。

  1. 将更多 TestNN 基础模块测试迁移到 NPU

本次把大量原本默认在 CPU 上构造的 module、parameter、buffer 和 tensor 显式迁移到 NPU,例如:

nn.Linear(...).npu()
nn.Conv2d(...).npu()
nn.BatchNorm2d(...).npu()
torch.rand(..., device="npu")
torch.empty(..., device="npu")
nn.Parameter(torch.randn(..., device="npu"))
Buffer(torch.rand(..., device="npu"))

覆盖的测试类型包括:

  • parameters() / named_parameters()
  • buffers() / named_buffers()
  • register_buffer() / register_parameter()
  • Sequential
  • ModuleList
  • ModuleDict
  • ParameterList
  • ParameterDict
  • state_dict
  • module attribute assignment
  • parameters_to_vector / vector_to_parameters
  • requires_grad_
  • module children/modules traversal
  • parameter/buffer 覆盖、删除、持久化等场景

这样可以确保这些基础 nn.Module 行为不仅在 CPU tensor 上被验证,也能覆盖 NPU tensor/module 在参数注册、buffer
管理、容器模块、state_dict 和属性赋值等场景下的行为。

  1. 放开部分 CUDA-only 测试,使其能够生成 NPU 用例

移除了部分 @onlyCUDA 限制,涉及:

  • test_batchnorm_large_batch
  • test_MarginLoss_warnings
  • test_mse_loss_error
  • test_masked_softmax_transformer_layout
  • test_masked_softmax_TxT_layout
  • test_overwrite_module_params_on_conversion_cpu_device
  • test_layernorm_weight_bias

这些测试本身并不是只适用于 CUDA,去掉 @onlyCUDA 后可以让 PyTorch device-type 测试框架生成 NPU 版本,从而补充
NPU 后端覆盖。

  1. 将 masked softmax 中的 CUDA 专用迁移改成通用 device 迁移

将原来的 CUDA 判断:

if self.device_type == "cuda":
input = input.cuda()
mask = mask.cuda()

改为:

input = input.to(device)
mask = mask.to(device)

这样测试逻辑不再绑定 CUDA,可以在 NPU device-type 测试中使用相同逻辑运行。

  1. 去除硬编码 CUDA 设备断言

例如将:

self.assertTrue(mw._base[0][0].device.type == "cuda")

修改为:

self.assertTrue(mw._base[0][0].device.type == torch.device(device).type)

这样断言表达的是“module 参数迁移到了目标 device”,而不是固定要求目标设备必须是 CUDA,从而适配 NPU 后端。

修改原因

2.9、2.10、2.11 原本没有 test_nn.py 的 torch-npu upstream patch,导致以下问题:

  • 很多 nn.Module 基础语义测试仍然只在 CPU tensor/module 上执行;
  • 部分 CUDA-only 装饰器会阻止 NPU 版本测试生成;
  • 部分测试逻辑硬编码 .cuda() 或 "cuda",无法直接适配 NPU;
  • CUDA capability / TF32 判断在 NPU 环境下不适用。

本次 patch 的目标是:在尽量保持 upstream 测试语义不变的前提下,只调整设备放置和设备判断逻辑,让这些用例能够真
实覆盖 NPU 后端。

影响范围

  • 新增 2.9、2.10、2.11 的 test_nn.py.patch。
  • 仅影响 upstream 测试适配,不修改 torch-npu 运行时实现逻辑。
  • 三个版本的修改内容基本一致,主要差异是 upstream test_nn.py 的行号和原始 blob 不同。

【资料变更】

“不涉及”

【接口变更】

“不涉及”

【功能验证】

说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤
新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图

执行修改过的用例命令是:

python -m unittest \
      test_nn.TestNN.test_ModuleDict \
      test_nn.TestNN.test_ModuleList \
      test_nn.TestNN.test_ParameterDict \
      test_nn.TestNN.test_ParameterDict_replication \
      test_nn.TestNN.test_ParameterList \
      test_nn.TestNN.test_ParameterList_replication \
      test_nn.TestNN.test_RNN_nonlinearity \
      test_nn.TestNN.test_RNN_nonlinearity_passed_as_arg \
      test_nn.TestNN.test_Sequential_add \
      test_nn.TestNN.test_Sequential_append \
      test_nn.TestNN.test_Sequential_delitem \
      test_nn.TestNN.test_Sequential_extend \
      test_nn.TestNN.test_Sequential_getitem \
      test_nn.TestNN.test_Sequential_iadd \
      test_nn.TestNN.test_Sequential_imul \
      test_nn.TestNN.test_Sequential_insert \
      test_nn.TestNN.test_Sequential_insert_fail_case \
      test_nn.TestNN.test_Sequential_mul \
      test_nn.TestNN.test_Sequential_pop \
      test_nn.TestNN.test_Sequential_rmul \
      test_nn.TestNN.test_Sequential_setitem \
      test_nn.TestNN.test_Sequential_setitem_named \
      test_nn.TestNN.test_add_module \
      test_nn.TestNN.test_add_module_raises_error_if_attr_exists \
      test_nn.TestNN.test_assignment \
      test_nn.TestNN.test_buffer_bad_module_subclass \
      test_nn.TestNN.test_buffer_not_persistent \
      test_nn.TestNN.test_buffer_not_persistent_assign \
      test_nn.TestNN.test_buffer_not_persistent_del \
      test_nn.TestNN.test_buffer_not_persistent_load \
      test_nn.TestNN.test_buffer_not_persistent_overwrite \
      test_nn.TestNN.test_buffers_and_named_buffers \
      test_nn.TestNN.test_call_supports_python_dict_output \
      test_nn.TestNN.test_children \
      test_nn.TestNN.test_dir \
      test_nn.TestNN.test_dir_digit \
      test_nn.TestNN.test_get_buffer \
      test_nn.TestNN.test_get_buffer_from_submodules \
      test_nn.TestNN.test_module_apply_inplace_op \
      test_nn.TestNN.test_module_to_argparse \
      test_nn.TestNN.test_modules \
      test_nn.TestNN.test_named_children \
      test_nn.TestNN.test_named_modules \
      test_nn.TestNN.test_named_parameters_remove_duplicate \
      test_nn.TestNN.test_non_leaf_parameters \
      test_nn.TestNN.test_parameter_assignment \
      test_nn.TestNN.test_parameterlistdict_setting_attributes \
      test_nn.TestNN.test_parameters_and_named_parameters \
      test_nn.TestNN.test_parameters_to_vector \
      test_nn.TestNN.test_register_buffer_allows_overwriting_with_same_name \
      test_nn.TestNN.test_register_buffer_raises_error_if_attr_exists \
      test_nn.TestNN.test_register_buffer_raises_error_if_name_is_not_string \
      test_nn.TestNN.test_register_parameter_allows_overwriting_with_same_name \
      test_nn.TestNN.test_register_parameter_raises_error_if_attr_exists \
      test_nn.TestNN.test_register_parameter_raises_error_if_name_is_not_string \
      test_nn.TestNN.test_repr \
      test_nn.TestNN.test_requires_grad_ \
      test_nn.TestNN.test_set_submodule \
      test_nn.TestNN.test_state_dict \
      test_nn.TestNN.test_train_errors_for_invalid_mode \
      test_nn.TestNN.test_vector_to_parameters \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_MarginLoss_warnings_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_batchnorm_large_batch_npu_float16 \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_batchnorm_large_batch_npu_float32 \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_layernorm_weight_bias_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_masked_softmax_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_masked_softmax_TxT_layout_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_masked_softmax_forward_with_nans_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_masked_softmax_grad_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_masked_softmax_transformer_layout_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_mse_loss_error_npu \
      test_nn.TestNNDeviceTypePRIVATEUSE1.test_overwrite_module_params_on_conversion_cpu_device_npu

日志如下

................................/usr/local/python/lib/python3.11/site-packages/torch/nn/modules/module.py:1866: FutureWarning: Using non-full backward hooks on a Module that does not return a single Tensor or a tuple of Tensors is deprecated and will be removed in future versions. This hook will be missing some of the grad_output. Please use register_full_backward_hook to get the documented behavior.
  self._maybe_warn_non_full_backward_hook(args, result, grad_fn)
.............................[W515 00:43:08.276193015 compiler_depend.ts:250] Warning: CAUTION: The operator 'aten::multi_margin_loss' is not currently supported on the NPU backend and will fall back to run on the CPU. This may have performance implications. (function npu_cpu_fallback)
[W515 00:43:08.277161980 compiler_depend.ts:250] Warning: CAUTION: The operator 'aten::multi_margin_loss_backward' is not currently supported on the NPU backend and will fall back to run on the CPU. This may have performance implications. (function npu_cpu_fallback)
....[W515 00:43:08.339054026 compiler_depend.ts:47] Warning: CAUTION: The operator aten::_masked_softmax need to be met the following conditions to run on the NPU backend: 1. dim = None/dim = -1/dim = input.dim()-1; 2. mask_type = 2; 3. input.dim() = 4. Now this operator will fallback to run on the CPU and may have performance implications. Please check your params. (function operator())
..[W515 00:43:12.646175898 compiler_depend.ts:250] Warning: CAUTION: The operator 'aten::_masked_softmax_backward' is not currently supported on the NPU backend and will fall back to run on the CPU. This may have performance implications. (function npu_cpu_fallback)
.../root/torchnpuapi/guanwang/2.9/pytorch/test/test_nn.py:9393: UserWarning: Using a target size (torch.Size([10])) that is different to the input size (torch.Size([10, 1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
  F.mse_loss(i, t)
..
----------------------------------------------------------------------
Ran 72 tests in 4.467s

OK
root@hostname-fqv42:~/torchnpuapi/guanwang/2.9/pytorch/test# 

【CheckList】

PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x]

likedislike
Pull Request已成功合入, 合并人@ascend-robot
(感谢 dinglaiping 的贡献)
Ddinglaiping成员
5月14日 创建了 pull request,commit 2ea23429
ascend-robot
ascend-robot成员
5月14日 评论:

Thanks for your pull-request.
The full list of commands accepted by me can be found at here。
You can get sig-info at here


PR Approval Progress

✅ Congratulations! All modules have met the lgtm and approve requirements.

Module Approval Details

module lgtm status approve status
test_upstream ✅ 李伟, huangjingwei (2/2) ✅ 李伟 (1/1)

💡 Tip:

  • Committer can comment /approve or /lgtm
  • Commenting /approve implies both code review (lgtm) and intent to merge (approve)

CLA Signature Pass

dinglaiping, thanks for your pull request. All authors of the commits have signed the CLA. 👍

likedislike
ascend-robotascend-robot成员
5月14日 添加了label:ascend-cla/yes
dinglaiping成员
5月14日 评论:

compile

likedislike
ascend-robot
ascend-robot成员
5月14日 评论:

当前仓库存在以下 保护分支 :

Protected Branch Version Release
master
v2.7.1
v2.9.0
v2.11.0
v2.10.0
v2.12.0

评论 /sync <branch1> <branch2> ... 可将当前 PR 修改同步到其它分支(创建同步 PR):
a) 如果当前 PR 是 Open 状态,同步操作将延迟到 PR 被合并时执行
b) 如果当前 PR 已经 Merged,将立即执行同步操作

注意:

  1. /sync 命令可以指定同步到多个分支,仅最后一个 /sync 命令生效
  2. 如果创建的同步 PR 不正确,可通过向同步 PR 的源分支提交轻量级 PR 完善,或使用 /close 命令关闭
likedislike
ascend-robotascend-robot成员
5月14日 添加了label:ci-pipeline-running
ascend-robot
ascend-robot成员
5月14日 评论:
流水线 PR-pipeline_pytorch#22183 运行中
阶段 任务名 状态 详情
编译构建 Build_X86 🕚 >>>
Build_ARM 🕚 >>>
Build_LibTorch_x86 🕚 >>>
Build_LibTorch_ARM 🕚 >>>
Build_X86_torchair 🕚 >>>
Build_ARM_torchair 🕚 >>>
patch_test 🕚 >>>
恶意代码检查 Antipoison 🕚 >>>
编码安全与规范检查 CodeCheck 🕚 >>>
check_error 🕚 >>>
开源片段检查 SCA 🕚 >>>
开发者测试 UT_X86_Part_01 🕚 >>>
UT_X86_Part_02 🕚 >>>
UT_ARM_A3_Part_01 🕚 >>>
UT_ARM_A3_Part_02 🕚 >>>
UT_DIST_X86_Part_01 🕚 >>>
UT_DIST_X86_Part_02 🕚 >>>
UT_DIST_X86_Part_03 🕚 >>>
UT_DIST_X86_Part_04 🕚 >>>
UT_ARM_A2_Part_01 🕚 >>>
UT_ARM_A2_Part_02 🕚 >>>
UT_ARM_A2_Part_03 🕚 >>>
UT_inductor_Part_01_pool 🕚 >>>
UT_inductor_Part_02_pool 🕚 >>>
UT_inductor_Part_03_pool 🕚 >>>
UT_inductor_Part_04_pool 🕚 >>>
UT_DIST_ARM_Part_01 🕚 >>>
UT_DIST_ARM_Part_02 🕚 >>>
UT_DIST_ARM_Part_03 🕚 >>>
UT_DIST_ARM_Part_04 🕚 >>>
流水线 PR-pipeline_pytorch 🕚 >>>
likedislike
ascend-robot
ascend-robot成员
5月14日 评论:

Ascend docs pipeline is running...

likedislike
ascend-robotascend-robot成员
5月14日 添加了label:docs-ci-pipeline-running
ascend-robot
ascend-robot成员
5月14日 评论:

✅ 文档门禁通过!

检查项 检查结果 详情
markdownlint ✅ 已通过 查看详情
link-validity-check ✅ 已通过 查看详情
resource-existence-check ✅ 已通过 查看详情
tag-closed-check ✅ 已通过 查看详情
likedislike
ascend-robotascend-robot成员
5月14日 删除了label:docs-ci-pipeline-running
ascend-robotascend-robot成员
5月14日 添加了label:docs-ci-pipeline-success
ascend-robot
ascend-robot成员
5月14日 评论:

Ascend docs pipeline is running...

likedislike
ascend-robotascend-robot成员
5月14日 删除了label:docs-ci-pipeline-success
ascend-robotascend-robot成员
5月14日 添加了label:docs-ci-pipeline-running
ascend-robot
ascend-robot成员
5月14日 评论:

✅ 文档门禁通过!

检查项 检查结果 详情
markdownlint ✅ 已通过 查看详情
link-validity-check ✅ 已通过 查看详情
resource-existence-check ✅ 已通过 查看详情
tag-closed-check ✅ 已通过 查看详情
likedislike
ascend-robotascend-robot成员
5月14日 删除了label:docs-ci-pipeline-running
ascend-robotascend-robot成员
5月14日 添加了label:docs-ci-pipeline-success
ascend-robotascend-robot成员
5月14日 删除了label:ci-pipeline-running
ascend-robot
ascend-robot成员
5月14日 评论:
流水线 PR-pipeline_pytorch#22183 已完成
阶段 任务名 状态 详情
编译构建 Build_X86 ✅ >>>
Build_ARM ✅ >>>
Build_LibTorch_x86 ✅ >>>
Build_LibTorch_ARM ✅ >>>
Build_X86_torchair 🛑 >>>
Build_ARM_torchair 🛑 >>>
patch_test ✅ >>>
恶意代码检查 Antipoison ✅ >>>
编码安全与规范检查 CodeCheck ✅ >>>
check_error ✅ >>>
开源片段检查 SCA ✅ >>>
开发者测试 UT_X86_Part_01 🛑 >>>
UT_X86_Part_02 🛑 >>>
UT_ARM_A3_Part_01 🛑 >>>
UT_ARM_A3_Part_02 🛑 >>>
UT_DIST_X86_Part_01 🛑 >>>
UT_DIST_X86_Part_02 🛑 >>>
UT_DIST_X86_Part_03 🛑 >>>
UT_DIST_X86_Part_04 🛑 >>>
UT_ARM_A2_Part_01 ✅ >>>
UT_ARM_A2_Part_02 ✅ >>>
UT_ARM_A2_Part_03 ✅ >>>
UT_inductor_Part_01_pool 🛑 >>>
UT_inductor_Part_02_pool 🛑 >>>
UT_inductor_Part_03_pool 🛑 >>>
UT_inductor_Part_04_pool 🛑 >>>
UT_DIST_ARM_Part_01 🛑 >>>
UT_DIST_ARM_Part_02 🛑 >>>
UT_DIST_ARM_Part_03 🛑 >>>
UT_DIST_ARM_Part_04 🛑 >>>
流水线 PR-pipeline_pytorch ✅ >>>
likedislike
ascend-robotascend-robot成员
5月14日 添加了label:ci-pipeline-passed
Ddinglaiping成员
5月15日 修改了pull request 的描述
Jingwei Huang
Jingwei Huang成员
5月18日 评论:

/lgtm

likedislike
liwei386成员
5月18日 评论:

/approve

likedislike
liwei386成员
5月18日 评论:

/approve

likedislike
ascend-robotascend-robot成员
5月18日 添加了label:approvedlgtm
ascend-robot
ascend-robot成员
5月18日 评论:

Review Guide

This pull-request passes review.
Committers who wrote a comment of /approve are: 李伟.
Reviewers who wrote a comment of /lgtm are: 李伟, huangjingwei.

likedislike
ascend-robotascend-robot成员
5月18日 合入了pull request