Files
TorchNPU/test/test_utils_checkpoint_api.py
T
c_34 301a551e0b compat(v2.13): reintroduce csrc compat module for upstream 2.13
Co-authored-by: chz34<chenhaozhe1@huawei.com>



# message auto-generated for no-merge-commit merge:
!39206 merge compat/2.13_ori into master

compat(v2.13): reintroduce csrc compat module for upstream 2.13

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

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

pytorch 上游重构修改,将`shared_ptr<Node>` 重构为 `intrusive_ptr<Node>`,主线适配上游main分支编译报错

https://github.com/pytorch/pytorch/pull/181782

- [ ] 需求
- [ ] 问题单
- [x] issue/工单  https://gitcode.com/Ascend/pytorch/issues/1812 https://gitcode.com/Ascend/pytorch/issues/2497 https://gitcode.com/Ascend/pytorch/issues/2508
- [x] 重构优化  https://gitcode.com/Ascend/pytorch/issues/1688
- [ ] 资料更新


# 【修改方案】
> 请描述修改内容的具体实现,涉及哪些组件之间进行交互,可以用1、2、3、...进行罗列\
> 如果是需求或者重构类的PR,需要补充详细设计文档(说明上下游组件关系、时序图、类图、DFX能力等内容)

    compat(v2.13): reintroduce csrc compat module for upstream 2.13
    
    C++ side (torch_npu/csrc/_compat/):
    - version.h: TORCH_NPU_VERSION_GE(MAJOR, MINOR) macro plus TORCH_NPU_MIN_SUPPORTED
      constants kept in sync with the Python side.
    - autograd.h: torch_npu::compat::GradFnPtr<T> alias and make_grad_fn<Op>(args...)
      wrap the Node smart pointer migration from std::shared_ptr+deleteNode (<=2.12)
      to c10::intrusive_ptr+make_intrusive (>=2.13, pytorch#181782). SavedForPtr
      covers SavedVariable::unpack's parameter type change.
    
    Hand-written C++ updated to use the alias:
    - VariableFallbackKernel.cpp, VariableTypeManual.cpp (grad_fn locals)
    - reducer.hpp (grad_accumulators_ and hooks_ element types)
    - torchnpugen/autograd/templates/Functions.h (unpack_list/unpack_opt_list
      saved_for parameter)
    
    Python side (torch_npu/_compat/utils.py):
    - make_config_entry(config, *, name) wraps _ConfigEntry which gained a required
      `name` parameter in PyTorch 2.12. _dynamo.patch_inductor_wrapper uses the
      helper instead of branching inline.
    
    torchgen's packaged emit_body and gen_autograd_functions were updated upstream
    alongside pytorch#181782, so no codegen post-processing is needed -- only the
    hand-written sources need the compat aliases.

# 【资料变更】
> 请确认是否涉及资料变更。如涉及,需要在PR中体现,并简要说明修改内容。如不涉及,需填写“不涉及”

不涉及

# 【接口变更】
> 请确认是否涉及跨代码仓或者客户面可见的接口变更。如涉及,需要详细说明接口以及对应的变更内容,同时需要在资料中体现。如不涉及,需填写“不涉及”

不涉及

# 【功能验证】
> 说明测试场景,测试方法。如果本次测试方式与常规单元测试不同,请详细说明您的测试步骤\
> 新增/变更内容是否已新增/适配UT测试用例看护,并补充测试自验证截图

基于现有用例

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

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


See merge request: Ascend/pytorch!39206
2026-06-26 14:55:06 +08:00

113 lines
4.1 KiB
Python

"""
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 and torch.utils.checkpoint.detach_variable (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_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()