Closed
【API一致性任务】[Usage]: API一致性说明:torch.nn.Module.add_module/apply/bfloat16/buffers/children 五个API的用例与资料一致性对齐 #4608
GMOWAdd on  Sep 4Closed at  Nov 2
GMOW
GMOW
Sep 4 Create

在提交新问题之前,请确保您已经在社区中搜索过相关问题,并使用了社区中提供的资源/工具后,仍未找到满意的解决方式。

环境信息

- 操作系统:Linux
- 主验证环境:Atlas NPU 单卡(910B3,npu:0),torch 2.10.0 + torch_npu 2.10.0,CANN 9.0.0
- A5 系列补充验证:Ascend950PR(soc_version=260,与文档条目 950DT 同系列;TorchNPU 26.1.0 官方公告支持 950DT 款型),CANN 9.1.0
- A5 验证版本:torch 2.7.1/2.9.0/2.10.0/2.11.0/2.12.0/2.13.0 对应 torch_npu 各版本(六套环境,结论覆盖全部目标分支)

验证环境

使用场景及问题

对以下 5 个 torch.nn.Module 基础 API 开展 API 一致性对齐(用例补齐、资料检查、API 功能验证):

  1. torch.nn.Module.add_module
  2. torch.nn.Module.apply
  3. torch.nn.Module.bfloat16
  4. torch.nn.Module.buffers
  5. torch.nn.Module.children

社区用例检索方式:克隆 pytorch 官方仓库(gitee 镜像,注意不是 torch-npu 仓库)后,进入 test 目录使用短关键词检索(add_module / .apply( / bfloat16 / buffers( / children(),已覆盖 v2.7.1、v2.11.0、v2.12.0、v2.13.0 四个版本,用例分布一致,检索证据见“二、测试用例完备性”。

一、API功能
• torch.nn.Module.add_module:向当前模块注册子模块,可通过属性名访问。入参 name(str)、module(Optional[Module]),支持传入 None;name 非字符串或 module 非法类型时抛出 TypeError。纯 Python 接口(操作 _modules 有序字典),与硬件和数据类型无关。
• torch.nn.Module.apply:将 fn 递归地应用到自身及所有子模块(后序遍历:先递归 children,再 fn(self)),返回 self,典型用途为参数初始化、批量迁移设备。纯 Python 递归接口,与硬件无关。
• torch.nn.Module.bfloat16:将模块所有浮点类型的参数和缓冲区原地转换为 bfloat16 数据类型(非浮点张量保持不变),返回 self。底层通过 _apply 递归处理所有子模块,dtype 转换在张量所在设备上执行,属于涉及硬件的接口。
• torch.nn.Module.buffers:返回模块缓冲区的迭代器,入参 recurse(bool,默认 True)控制是否递归包含子模块缓冲区。纯 Python 接口(遍历 _buffers 字典),与硬件无关。
• torch.nn.Module.children:返回直接子模块的迭代器(不含递归,重复引用的同一子模块只返回一次)。纯 Python 接口,与硬件无关。

二、测试用例完备性

社区用例检索证据(pytorch 官方仓库 v2.7.1 test 目录实际 grep 输出):

社区用例检索证据-1

社区用例检索证据-2

测试用例所在目录:pytorch 官方仓库 test/test_nn.py(TestNN 类,大文件,以下标注用例行号范围)。逐 API 情况:

  1. torch.nn.Module.add_module:社区用例覆盖完整。test_add_module(v2.7.1 L1448-1469,覆盖 add_module/register_module 两种调用、注册 None 子模块、覆盖已有属性、TypeError 异常场景)、test_add_module_raises_error_if_attr_exists(L704-722);v2.11.0 L1480/L734、v2.12.0 L1482/L736、v2.13.0 L1483 同样存在。
  2. torch.nn.Module.apply:社区无直接用例。全 test 目录检索 .apply( 仅发现其他用例中的顺带使用(distributed/test_dynamo_distributed.py、nn/test_module_hooks.py、quantization 等);test_nn.py 的 test_module_apply_inplace_op(L1546-1570)验证的是私有方法 _apply,非本 API 直接用例。
  3. torch.nn.Module.bfloat16:社区无直接用例。test_nn.py 中 bfloat16 相关用例(如 L7374 参数化生成的 *_bfloat16 前向计算用例)均为验证算子在 bf16 dtype 下的前向行为,非 Module.bfloat16() 转换方法本身;全 test 目录亦无直接验证该方法的模块级用例。
  4. torch.nn.Module.buffers:社区用例覆盖完整。test_buffers_and_named_buffers(v2.7.1 L336-374,覆盖 recurse=True/False、remove_duplicate 去重、Sequential 嵌套);v2.11.0 L347、v2.12.0 L349、v2.13.0 L350 同样存在。
  5. torch.nn.Module.children:社区用例覆盖完整。test_children(v2.7.1 L407-415,验证 Sequential 下去重与顺序)、test_named_children(L471-488);v2.11.0 L418/L482、v2.12.0 L420/L484、v2.13.0 L421 同样存在。

三、API适配

3.1 API适配
五个 API 均无需修改源码:torch.nn.Module.add_module / apply / buffers / children 为纯 Python 接口,不涉及硬件;torch.nn.Module.bfloat16 的设备侧 dtype 转换在 NPU 上验证通过,且与 CPU 侧转换结果逐位一致(torch.equal 为 True)。

3.2 测试用例适配
• torch.nn.Module.add_module / children:torch-npu v2.7.1/v2.9.0/v2.10.0/v2.11.0/v2.12.0 的 test_upstream/test/test_nn.py.patch 已对相关用例做了 NPU 适配(如 nn.Linear(10, 20).npu()),分析合理,无需新增 patch;
• torch.nn.Module.buffers:纯逻辑用例未被 patch 修改,可直接在 NPU 环境运行;
• torch.nn.Module.bfloat16 / apply:社区无直接用例,新增测试文件 test/nn/test_module_bfloat16_apply.py(共 10 个用例:bfloat16 覆盖浮点参数/缓冲区转换(fp32/fp64)、非浮点张量保持、返回 self 且设备不变、无浮点张量模块边界、NPU 与 CPU 侧结果一致性对比;apply 覆盖 fn 全子模块调用、后序遍历顺序、返回 self、apply 迁移模块到 NPU、fn 不可调用异常),按最新任务口径提交到 2.7.1/2.11.0/2.12.0/master 四个分支(2.9.0/2.10.0 转入维护阶段暂不作要求,2.6.0/2.8.0 不再要求;后续如发布 2.13.0 版本分支将按口径补充提交)。

四、验证结果

  1. 新增用例运行(test/nn/test_module_bfloat16_apply.py,10 个用例):

新增用例运行结果

  1. 社区用例运行(原始未适配版本,5 个用例):

社区用例运行结果

  1. 社区用例运行(应用 torch-npu NPU 适配 patch 后,即 test_upstream 形态,3 个用例):

适配 patch 后运行结果

  1. A5 功能一致性直接验证(五个 API 逐一核查,含 NPU 与 CPU 侧 bfloat16 转换精度对比):

A5 功能核查

五、验证日志说明

  1. 验证环境见“环境信息”(Atlas NPU 单卡,torch 2.10.0 + torch_npu 2.10.0,CANN 9.0.0),API 语义跨版本一致;
  2. 运行命令:python test_nn.py TestNN.test_add_module TestNN.test_add_module_raises_error_if_attr_exists TestNN.test_buffers_and_named_buffers TestNN.test_children TestNN.test_named_children -v(社区用例);git apply test_nn.py.patch 后重跑 add_module/children 相关用例(适配后);python test_module_bfloat16_apply.py -v(新增用例);
  3. 社区用例取自与验证环境 torch 版本匹配的 pytorch v2.10.0 源码,用例内容与 v2.7.1 行号标注一致(仅行号差异);
  4. 完整未裁剪运行日志(含 transfer_to_npu 导入提示)可按需提供。

六、A5 系列(Ascend950PR)补充验证
为确认 Ascend 950DT 款型支持状态(对应文档 PR 中 950DT 条目修正),在 950PR 实机完成补充验证,六套环境全部通过:

新增用例(test/nn/test_module_bfloat16_apply.py,10 用例,torch.nn.Module.bfloat16 ×5 + torch.nn.Module.apply ×5)A5 实机运行日志原文(master/2.13.0 环境,六套环境用例集完全一致,其余版本仅耗时不同):

# A5 verification (master) | 2026-09-04 12:05:34
# SoC: Ascend950PR (soc_version=260, Ascend950 family) | CANN 9.1.0 | npu-smi 25.7.rc1.b085
# torch 2.13.0+cpu | torch_npu 2.13.0rc1 (master 适配, 对应 PR 45798)
+-------------------------------------------------------------------------------------------------+
| npu-smi 25.7.rc1.b085                            Version: 25.7.rc1.b085                         |
+--------+------------------+---------------+-----------------------------------------------------+
| NPU ID | Name             | Health        | Power(W)    Temp(C)           Hugepages-Usage(page) |
|        |                  | Bus-Id        | AICore(%)   Memory-Usage(MB)  HBM-Usage(MB)         |
+========+==================+===============+=====================================================+
| 0      | Ascend950PR      | Alarm         | 200.5       56                0     / 0             |
|        |                  | 0000:91:00.0  | 0           0    / 0          5238  / 131072        |
test_apply_calls_fn_on_self_and_all_submodules (__main__.TestModuleApply.test_apply_calls_fn_on_self_and_all_submodules)
Verify apply calls fn on self and every submodule exactly once. ... ok
test_apply_moves_module_to_device (__main__.TestModuleApply.test_apply_moves_module_to_device)
Verify apply can be used to move all submodules to the device. ... ok
test_apply_raises_type_error_for_non_callable_fn (__main__.TestModuleApply.test_apply_raises_type_error_for_non_callable_fn)
Verify apply raises TypeError when fn is not callable. ... ok
test_apply_returns_self (__main__.TestModuleApply.test_apply_returns_self)
Verify apply returns self. ... ok
test_apply_visits_submodules_before_parent (__main__.TestModuleApply.test_apply_visits_submodules_before_parent)
Verify apply visits submodules recursively before their parent. ... ok
test_bfloat16_casts_all_floating_point_params_and_buffers (__main__.TestModuleBFloat16.test_bfloat16_casts_all_floating_point_params_and_buffers)
Verify bfloat16 casts all floating point params and buffers, including nested ones. ... ok
test_bfloat16_keeps_non_floating_point_tensors (__main__.TestModuleBFloat16.test_bfloat16_keeps_non_floating_point_tensors)
Verify bfloat16 keeps non floating point tensors unchanged. ... ok
test_bfloat16_matches_cpu_result (__main__.TestModuleBFloat16.test_bfloat16_matches_cpu_result)
Verify bfloat16 cast result on NPU matches the CPU side. ... ok
test_bfloat16_module_without_floating_point_tensors (__main__.TestModuleBFloat16.test_bfloat16_module_without_floating_point_tensors)
Verify bfloat16 works on a module without floating point tensors. ... ok
test_bfloat16_returns_self_and_keeps_device (__main__.TestModuleBFloat16.test_bfloat16_returns_self_and_keeps_device)
Verify bfloat16 modifies the module in place, returns self and keeps device. ... ok

----------------------------------------------------------------------
Ran 10 tests in 2.045s

OK

各版本结果汇总:

2.7.1  : Ran 10 tests in 1.837s  OK
2.9.0  : Ran 10 tests in 1.874s  OK
2.10.0 : Ran 10 tests in 1.865s  OK
2.11.0 : Ran 10 tests in 1.846s  OK
2.12.0 : Ran 10 tests in 1.869s  OK
2.13.0 : Ran 10 tests in 2.045s  OK   (master, 对应 PR 45798)

社区原始用例(torch.nn.Module.add_module / buffers / children 等社区已有用例,pytorch v2.13.0 test/test_nn.py,NPU 适配方式同 torch-npu)A5 实机运行日志原文(其余版本用例集一致;2.7.1 无 test_register_buffer_allows_tensor_like_object 用例):

# A5 community-cases verification (master) | 2026-09-04 12:06:06
# SoC: Ascend950PR | CANN 9.1.0 | torch 2.13.0+cpu | torch_npu 2.13.0rc1 (master)
# 社区用例来源: pytorch v2.13.0 test/test_nn.py (torch-npu master 适配版本), NPU 适配方式同 torch-npu adapt_testcases_to_npu.py
+-------------------------------------------------------------------------------------------------+
| npu-smi 25.7.rc1.b085                            Version: 25.7.rc1.b085                         |
+--------+------------------+---------------+-----------------------------------------------------+
| NPU ID | Name             | Health        | Power(W)    Temp(C)           Hugepages-Usage(page) |
|        |                  | Bus-Id        | AICore(%)   Memory-Usage(MB)  HBM-Usage(MB)         |
+========+==================+===============+=====================================================+
| 0      | Ascend950PR      | Alarm         | 200.4       56                0     / 0             |
|        |                  | 0000:91:00.0  | 0           0    / 0          5237  / 131072        |
test_add_module (__main__.TestNN.test_add_module) ... ok
test_add_module_raises_error_if_attr_exists (__main__.TestNN.test_add_module_raises_error_if_attr_exists) ... ok
test_buffers_and_named_buffers (__main__.TestNN.test_buffers_and_named_buffers) ... ok
test_children (__main__.TestNN.test_children) ... ok
test_named_children (__main__.TestNN.test_named_children) ... ok
test_register_buffer_allows_overwriting_with_same_name (__main__.TestNN.test_register_buffer_allows_overwriting_with_same_name) ... ok
test_register_buffer_allows_tensor_like_object (__main__.TestNN.test_register_buffer_allows_tensor_like_object) ... ok
test_register_buffer_raises_error_if_attr_exists (__main__.TestNN.test_register_buffer_raises_error_if_attr_exists) ... ok
test_register_buffer_raises_error_if_name_is_not_string (__main__.TestNN.test_register_buffer_raises_error_if_name_is_not_string) ... ok
test_register_buffer_raises_error_if_not_tensor (__main__.TestNN.test_register_buffer_raises_error_if_not_tensor) ... ok

----------------------------------------------------------------------
Ran 10 tests in 0.008s

OK
torch: 2.13.0+cpu | torch_npu: 2.13.0.rc1
accelerator: npu | soc: 260 (260 = Ascend950; npu-smi: Ascend950PR)
children: ['Linear']
named_children: ['linear']
buffers dtypes: ['torch.float32', 'torch.int64']
named_buffers: ['running_mean', 'step']
buffer device: npu:0
overwrite same name -> buffer count: 2
after module.to(npu) buffer devices: npu:0 npu:0
recursive named_buffers: ['running_mean', 'step', 'sub.scale']
recursive buffers on npu: True

各版本结果汇总:

2.7.1  : Ran 9 tests in 0.007s   OK   (该版本无 test_register_buffer_allows_tensor_like_object 用例)
2.9.0  : Ran 10 tests in 0.008s  OK
2.10.0 : Ran 10 tests in 0.007s  OK
2.11.0 : Ran 10 tests in 0.008s  OK
2.12.0 : Ran 10 tests in 0.008s  OK
2.13.0 : Ran 10 tests in 0.008s  OK

API 直接探测(六套环境结果一致):

soc: 260 (260 = Ascend950; npu-smi: Ascend950PR)
children: ['Linear']
apply visited: Linear
apply visited: Module
param device: npu:0
bfloat16 probe: dtype = torch.bfloat16 , device = npu:0

结论:五个 API 在 A5 系列上全部正常,与 910B3 上结论一致。

七、资料支持情况
docs/zh/api/native_api 各版本目录(2-7-1/2-11-0/2-12-0/2-13-0)torch-nn.md 中 5 个 API 均已有条目且标注支持:
• torch.nn.Module.bfloat16、torch.nn.Module.buffers:条目无错误限制说明;据 A5 实机验证(950PR 上 bfloat16 5 个用例全部通过,含与 CPU 侧结果一致性对比),已在文档 PR 中将 bfloat16 的 950DT 状态由“不支持”同步修正为“支持”;buffers 原本即为“支持”;
• torch.nn.Module.add_module / apply / children:原条目带有错误的“self仅支持fp32”限制说明(非计算类 API 与数据类型无关,按规范应删去),已单独提交文档 PR 修正(4 个版本目录共 12 处)。
注:课程材料所指 v2.7.1/docs/zh/native_apis 旧路径已迁移至 master 分支 docs/zh/api/native_api(现存唯一资料目录),文档 PR 合入 master 并刷新全部版本目录。

用例 PR(按最新任务口径提交到 2.7.1、2.11.0、2.12.0、master):

文档 PR(master,docs/zh/api/native_api):
https://gitcode.com/Ascend/pytorch/merge_requests/45799

补充 PR(额外覆盖,CI 已通过):

关闭的 PR:2.6.0(MR 45791)、2.8.0(MR 45793)按最新口径不再要求提交,已关闭。其中 UT_ARM_A2 阶段失败为分支 CI 脚本与门禁模板不兼容所致(ci/access_control_test.py 不支持门禁传入的 --npu_core 参数,所有用例未执行),与用例改动无关,已在对应 PR 评论中说明。

likedislike
TorchNPU-BotTorchNPU-BotCollaborators
Sep 4 Added label: help-wantedevent: api-consistencybot-triaged
TorchNPU-Bot
TorchNPU-BotCollaborators
Sep 4 Comments:

检测到社区任务相关 issue,自动添加标签:event: api-consistency、help-wanted

likedislike
GMOWGMOW
Sep 4 Associated pull request
19 event messages are collapsed here。 See more
ascend-robotascend-robotCollaborators
Nov 2 Added label: resolved