Co-authored-by: yangke<1723981822@qq.com> # message auto-generated for no-merge-commit merge: !45798 merge test-module-bfloat16-apply into master test(nn): add test for torch.nn.Module.bfloat16 and torch.nn.Module.apply Created-by: gcw_8p1hhlB0 Commit-by: yangke Merged-by: ascend-robot Description: # 【合入来源】 > <font color="red">**https://gitcode.com/Ascend/pytorch/issues/4608**</font>\ > <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部issue等)**</font> - [ ] issue/工单 pytorch 社区用例没有直接验证 torch.nn.Module.bfloat16 和 torch.nn.Module.apply 的用例,故新增该测试用例文件,用于验证这两个 API 在 NPU 上的正确性。 # 【修改方案】 一、API功能说明 ``` 1. torch.nn.Module.bfloat16 将模块所有浮点类型的参数和缓冲区原地(in-place)转换为 bfloat16 数据类型, 非浮点张量保持不变,返回 self。底层通过 _apply 递归处理所有子模块, dtype 转换在张量所在设备上执行,属于涉及硬件的接口。 2. torch.nn.Module.apply 将 fn 递归地应用到自身及所有子模块(后序遍历:先递归 children 再 fn(self)), 返回 self。纯 Python 递归接口,典型用途为参数初始化、批量迁移设备。 ``` 二、测试文件 test_module_bfloat16_apply.py 完整验证该 API 的原因 ``` 社区用例检索情况(在 pytorch 官方仓库 test 目录按短关键词检索,覆盖 v2.7.1/v2.11.0/v2.12.0/v2.13.0,用例分布一致): 1. torch.nn.Module.bfloat16:test_nn.py 中 bfloat16 相关用例(如参数化生成的 *_bfloat16 前向计算用例)均验证算子在 bf16 dtype 下的前向行为,全 test 目录无直接验证 Module.bfloat16() 转换方法的用例,社区用例确实缺失,需要新增。 2. torch.nn.Module.apply:仅在其他用例中顺带使用(test_dynamo_distributed.py、 test_module_hooks.py、quantization 等),test_nn.py 的 test_module_apply_inplace_op 验证的是私有方法 _apply,社区无直接用例。 用例覆盖说明(按 API 功能一致标准覆盖全场景): 1. torch.nn.Module.bfloat16(该 API 无入参,按张量类型等价类划分): test_bfloat16_casts_all_floating_point_params_and_buffers:fp32/fp64 参数与 fp32 缓冲区(含嵌套子模块)全部转为 bfloat16; test_bfloat16_keeps_non_floating_point_tensors:int64 缓冲区保持不变; test_bfloat16_returns_self_and_keeps_device:返回 self、设备不变; test_bfloat16_module_without_floating_point_tensors:无浮点张量模块边界场景; test_bfloat16_matches_cpu_result:NPU 侧与 CPU 侧转换结果一致性对比。 2. torch.nn.Module.apply(fn 为唯一入参): test_apply_calls_fn_on_self_and_all_submodules:fn 对自身及全部子模块各调用一次; test_apply_visits_submodules_before_parent:后序遍历顺序验证; test_apply_returns_self:返回 self; test_apply_moves_module_to_device:apply 批量迁移模块到设备的典型用法(张量运行在 NPU); test_apply_raises_type_error_for_non_callable_fn:fn 不可调用的异常传参场景。 ``` 社区用例检索证据(pytorch 官方仓库 v2.7.1 test 目录实际 grep 输出):   三、NPU适配 ``` 本用例按规范在导入头文件后获取设备: device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu" 张量全部运行在 NPU 上(CPU 环境自动回退),无需对 API 本身做任何修改。 ``` # 【资料变更】 不涉及 torch.nn.Module.bfloat16、torch.nn.Module.buffers 在 docs/zh/api/native_api 各版本目录中已有条目且无错误; torch.nn.Module.add_module / torch.nn.Module.apply / torch.nn.Module.children 的错误“self仅支持fp32”限制说明已单独提交 PR 修正:[文档 PR 链接] # 【接口变更】 不涉及 # 【功能验证】 验证结论:在 NPU 环境下(Atlas NPU 单卡,torch 2.10.0 + torch_npu 2.10.0,CANN 9.0.0),新增测试文件 10 个用例全部通过(TestModuleBFloat16 5 例 + TestModuleApply 5 例);torch.nn.Module.bfloat16 的 NPU 侧与 CPU 侧转换结果逐位一致(torch.equal 为 True);torch.nn.Module.apply 后序递归、设备迁移行为符合预期。验证结果表明两个 API 在 NPU 环境下功能正常,无需修改源码即可稳定适配 NPU 设备。 用例运行结果:   # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!45798
146 lines
5.6 KiB
Python
146 lines
5.6 KiB
Python
# Copyright (c) 2026 Huawei Technologies Co., Ltd
|
|
# All rights reserved.
|
|
#
|
|
# Licensed under the BSD 3-Clause License (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# https://opensource.org/licenses/BSD-3-Clause
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
"""
|
|
Add validation cases for torch.nn APIs on NPU:
|
|
1. PyTorch community lacks direct test cases for torch.nn.Module.bfloat16 and
|
|
torch.nn.Module.apply, so this file is added.
|
|
2. This file validates torch.nn.Module.bfloat16, torch.nn.Module.apply (extendable).
|
|
"""
|
|
|
|
import torch
|
|
import torch.nn as nn
|
|
from torch.testing._internal.common_utils import TestCase, run_tests
|
|
|
|
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
|
|
|
|
|
|
class TestModuleBFloat16(TestCase):
|
|
"""Test torch.nn.Module.bfloat16 method."""
|
|
|
|
def _make_module(self):
|
|
module = nn.Linear(4, 4)
|
|
module.register_parameter(
|
|
"param_fp64", nn.Parameter(torch.randn(3, 3, dtype=torch.float64)))
|
|
module.register_buffer("buffer_fp32", torch.randn(4))
|
|
module.register_buffer("buffer_int64", torch.arange(4, dtype=torch.int64))
|
|
return module
|
|
|
|
def test_bfloat16_casts_all_floating_point_params_and_buffers(self):
|
|
"""Verify bfloat16 casts all floating point params and buffers, including nested ones."""
|
|
module = nn.Sequential(self._make_module(), self._make_module()).to(device_type)
|
|
module.bfloat16()
|
|
|
|
for submodule in module:
|
|
self.assertEqual(submodule.weight.dtype, torch.bfloat16)
|
|
self.assertEqual(submodule.bias.dtype, torch.bfloat16)
|
|
self.assertEqual(submodule.param_fp64.dtype, torch.bfloat16)
|
|
self.assertEqual(submodule.buffer_fp32.dtype, torch.bfloat16)
|
|
|
|
def test_bfloat16_keeps_non_floating_point_tensors(self):
|
|
"""Verify bfloat16 keeps non floating point tensors unchanged."""
|
|
module = self._make_module().to(device_type)
|
|
module.bfloat16()
|
|
|
|
self.assertEqual(module.buffer_int64.dtype, torch.int64)
|
|
self.assertEqual(module.buffer_int64.tolist(), [0, 1, 2, 3])
|
|
|
|
def test_bfloat16_returns_self_and_keeps_device(self):
|
|
"""Verify bfloat16 modifies the module in place, returns self and keeps device."""
|
|
module = self._make_module().to(device_type)
|
|
result = module.bfloat16()
|
|
|
|
self.assertIs(result, module)
|
|
for tensor in list(module.parameters()) + list(module.buffers()):
|
|
self.assertEqual(tensor.device.type, device_type)
|
|
|
|
def test_bfloat16_module_without_floating_point_tensors(self):
|
|
"""Verify bfloat16 works on a module without floating point tensors."""
|
|
module = nn.Module()
|
|
module.register_buffer("step", torch.tensor(3, dtype=torch.int64))
|
|
module.to(device_type)
|
|
result = module.bfloat16()
|
|
|
|
self.assertIs(result, module)
|
|
self.assertEqual(module.step.dtype, torch.int64)
|
|
|
|
def test_bfloat16_matches_cpu_result(self):
|
|
"""Verify bfloat16 cast result on NPU matches the CPU side."""
|
|
torch.manual_seed(1234)
|
|
module_cpu = self._make_module()
|
|
|
|
torch.manual_seed(1234)
|
|
module_npu = self._make_module().to(device_type)
|
|
|
|
module_cpu.bfloat16()
|
|
module_npu.bfloat16()
|
|
|
|
self.assertEqual(module_cpu.weight, module_npu.weight.to("cpu"))
|
|
self.assertEqual(module_cpu.param_fp64, module_npu.param_fp64.to("cpu"))
|
|
self.assertEqual(module_cpu.buffer_fp32, module_npu.buffer_fp32.to("cpu"))
|
|
|
|
|
|
class TestModuleApply(TestCase):
|
|
"""Test torch.nn.Module.apply method."""
|
|
|
|
def _make_tree(self):
|
|
root = nn.Module()
|
|
root.linear = nn.Linear(4, 4)
|
|
root.seq = nn.Sequential(nn.Linear(4, 4), nn.ReLU())
|
|
return root
|
|
|
|
def test_apply_calls_fn_on_self_and_all_submodules(self):
|
|
"""Verify apply calls fn on self and every submodule exactly once."""
|
|
root = self._make_tree().to(device_type)
|
|
visited = []
|
|
root.apply(visited.append)
|
|
|
|
expected = {root, root.linear, root.seq, root.seq[0], root.seq[1]}
|
|
self.assertEqual(set(visited), expected)
|
|
self.assertEqual(len(visited), len(expected))
|
|
|
|
def test_apply_visits_submodules_before_parent(self):
|
|
"""Verify apply visits submodules recursively before their parent."""
|
|
root = self._make_tree().to(device_type)
|
|
order = []
|
|
root.apply(lambda module: order.append(type(module).__name__))
|
|
|
|
self.assertEqual(order, ["Linear", "Linear", "ReLU", "Sequential", "Module"])
|
|
|
|
def test_apply_returns_self(self):
|
|
"""Verify apply returns self."""
|
|
root = self._make_tree().to(device_type)
|
|
|
|
self.assertIs(root.apply(lambda module: None), root)
|
|
|
|
def test_apply_moves_module_to_device(self):
|
|
"""Verify apply can be used to move all submodules to the device."""
|
|
root = self._make_tree()
|
|
root.apply(lambda module: module.to(device_type))
|
|
|
|
for param in root.parameters():
|
|
self.assertEqual(param.device.type, device_type)
|
|
|
|
def test_apply_raises_type_error_for_non_callable_fn(self):
|
|
"""Verify apply raises TypeError when fn is not callable."""
|
|
root = self._make_tree().to(device_type)
|
|
|
|
with self.assertRaises(TypeError):
|
|
root.apply(None)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|