Files
TorchNPU/test/utils/test_CheckpointFunction_BuildExtension_hipify_python__contextlib.py
lyd123333 159c687c68 [test] add CheckpointFunction.backward cpp_extension.BuildExtension.with_options hipify_python.hipify _contextlib._DecoratorContextManager API test case
Co-authored-by: lyd123333<3906916351@qq.com>



# message auto-generated for no-merge-commit merge:
!45275 merge CheckpointFunction-BuildExtension-hipify_python-_contextlib-master into master

[test] add CheckpointFunction.backward cpp_extension.BuildExtension.with_options hipify_python.hipify _contextlib._DecoratorContextManager API test case

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

# 【合入来源】

[#147](https://gitcode.com/Ascend/pytorch-ecosystem/issues/147)
[#122](https://gitcode.com/Ascend/pytorch-ecosystem/issues/122)
[#74](https://gitcode.com/Ascend/pytorch-ecosystem/issues/74)
[#134](https://gitcode.com/Ascend/pytorch-ecosystem/issues/134)

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

公开issue:

- `torch.utils.checkpoint.CheckpointFunction.backward`:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(26)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/147)
- `torch.utils.cpp_extension.BuildExtension.with_options`:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(33)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/122)
- `torch.utils.hipify.hipify_python.hipify`:[8月社区任务第二期-Ascend for PyTorch API 一致性开发(51)](https://gitcode.com/Ascend/pytorch-ecosystem/issues/74)
- `torch.utils._contextlib._DecoratorContextManager`: [8月社区任务第二期-Ascend for PyTorch API 一致性开发(13) ](https://gitcode.com/Ascend/pytorch-ecosystem/issues/134)

# torch.utils 相关四个 API 分析

## 1. API 功能说明

| API | 功能说明 | 是否硬件相关 |
|---|---|---|
| `torch.utils.checkpoint.CheckpointFunction.backward` | `CheckpointFunction` 是 activation checkpoint 的底层 autograd Function。其 `backward` 方法在反向传播阶段重新执行前向计算,从而避免在 forward 阶段保存全部中间激活,达到以计算换显存的目的。 | 不是专门硬件接口,但会依赖具体设备上的 autograd、算子执行和 RNG 状态管理。 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | `BuildExtension` 是 PyTorch 提供的自定义 C++/CUDA/SYCL 扩展构建类;`with_options(**options)` 用于生成一个带默认构建参数的 `BuildExtension` 子类/构造器,常用于 `setup.py` 的 `cmdclass={"build_ext": BuildExtension.with_options(...)}`。 | 属于构建工具接口,涉及 CUDA/SYCL 编译参数,但本身不是运行时硬件 API。 |
| `torch.utils.hipify.hipify_python.hipify` | PyTorch 内置 HIPIFY 工具入口,用于扫描指定项目目录,将 CUDA/C++ 源文件中的 CUDA API、头文件、kernel launch 等模式转换为 HIP/ROCm 对应形式。 | 是 GPU 迁移工具,面向 AMD ROCm/HIP;不是 Ascend NPU 运行时接口。 |
| `torch.utils._contextlib._DecoratorContextManager` | PyTorch 内部上下文管理器基类,用于让 context manager 同时具备 decorator 用法,例如 `torch.no_grad()`、`torch.inference_mode()` 这类接口。 | 纯 Python 上下文控制工具,不涉及硬件。 |

## 3. torch-npu 平台测试必要性

| API | 是否建议补充 NPU 测试 | 原因 |
|---|---|---|
| `torch.utils.checkpoint.CheckpointFunction.backward` | 建议 | checkpoint backward 会触发反向传播阶段的重计算,涉及 NPU Tensor 的 autograd、算子执行、梯度回传以及 RNG 状态保存/恢复,适合作为 torch-npu 兼容性测试。 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 不建议作为 NPU 专项测试 | 该接口只负责构建参数注入,不直接执行 NPU 算子。可做纯 Python import/行为测试,但不需要 NPU 设备测试。 |
| `torch.utils.hipify.hipify_python.hipify` | 不建议作为 NPU 专项测试 | 该接口面向 CUDA 到 HIP/ROCm 的源码迁移,与 Ascend NPU 后端无直接关系。 |
| `torch.utils._contextlib._DecoratorContextManager` | 不建议作为 NPU 专项测试 | 该接口是内部 Python 上下文管理工具,设备无关。若需要覆盖,可通过公开 API `torch.no_grad()` 在 NPU Tensor 上做轻量验证。 |


# 二. 上游用例检查情况:

1. torch.utils.checkpoint.CheckpointFunction.backward:
   上游有测试,但不是直接调用内部 backward,而是通过 checkpoint(..., use_reentrant=True) + backward() 间接覆盖真实路径,因此需要补充torch-npu平台的测试用例,

2. torch.utils.cpp_extension.BuildExtension.with_options:
   上游有测试/使用覆盖,在 test/cpp_extensions/setup.py 中通过 BuildExtension.with_options(use_ninja=USE_NINJA)间接参与真实扩展构建流程,因此需要补充torch-npu平台的测试用例。

3. torch.utils.hipify.hipify_python.hipify:
   上游有 hipify 模块 import 测试和 Trie 辅助结构测试;没有看到完整直接调用 hipify() 并校验 CUDA→HIP 转换结果的单测,但 cpp_extension 的 ROCm 构建链路会间接调用它。该API和torch-npu平台无关,因此无需进行测试用例补充。

4. torch.utils._contextlib._DecoratorContextManager:
   上游没有直接测试该内部类,但通过 set_device、torch.no_grad 等上下文管理器的装饰器用法间接覆盖其核心能力。因此需要进行测试用例补充。

# 三. 资料情况检查:

| API | PyTorch 2.7 | PyTorch 2.11 | PyTorch 2.12 | PyTorch 2.13 | 结论 |
|---|---|---|---|---|---|
| `torch.utils.checkpoint.CheckpointFunction.backward` | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 官方公开文档主要记录 `torch.utils.checkpoint.checkpoint`,`CheckpointFunction.backward` 更偏内部实现。 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 官方文档有 `BuildExtension` 类条目,但 `with_options` 方法本身未单独成页。 |
| `torch.utils.hipify.hipify_python.hipify` | 有独立条目 | 有独立条目 | 有独立条目 | 有独立条目 | 2.7.1/2.11/2.12/2.13 官方 generated 文档均有独立条目 |
| `torch.utils._contextlib._DecoratorContextManager` | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 未查到独立条目 | 内部类,不属于稳定公开 API 文档条目。 |

如表所示,虽然`torch.utils.hipify.hipify_python.hipify`在各个分支都有独立条目,因此 `torch.utils.hipify.hipify_python.hipify` 需要进行资料补充。


# 四. API功能性验证

## 1. 测试场景

| API | 测试场景 | 预期结果 |
|---|---|---|
| `torch.utils.checkpoint.CheckpointFunction.backward` | 检查 `CheckpointFunction.backward` 是否存在且可调用 | API 存在,并且是可调用对象 |
| `torch.utils.checkpoint.CheckpointFunction.backward` | 在 NPU 上通过 `checkpoint(..., use_reentrant=True)` 触发 backward,并与普通 backward 对比 | checkpoint 路径输出和梯度与普通路径一致,梯度位于 NPU |
| `torch.utils.checkpoint.CheckpointFunction.backward` | checkpoint 函数包含非 Tensor 参数 | backward 正常执行,输出和梯度与普通路径一致 |
| `torch.utils.checkpoint.CheckpointFunction.backward` | checkpoint 函数返回多个 Tensor 输出 | 多输出均正确,合并 loss 后梯度与普通路径一致 |
| `torch.utils.checkpoint.CheckpointFunction.backward` | checkpoint 中包含 Dropout,并验证 RNG 状态保存恢复 | checkpoint 路径和普通路径的梯度一致 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 调用 `with_options(use_ninja=False)` 生成构建类 | 返回结果是 `BuildExtension` 的子类,且不是原始 `BuildExtension` 类 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 注入 `use_ninja=False`、`no_python_abi_suffix=True` 参数 | 实例化后的构建命令参数正确生效 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 构造时传入与预设参数冲突的参数 | `with_options` 中预设的参数优先生效 |
| `torch.utils.cpp_extension.BuildExtension.with_options` | 多次调用 `with_options` 生成不同构建类 | 不同构建类可独立实例化,配置互不影响 |
| `torch.utils.hipify.hipify_python.hipify` | 检查 `hipify_python.hipify` 是否存在且可调用 | API 存在,并且是可调用对象 |
| `torch.utils.hipify.hipify_python.hipify` | 创建 `.cu` 文件并调用 `hipify()` 处理 | 返回结果为 `dict`,且包含目标 CUDA 文件处理记录 |
| `torch.utils.hipify.hipify_python.hipify` | 使用 `extra_files` 和 `hipify_extra_files_only=True` 只处理额外文件 | 返回结果包含指定 extra CUDA 文件 |
| `torch.utils.hipify.hipify_python.hipify` | 使用 `ignores` 忽略指定 CUDA 文件 | 被忽略文件不出现在处理结果中 |
| `torch.utils._contextlib._DecoratorContextManager` | 自定义上下文管理器作为普通函数装饰器 | 执行顺序为 `enter -> body -> exit`,函数结果正确 |
| `torch.utils._contextlib._DecoratorContextManager` | 被装饰函数抛出异常 | 即使函数抛异常,`__exit__` 仍正常执行 |
| `torch.utils._contextlib._DecoratorContextManager` | 自定义上下文管理器作为 generator 函数装饰器 | generator 执行期间上下文保持生效,产出结果正确 |
| `torch.utils._contextlib._DecoratorContextManager` | 通过公开接口 `@torch.no_grad()` 在 NPU Tensor 上间接验证装饰器行为 | 输出 Tensor 位于 NPU,且 `requires_grad=False` |

## 2. 测试核心代码

```python
class TestTorchUtilsCheckpointFunctionBackward(TestCase):

    def test_checkpoint_function_backward_exists(self):
        self.assertTrue(hasattr(CheckpointFunction, "backward"))
        self.assertTrue(callable(CheckpointFunction.backward))

    def test_checkpoint_backward_matches_normal_backward_on_npu(self):
        if not npu_available():
            self.skipTest("NPU is not available")

        def run_fn(x):
            return torch.sin(x) * torch.cos(x) + x * x

        x = torch.randn(4, 4, device="npu", dtype=torch.float32, requires_grad=True)
        x_ref = x.detach().clone().requires_grad_(True)

        checkpoint_out = checkpoint(run_fn, x, use_reentrant=True)
        normal_out = run_fn(x_ref)

        checkpoint_out.sum().backward()
        normal_out.sum().backward()

        self.assertEqual(checkpoint_out.device.type, "npu")
        self.assertIsNotNone(x.grad)
        self.assertEqual(x.grad.device.type, "npu")
        self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu())
        self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())

    def test_checkpoint_backward_with_non_tensor_argument_on_npu(self):
        if not npu_available():
            self.skipTest("NPU is not available")

        def run_fn(x, scale):
            return x * scale + x.relu()

        x = torch.randn(3, 3, device="npu", dtype=torch.float32, requires_grad=True)
        x_ref = x.detach().clone().requires_grad_(True)
        scale = 2.5

        checkpoint_out = checkpoint(run_fn, x, scale, use_reentrant=True)
        normal_out = run_fn(x_ref, scale)

        checkpoint_out.sum().backward()
        normal_out.sum().backward()

        self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu())
        self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())

    def test_checkpoint_backward_with_multiple_outputs_on_npu(self):
        if not npu_available():
            self.skipTest("NPU is not available")

        def run_fn(x):
            return x * 2.0, x * x

        x = torch.randn(2, 3, device="npu", dtype=torch.float32, requires_grad=True)
        x_ref = x.detach().clone().requires_grad_(True)

        out1, out2 = checkpoint(run_fn, x, use_reentrant=True)
        ref1, ref2 = run_fn(x_ref)

        loss = out1.sum() + out2.sum()
        ref_loss = ref1.sum() + ref2.sum()

        loss.backward()
        ref_loss.backward()

        self.assertRtolEqual(out1.detach().cpu(), ref1.detach().cpu())
        self.assertRtolEqual(out2.detach().cpu(), ref2.detach().cpu())
        self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())

    def test_checkpoint_backward_rng_state_with_dropout_on_npu(self):
        if not npu_available():
            self.skipTest("NPU is not available")
        if not hasattr(torch.npu, "get_rng_state") or not hasattr(torch.npu, "set_rng_state"):
            self.skipTest("NPU RNG state APIs are not available")

        torch.manual_seed(1234)
        torch.npu.manual_seed(1234)

        dropout = torch.nn.Dropout(p=0.5)

        def run_fn(x):
            return dropout(x)

        x = torch.randn(128, device="npu", dtype=torch.float32, requires_grad=True)

        cpu_state = torch.get_rng_state()
        npu_state = torch.npu.get_rng_state()

        checkpoint_out = checkpoint(run_fn, x, use_reentrant=True)
        checkpoint_out.sum().backward()
        checkpoint_grad = x.grad.detach().clone()

        torch.set_rng_state(cpu_state)
        torch.npu.set_rng_state(npu_state)
        x_ref = x.detach().clone().requires_grad_(True)

        normal_out = run_fn(x_ref)
        normal_out.sum().backward()

        self.assertRtolEqual(checkpoi

See merge request: Ascend/pytorch!45275
2026-10-07 21:05:32 +08:00

396 lines
13 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, cpp_extension, hipify and
contextlib related APIs on NPU.
This file validates the core behavior of the following APIs:
1. torch.utils.checkpoint.CheckpointFunction.backward
2. torch.utils.cpp_extension.BuildExtension.with_options
3. torch.utils.hipify.hipify_python.hipify
4. torch.utils._contextlib._DecoratorContextManager
"""
import os
import tempfile
import textwrap
import torch
from setuptools import Distribution
from torch.utils.checkpoint import CheckpointFunction, checkpoint
from torch.utils.cpp_extension import BuildExtension
from torch.utils.hipify import hipify_python
from torch.utils._contextlib import _DecoratorContextManager
from torch_npu.testing.testcase import TestCase, run_tests
def npu_available():
return hasattr(torch, "npu") and torch.npu.is_available()
class TestTorchUtilsCheckpointFunctionBackward(TestCase):
def test_checkpoint_function_backward_exists(self):
self.assertTrue(hasattr(CheckpointFunction, "backward"))
self.assertTrue(callable(CheckpointFunction.backward))
def test_checkpoint_backward_matches_normal_backward_on_npu(self):
if not npu_available():
self.skipTest("NPU is not available")
def run_fn(x):
return torch.sin(x) * torch.cos(x) + x * x
x = torch.randn(4, 4, device="npu", dtype=torch.float32, requires_grad=True)
x_ref = x.detach().clone().requires_grad_(True)
checkpoint_out = checkpoint(run_fn, x, use_reentrant=True)
normal_out = run_fn(x_ref)
checkpoint_out.sum().backward()
normal_out.sum().backward()
self.assertEqual(checkpoint_out.device.type, "npu")
self.assertIsNotNone(x.grad)
self.assertEqual(x.grad.device.type, "npu")
self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu())
self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())
def test_checkpoint_backward_with_non_tensor_argument_on_npu(self):
if not npu_available():
self.skipTest("NPU is not available")
def run_fn(x, scale):
return x * scale + x.relu()
x = torch.randn(3, 3, device="npu", dtype=torch.float32, requires_grad=True)
x_ref = x.detach().clone().requires_grad_(True)
scale = 2.5
checkpoint_out = checkpoint(run_fn, x, scale, use_reentrant=True)
normal_out = run_fn(x_ref, scale)
checkpoint_out.sum().backward()
normal_out.sum().backward()
self.assertRtolEqual(checkpoint_out.detach().cpu(), normal_out.detach().cpu())
self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())
def test_checkpoint_backward_with_multiple_outputs_on_npu(self):
if not npu_available():
self.skipTest("NPU is not available")
def run_fn(x):
return x * 2.0, x * x
x = torch.randn(2, 3, device="npu", dtype=torch.float32, requires_grad=True)
x_ref = x.detach().clone().requires_grad_(True)
out1, out2 = checkpoint(run_fn, x, use_reentrant=True)
ref1, ref2 = run_fn(x_ref)
loss = out1.sum() + out2.sum()
ref_loss = ref1.sum() + ref2.sum()
loss.backward()
ref_loss.backward()
self.assertRtolEqual(out1.detach().cpu(), ref1.detach().cpu())
self.assertRtolEqual(out2.detach().cpu(), ref2.detach().cpu())
self.assertRtolEqual(x.grad.cpu(), x_ref.grad.cpu())
def test_checkpoint_backward_rng_state_with_dropout_on_npu(self):
if not npu_available():
self.skipTest("NPU is not available")
if not hasattr(torch.npu, "get_rng_state") or not hasattr(torch.npu, "set_rng_state"):
self.skipTest("NPU RNG state APIs are not available")
torch.manual_seed(1234)
torch.npu.manual_seed(1234)
dropout = torch.nn.Dropout(p=0.5)
def run_fn(x):
return dropout(x)
x = torch.randn(128, device="npu", dtype=torch.float32, requires_grad=True)
cpu_state = torch.get_rng_state()
npu_state = torch.npu.get_rng_state()
checkpoint_out = checkpoint(run_fn, x, use_reentrant=True)
checkpoint_out.sum().backward()
checkpoint_grad = x.grad.detach().clone()
torch.set_rng_state(cpu_state)
torch.npu.set_rng_state(npu_state)
x_ref = x.detach().clone().requires_grad_(True)
normal_out = run_fn(x_ref)
normal_out.sum().backward()
self.assertRtolEqual(checkpoint_grad.cpu(), x_ref.grad.cpu())
class TestTorchUtilsBuildExtensionWithOptions(TestCase):
def test_build_extension_with_options_returns_subclass(self):
custom_build_extension = BuildExtension.with_options(use_ninja=False)
self.assertTrue(issubclass(custom_build_extension, BuildExtension))
self.assertIsNot(custom_build_extension, BuildExtension)
def test_build_extension_with_options_injects_options(self):
custom_build_extension = BuildExtension.with_options(
use_ninja=False,
no_python_abi_suffix=True,
)
dist = Distribution({"name": "test_extension"})
cmd = custom_build_extension(dist)
self.assertFalse(cmd.use_ninja)
self.assertTrue(cmd.no_python_abi_suffix)
def test_build_extension_with_options_overrides_constructor_kwargs(self):
custom_build_extension = BuildExtension.with_options(use_ninja=False)
dist = Distribution({"name": "test_extension"})
cmd = custom_build_extension(dist, use_ninja=True)
self.assertFalse(cmd.use_ninja)
def test_build_extension_with_options_multiple_classes_are_independent(self):
no_ninja_build = BuildExtension.with_options(use_ninja=False)
ninja_build = BuildExtension.with_options(use_ninja=True)
dist1 = Distribution({"name": "test_extension_1"})
dist2 = Distribution({"name": "test_extension_2"})
cmd1 = no_ninja_build(dist1)
cmd2 = ninja_build(dist2)
self.assertFalse(cmd1.use_ninja)
self.assertIsInstance(cmd2.use_ninja, bool)
class TestTorchUtilsHipifyPythonHipify(TestCase):
def test_import_hipify_python_and_hipify_exists(self):
self.assertTrue(hasattr(hipify_python, "hipify"))
self.assertTrue(callable(hipify_python.hipify))
def test_hipify_python_hipify_cuda_file(self):
with tempfile.TemporaryDirectory() as project_dir:
output_dir = os.path.join(project_dir, "hip_output")
os.makedirs(output_dir, exist_ok=True)
cuda_file = os.path.join(project_dir, "kernel.cu")
with open(cuda_file, "w", encoding="utf-8") as f:
f.write(
textwrap.dedent(
"""
#include <cuda_runtime.h>
__global__ void add_kernel(float* x) {
int i = threadIdx.x;
x[i] += 1.0f;
}
"""
)
)
result = hipify_python.hipify(
project_directory=project_dir,
output_directory=output_dir,
extra_files=(cuda_file,),
hipify_extra_files_only=True,
show_progress=False,
)
self.assertIsInstance(result, dict)
self.assertTrue(len(result) > 0)
self.assertTrue(
any("kernel" in os.path.basename(path) for path in result.keys())
)
def test_hipify_python_hipify_extra_file_only(self):
with tempfile.TemporaryDirectory() as project_dir:
cuda_file = os.path.join(project_dir, "extra_kernel.cu")
with open(cuda_file, "w", encoding="utf-8") as f:
f.write(
textwrap.dedent(
"""
#include <cuda_runtime.h>
__global__ void extra_kernel(float* x) {
x[threadIdx.x] = 1.0f;
}
"""
)
)
result = hipify_python.hipify(
project_directory=project_dir,
output_directory=project_dir,
extra_files=(cuda_file,),
hipify_extra_files_only=True,
show_progress=False,
)
self.assertIsInstance(result, dict)
self.assertTrue(
any("extra_kernel" in os.path.basename(path) for path in result.keys())
)
def test_hipify_python_hipify_ignores_file(self):
with tempfile.TemporaryDirectory() as project_dir:
ignored_file = os.path.join(project_dir, "ignored_kernel.cu")
with open(ignored_file, "w", encoding="utf-8") as f:
f.write(
textwrap.dedent(
"""
#include <cuda_runtime.h>
__global__ void ignored_kernel(float* x) {
x[threadIdx.x] = 1.0f;
}
"""
)
)
result = hipify_python.hipify(
project_directory=project_dir,
output_directory=project_dir,
includes=("*",),
ignores=("*ignored_kernel.cu",),
show_progress=False,
)
self.assertIsInstance(result, dict)
self.assertFalse(
any("ignored_kernel" in os.path.basename(path) for path in result.keys())
)
class TestTorchUtilsDecoratorContextManager(TestCase):
def test_decorator_context_manager_as_function_decorator(self):
log = []
class SampleContext(_DecoratorContextManager):
def __enter__(self):
log.append("enter")
def __exit__(self, exc_type, exc_value, traceback):
log.append("exit")
def clone(self):
return SampleContext()
ctx = SampleContext()
device = "npu" if npu_available() else "cpu"
@ctx
def decorated_func(x):
log.append("body")
return x + 1
x = torch.ones(2, 2, device=device)
y = decorated_func(x)
self.assertEqual(log, ["enter", "body", "exit"])
self.assertEqual(y.device.type, torch.device(device).type)
self.assertRtolEqual(y.cpu(), torch.ones(2, 2) + 1)
def test_decorator_context_manager_exits_on_exception(self):
log = []
class SampleContext(_DecoratorContextManager):
def __enter__(self):
log.append("enter")
def __exit__(self, exc_type, exc_value, traceback):
log.append("exit")
def clone(self):
return SampleContext()
ctx = SampleContext()
@ctx
def decorated_func():
log.append("body")
raise RuntimeError("expected error")
with self.assertRaisesRegex(RuntimeError, "expected error"):
decorated_func()
self.assertEqual(log, ["enter", "body", "exit"])
def test_decorator_context_manager_as_generator_decorator(self):
log = []
class SampleContext(_DecoratorContextManager):
def __enter__(self):
log.append("enter")
def __exit__(self, exc_type, exc_value, traceback):
log.append("exit")
def clone(self):
return SampleContext()
ctx = SampleContext()
device = "npu" if npu_available() else "cpu"
@ctx
def decorated_generator():
log.append("yield_1")
yield torch.ones(1, device=device)
log.append("yield_2")
yield torch.ones(1, device=device) + 1
outputs = list(decorated_generator())
yield_events = [item for item in log if item.startswith("yield")]
self.assertEqual(yield_events, ["yield_1", "yield_2"])
self.assertEqual(log.count("enter"), log.count("exit"))
self.assertGreaterEqual(log.count("enter"), 1)
self.assertEqual(outputs[0].device.type, torch.device(device).type)
self.assertEqual(outputs[1].device.type, torch.device(device).type)
self.assertRtolEqual(outputs[0].cpu(), torch.ones(1))
self.assertRtolEqual(outputs[1].cpu(), torch.ones(1) + 1)
def test_torch_no_grad_decorator_behavior_on_npu(self):
if not npu_available():
self.skipTest("NPU is not available")
@torch.no_grad()
def decorated_func(x):
return x * 2
x = torch.randn(2, 2, device="npu", requires_grad=True)
y = decorated_func(x)
self.assertEqual(y.device.type, "npu")
self.assertFalse(y.requires_grad)
if __name__ == "__main__":
run_tests()