Files
TorchNPU/test/test_utils_checkpoint_api.py
baoxuebin_2026 1b30f7422c test: add utils api npu coverage
Co-authored-by: baoxuebin_2026<xuebin@isrc.iscas.ac.cn>



# message auto-generated for no-merge-commit merge:
!44624 merge codex/utils-api-consistency-master into master

test: add utils api npu coverage

Created-by: baoxuebin_2026
Commit-by: baoxuebin_2026
Merged-by: ascend-robot
Description: # 【合入来源】
[#150](https://gitcode.com/Ascend/pytorch-ecosystem/issues/150)
[#137](https://gitcode.com/Ascend/pytorch-ecosystem/issues/137)
[#100](https://gitcode.com/Ascend/pytorch-ecosystem/issues/100)

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

公开issue:
- `torch.utils.checkpoint.set_device_states`:
  https://gitcode.com/Ascend/pytorch-ecosystem/issues/150
- `torch.utils._foreach_utils._has_foreach_support`:
  https://gitcode.com/Ascend/pytorch-ecosystem/issues/137
- `torch.utils.module_tracker.ModuleTracker`:
  https://gitcode.com/Ascend/pytorch-ecosystem/issues/100

# 【修改方案】
1. API 功能说明:
   - `torch.utils.checkpoint.set_device_states`:为指定设备恢复随机数生成器状态,用于 checkpoint 重计算等场景保持随机数状态一致。
   - `torch.utils._foreach_utils._has_foreach_support`:判断给定设备和张量列表是否满足 foreach 快路径的使用条件。
   - `torch.utils.module_tracker.ModuleTracker`:上下文管理器,用于跟踪模块前向和反向执行期间的模块层级。

2. 上游用例检查情况:
   - `torch.utils.checkpoint.set_device_states` 涉及设备 RNG 状态。PyTorch 社区主要通过 checkpoint RNG 场景间接覆盖,未提供直接 NPU 用例,因此在 `test` 目录补充最小 NPU 验证。
   - `torch.utils._foreach_utils._has_foreach_support` 用于判断设备是否支持 foreach 快路径,直接涉及 NPU 后端能力。PyTorch 社区未提供面向 NPU 的直接验证,因此在 `test` 目录补充最小 NPU 验证。
   - `torch.utils.module_tracker.ModuleTracker` 为纯 Python 接口。PyTorch 社区已有独立、完整用例,覆盖模块层级、前向、反向和 checkpoint 场景,因此不新增 NPU 用例。

3. 新增用例文件:
   - `test/test_utils_checkpoint_api.py`
   - `test/test_utils_api.py`

4. 新增用例覆盖场景:
   - `set_device_states` 显式传入 `device_type="npu"`,恢复 NPU RNG 状态并验证随机序列一致。
   - `set_device_states` 省略可选参数 `device_type`,验证 Torch-NPU 默认设备类型路径。
   - `_has_foreach_support` 验证 NPU 张量及 `None` 组成的列表支持 foreach 快路径。
   - `_has_foreach_support` 验证混入非 Tensor 对象时返回不支持。

5. NPU 适配说明:
   - 新增张量均通过 `torch.accelerator.current_accelerator()` 获取当前 NPU 设备。
   - 未修改 `test_upstream/`,未新增 NPU 适配 patch。
   - 未修改 Torch-NPU API 实现。

6. 新增或修改的测试文件头部已包含 Huawei copyright 和 API 功能说明。

# 【资料变更】
不涉及。资料补齐已单独提交文档 PR。

# 【接口变更】
不涉及。未修改跨仓接口,也未修改用户可见接口行为。

# 【功能验证】
测试环境:
```text
NPU: Ascend 910B2C
torch: 2.13.0
torch_npu: 2.13.0
CANN: 8.5.1
```
测试命令:

source /usr/local/Ascend/cann-8.5.1/set_env.sh

TORCH_DEVICE_BACKEND_AUTOLOAD=1 \
/usr/local/python3.11.14/bin/python test/test_utils_checkpoint_api.py -v

TORCH_DEVICE_BACKEND_AUTOLOAD=1 \
/usr/local/python3.11.14/bin/python test/test_utils_api.py -v


板端核心验证结果:

PASS test_set_device_states_restores_npu_rng_sequence
PASS set_device_states default device_type
PASS test_has_foreach_support_for_npu_tensors
PASS ModuleTracker NPU forward and backward validation

See merge request: Ascend/pytorch!44624
2026-10-10 10:21:35 +08:00

147 lines
5.4 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.utils.checkpoint APIs on NPU:
1. PyTorch community tests cover these APIs mainly through checkpoint call chains, so this file adds direct API validations.
2. This file validates torch.utils.checkpoint.SelectiveCheckpointContext, detach_variable, and set_device_states (extendable).
"""
import functools
import inspect
import torch
from torch.testing._internal.common_utils import TestCase, run_tests
from torch.utils import checkpoint as checkpoint_utils
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
class TestUtilsCheckpointAPIs(TestCase):
def test_set_device_states_restores_npu_rng_sequence(self):
# Validate the default device selection independently from the explicit path.
torch.npu.manual_seed(20260814)
state = torch.npu.get_rng_state(0)
expected = torch.rand(8, device=device_type)
checkpoint_utils.set_device_states([0], [state])
actual = torch.rand(8, device=device_type)
self.assertEqual(actual, expected)
torch.npu.manual_seed(20260814)
state = torch.npu.get_rng_state(0)
expected = torch.rand(8, device=device_type)
checkpoint_utils.set_device_states([0], [state], device_type=device_type)
actual = torch.rand(8, device=device_type)
self.assertEqual(actual, expected)
def test_detach_variable_keeps_device_and_requires_grad(self):
x = torch.randn(2, 3, device=device_type, requires_grad=True)
y = (x * 2).relu()
marker = object()
detached_x, detached_y, detached_marker = checkpoint_utils.detach_variable(
(x, y, marker)
)
self.assertEqual(detached_x.device.type, device_type)
self.assertEqual(detached_y.device.type, device_type)
self.assertTrue(detached_x.requires_grad)
self.assertTrue(detached_y.requires_grad)
self.assertTrue(detached_x.is_leaf)
self.assertTrue(detached_y.is_leaf)
self.assertIsNone(detached_x.grad_fn)
self.assertIsNone(detached_y.grad_fn)
self.assertEqual(detached_x, x)
self.assertEqual(detached_y, y)
self.assertIs(detached_marker, marker)
def test_detach_variable_rejects_non_tuple_input(self):
x = torch.randn(2, device=device_type)
with self.assertRaisesRegex(RuntimeError, "Only tuple"):
checkpoint_utils.detach_variable([x])
def test_selective_checkpoint_context_direct_attributes(self):
ctx = checkpoint_utils.SelectiveCheckpointContext(is_recompute=False)
self.assertIsInstance(ctx, checkpoint_utils.SelectiveCheckpointContext)
self.assertFalse(ctx.is_recompute)
signature = inspect.signature(checkpoint_utils.SelectiveCheckpointContext)
if "op_output" in signature.parameters:
output = torch.ones(2, device=device_type)
ctx = checkpoint_utils.SelectiveCheckpointContext(
is_recompute=False,
op_output=output,
)
self.assertIs(ctx.op_output, output)
self.assertEqual(ctx.op_output.device.type, device_type)
def test_selective_checkpoint_context_passed_to_policy_fn(self):
contexts = []
def policy_fn(ctx, op, *args, **kwargs):
contexts.append(ctx)
return checkpoint_utils.CheckpointPolicy.PREFER_RECOMPUTE
def fn(x):
return x.sin().cos().sum()
x = torch.randn(4, device=device_type, requires_grad=True)
context_fn = functools.partial(
checkpoint_utils.create_selective_checkpoint_contexts,
policy_fn,
)
out = checkpoint_utils.checkpoint(
fn,
x,
use_reentrant=False,
context_fn=context_fn,
)
out.backward()
self.assertTrue(contexts)
self.assertTrue(
all(
isinstance(ctx, checkpoint_utils.SelectiveCheckpointContext)
for ctx in contexts
)
)
# Since PyTorch #176455, SAC uses indexed storage during the backward
# recompute pass and no longer invokes policy_fn there, so every context
# passed to policy_fn comes from the forward pass (is_recompute=False).
self.assertTrue(all(not ctx.is_recompute for ctx in contexts))
forward_contexts = [ctx for ctx in contexts if not ctx.is_recompute]
if forward_contexts and hasattr(forward_contexts[0], "op_output"):
tensor_outputs = [
ctx.op_output
for ctx in forward_contexts
if isinstance(ctx.op_output, torch.Tensor)
]
self.assertTrue(tensor_outputs)
self.assertTrue(
all(output.device.type == device_type for output in tensor_outputs)
)
if __name__ == "__main__":
run_tests()