Files
TorchNPU/test/test_tensor_map_.py
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

58 lines
2.3 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.map_.
This file adds self-contained, focused validation for torch.Tensor.map_ as requested by the
Ascend for PyTorch API consistency task (#2720). Extendable.
PyTorch community test: test/test_torch.py::test_broadcast includes "map" in its
parametrized fn list, but the test is explicitly skipped on CUDA devices
("map and map2 are not implemented on CUDA tensors"). NPU follows the same
behavior -- map_ is CPU-only, so functional validation is done on CPU tensors.
NPU tensors are verified to raise the expected error.
"""
import torch
from torch.testing._internal.common_utils import run_tests, TestCase
class TestTensorMap(TestCase):
def test_map_applies_callable(self):
# map_ is CPU-only in PyTorch community (same as CUDA)
dst = torch.zeros(3)
src = torch.tensor([1.0, 2.0, 3.0])
dst.map_(src, lambda d, s: s * 2)
self.assertEqual(dst, torch.tensor([2.0, 4.0, 6.0]))
def test_map_uses_destination_values(self):
# map_ is CPU-only in PyTorch community (same as CUDA)
dst = torch.tensor([10.0, 20.0])
src = torch.tensor([1.0, 2.0])
dst.map_(src, lambda d, s: d + s)
self.assertEqual(dst, torch.tensor([11.0, 22.0]))
def test_map_raises_on_npu_tensor(self):
# Verify that map_ raises TypeError with the expected message on NPU tensors
dst = torch.zeros(3).npu()
src = torch.tensor([1.0, 2.0, 3.0]).npu()
with self.assertRaises(TypeError) as ctx:
dst.map_(src, lambda d, s: s * 2)
self.assertIn("map_ is only implemented on CPU", str(ctx.exception))
if __name__ == "__main__":
run_tests()