Files
TorchNPU/test/test_tensor_module_load.py
T
lele130 b2933bc8bc [test][master] add NPU validation cases for torch.Tensor.map_ and torch.Tensor.module_load (issues #2720 #2722)
Co-authored-by: lele130<20230105101@stu.lzjtu.edu.cn>



# message auto-generated for no-merge-commit merge:
!41655 merge test-map-module-load-master into master

[test][master] add NPU validation cases for torch.Tensor.map_ and torch.Tensor.module_load (issues #2720 #2722)

Created-by: lele130
Commit-by: lele130
Merged-by: ascend-robot
Description: <!--
PR描述模板更新日期:20260203
-->

# 【合入来源】

> <font color="red">**如有社区 issue,请关联 issue 链接**</font>
> <font color="red">**请勿携带内部流程信息(需求链接、问题单、内部 issue 等)**</font>

- [ ] 需求
- [ ] 问题单
- [x] issue/工单
- [ ] 重构优化
- [ ] 资料更新

关联 issue:
- [#2720](https://gitcode.com/Ascend/pytorch/issues/2720) — `torch.Tensor.map_`(API 一致性验证)
- [#2722](https://gitcode.com/Ascend/pytorch/issues/2722) — `torch.Tensor.module_load`(API 一致性验证)

# 【修改方案】

本 PR 为 `torch.Tensor.map_` 和 `torch.Tensor.module_load` 两个 API 在 NPU 场景下补充一致性验证用例。PyTorch 社区缺少针对这两个 API 的直接、集中测试,按规范 1.3(自写用例)新增测试文件到 `test/` 目录。

修改文件:

- `test/test_tensor_map_.py`(新增):覆盖 `torch.Tensor.map_`(3 个用例)
- `test/test_tensor_module_load.py`(新增):覆盖 `torch.Tensor.module_load`(5 个用例)

合计 8 个用例。不涉及 `torch_npu` 任何 C++/Python 代码改动。

# 【API 功能介绍】

## 1. torch.Tensor.map_(tensor, callable) → Tensor

对 `self` 和给定 `tensor` 的每个元素应用 `callable`,结果存回 `self` tensor。两个 tensor 必须可广播。

- **callable 签名**:`def callable(a, b) -> number`
- **实现位置**:`torch/_tensor.py`,底层调用 `at::map` kernel
- **NPU 支持情况**:NPU 上不可用(`TypeError: map_ is only implemented on CPU tensors`),社区 CUDA 同样不支持
- **测试覆盖**:CPU 正常路径(2 用例)+ NPU 异常断言(1 用例)

## 2. torch.Tensor.module_load(other, assign=False) → Tensor

定义如何将 `other` 转换后加载到 `self` 中,用于 `load_state_dict()` 的 swap_tensors 路径。当 `get_swap_module_params_on_conversion()` 为 True 时使用。

- **实现**:`self.copy_(other).detach()`(assign=False)或 `other.detach()`(assign=True)
- **实现位置**:`torch/_tensor.py`
- **NPU 支持情况**:非计算类 API,基于 `copy_` 和 `detach` 实现,NPU 上直接可用,与数据类型无关
- **测试覆盖**:NPU tensor 上 5 个用例(返回值、dtype 保持、assign=True、destination 更新、detach 语义)

# 【上游社区用例情况】

## torch.Tensor.map_

PyTorch 社区 `test/test_torch.py::test_broadcast` 包含 `"map"`,但显式跳过 CUDA 设备。NPU 行为与 CUDA 一致。

## torch.Tensor.module_load

社区无直接测试用例,仅通过 `load_state_dict` 间接覆盖。

# 【测试环境】

- 操作系统:Linux 4.19.90-2102.2.0.0068.3.ctl2.aarch64
- 昇腾硬件:Ascend NPU(Ascend910B2)
- 安装版本:torch 2.12.0 + torch_npu 2.12.0
- 测试分支:master

# 【测试日志】

```text
$ python -u test/test_tensor_map_.py -v
test_map_applies_callable ... ok
test_map_raises_on_npu_tensor ... ok
test_map_uses_destination_values ... ok
----------------------------------------------------------------------
Ran 3 tests in 0.800s OK

$ python -u test/test_tensor_module_load.py -v
test_module_load_assign_true ... ok
test_module_load_keeps_dest_dtype ... ok
test_module_load_returns_detached_tensor ... ok
test_module_load_returns_source_values ... ok
test_module_load_updates_destination ... ok
----------------------------------------------------------------------
Ran 5 tests in 0.772s OK
```

# 【资料补齐检查结论】

- `torch.Tensor.map_`:`docs/zh/native_apis` 中已有该 API 记录。`map_` 在 NPU 上不可用,社区 CUDA 同样不支持,无需补充资料。
- `torch.Tensor.module_load`:`docs/zh/native_apis` 中已有该 API 记录。非计算类 API,与数据类型无关,无需补充资料。

Fixes #2720, Fixes #2722


See merge request: Ascend/pytorch!41655
2026-08-18 11:20:02 +08:00

67 lines
2.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 consistency validation cases for torch.Tensor.module_load.
This file adds self-contained, focused validation for torch.Tensor.module_load as requested by the
Ascend for PyTorch API consistency task (#2722). Where tensors are involved
they run on NPU via the accelerator device pattern. Extendable.
"""
import torch
from torch.testing._internal.common_utils import run_tests, TestCase
DEVICE = (acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu")
class TestTensorModuleLoad(TestCase):
def test_module_load_returns_source_values(self):
dest = torch.zeros(3).to(DEVICE)
src = torch.tensor([1.0, 2.0, 3.0]).to(DEVICE)
out = dest.module_load(src)
self.assertEqual(out.cpu(), src.cpu())
def test_module_load_keeps_dest_dtype(self):
dest = torch.zeros(2, dtype=torch.float32).to(DEVICE)
src = torch.tensor([1.0, 2.0], dtype=torch.float64).to(DEVICE)
out = dest.module_load(src)
self.assertEqual(out.dtype, dest.dtype)
def test_module_load_assign_true(self):
dest = torch.zeros(3).to(DEVICE)
src = torch.tensor([4.0, 5.0, 6.0]).to(DEVICE)
out = dest.module_load(src, assign=True)
# assign=True should return other.detach(), preserving src values
self.assertEqual(out.cpu(), src.cpu())
def test_module_load_updates_destination(self):
dest = torch.ones(3).to(DEVICE)
src = torch.tensor([7.0, 8.0, 9.0]).to(DEVICE)
out = dest.module_load(src, assign=False)
# assign=False does self.copy_(other).detach(), dest should be updated
self.assertEqual(dest.cpu(), src.cpu())
def test_module_load_returns_detached_tensor(self):
dest = torch.zeros(3, requires_grad=True).to(DEVICE)
src = torch.tensor([1.0, 2.0, 3.0]).to(DEVICE)
out = dest.module_load(src)
# module_load returns detach() result, so out should not require grad
self.assertFalse(out.requires_grad)
if __name__ == "__main__":
run_tests()