Files
TorchNPU/test/test_tensor_setstate_api_completion.py
ascend-robot e411d6bb7b test(tensor): add Tensor.__setstate__ NPU coverage
Co-authored-by: coconut<zhehanzhao7@gmail.com>



# message auto-generated for no-merge-commit merge:
!42442 merge api-completion-tensor-setstate-master into master

test(tensor): add Tensor.__setstate__ NPU coverage

Created-by: coconut77
Commit-by: coconut
Merged-by: ascend-robot
Description: 
# 【合入来源】

## 关联 issue

- 任务 Issue:https://gitcode.com/Ascend/pytorch/issues/2677
- 说明性 Issue:https://gitcode.com/Ascend/pytorch/issues/4679

# 【修改方案】

## 修改说明

本 PR 在 master 分支新增 `test/test_tensor_setstate_api_completion.py`,直接验证 `torch.Tensor.__setstate__` 的核心行为:

- 叶子 Tensor 调用 `__setstate__` 后可以恢复 `requires_grad` 状态;
- 非叶子 Tensor 调用 `__setstate__` 时抛出与原生 PyTorch 一致的异常;
- 测试通过 `torch.accelerator.current_accelerator()` 选择当前设备,NPU 环境实际使用 NPU。

修改文件:

~~~text
test/test_tensor_setstate_api_completion.py
~~~

## 涉及 API

`torch.Tensor.__setstate__`

## 社区用例覆盖情况

PyTorch 社区用例主要通过序列化、JIT 或 pickle 等间接路径触发 `__setstate__`,没有面向该接口的直接行为测试。因此本 PR 增加直接 API 调用覆盖,验证 Ascend NPU 上的行为与原生 PyTorch 保持一致。

## NPU 适配

测试不使用 `transfer_to_npu`,也不包含 `tensor.cuda()`、`torch.cuda.*` 或 `device="cuda"` 等 CUDA 迁移路径。

~~~python
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
~~~

无加速器环境回退到 CPU 仅用于保证测试文件可导入;NPU 环境通过 `accelerator=npu` 和 `NPU_AVAILABLE=True` 确认实际走 NPU 路径。

## 测试核心逻辑

~~~python
tensor = torch.ones(2, device=device_type)
self.assertFalse(tensor.requires_grad)

tensor.__setstate__((True, None, None))
self.assertTrue(tensor.requires_grad)

with self.assertRaisesRegex(
    RuntimeError, "__setstate__ can be only called on leaf Tensors"
):
    (tensor + 1).__setstate__((False, None, None))
~~~

# 【资料变更】

已通过独立 doc PR 在 `docs/zh/api/native_api/private_apis.md` 中补充 API 记录。

# 【接口变更】

不涉及 API 签名、实现或行为变更,本 PR 仅补充测试覆盖。

# 【功能验证】

## 910B3 测试结果

~~~text
COMMAND: /workspace/venvs/torch2100/bin/python /workspace/tensor_setstate_910B3_tests_20260908/test_tensor_setstate_api_completion_v271.py -v
PWD: /tmp
DATE: 2026-09-08 14:13:42 CST
test_tensor_setstate (__main__.TestTensorSetstateApiCompletion.test_tensor_setstate) ... ok

----------------------------------------------------------------------
Ran 1 test in 1.411s

OK
EXIT_CODE: 0
~~~

910B3 日志目录:

~~~text
/workspace/tensor_setstate_910B3_logs_20260908/master_910B3_complete_v2.log
~~~

## Ascend950PR 验证说明

Ascend950PR 已使用实际保存的 `test_tensor_setstate_api_completion.py` 文件完成 v2.7.1、v2.11.0 和 v2.12.0 验证。三个版本均确认 `ACCELERATOR: npu`、`NPU_AVAILABLE: True`、`OK` 和退出码 `0`。


# 【CheckList】

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

- [x] 代码注释完备,正确记录错误日志
- [x] 代码实现进行了返回值、空指针等校验
- [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等
- [x] PR持续集成流水线(CI)执行通过,代码检查无异常(PR 创建并通过 CI 后勾选)


See merge request: Ascend/pytorch!42442
2026-09-28 11:49:53 +08:00

45 lines
1.5 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.
"""
Validate torch.Tensor.__setstate__ API completion on NPU.
This file covers torch.Tensor.__setstate__ directly because the upstream
coverage is only indirect through serialization/JIT-style __setstate__ paths.
"""
import torch
from torch.testing._internal.common_utils import TestCase, run_tests
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
class TestTensorSetstateApiCompletion(TestCase):
def test_tensor_setstate(self):
tensor = torch.ones(2, device=device_type)
self.assertFalse(tensor.requires_grad)
tensor.__setstate__((True, None, None))
self.assertTrue(tensor.requires_grad)
with self.assertRaisesRegex(
RuntimeError, "__setstate__ can be only called on leaf Tensors"
):
(tensor + 1).__setstate__((False, None, None))
if __name__ == "__main__":
run_tests()