test: add NPU tests for torch._higher_order_ops.auto_functionalized

Co-authored-by: gcw_fiAo4tDr<iqueenqueen@163.com>



# message auto-generated for no-merge-commit merge:
!45073 merge test-auto-functionalized-master into master

test: add NPU tests for torch._higher_order_ops.auto_functionalized

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

# 【合入来源】
关联任务:[#2701 【社区任务】7月社区任务第一期-Ascend for PyTorch API 一致性开发(78)](https://gitcode.com/Ascend/pytorch/issues/2701)


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

# 【修改方案】
一、API 功能

```text
torch._higher_order_ops.auto_functionalized(_mutable_op, **kwargs) 用于把带可变参数的自定义算子转换为函数式调用,核心能力如下:

调用签名
   torch._higher_order_ops.auto_functionalized(_mutable_op, **kwargs)

参数说明
   _mutable_op(torch._ops.OpOverload,必选):需要进行函数式转换的可变自定义算子重载。该算子的 schema 必须包含至少一个带写别名的可变参数;当前支持的可变参数类型为 Tensor、Tensor? 和 Tensor[]。

   **kwargs(Any,必选项由 _mutable_op 的 schema 动态决定):传给 _mutable_op 的实际参数,键名、类型、默认值以及哪些参数可变均由 _mutable_op 的 schema 定义。例如 schema 为 mutate_and_sum(Tensor(a!) mutable, Tensor increment) -> Tensor 时,应传入 mutable=<Tensor> 和 increment=<Tensor>。

返回值说明
   返回扁平 tuple:先放置 _mutable_op 的原始输出,再按 schema 参数顺序追加所有更新后的可变参数克隆。若原算子无返回值,首项为 None;若原算子有多个输出,则多个输出依次位于更新后的可变参数之前。

内部参数说明
   源码执行实现中的 _only_clone_these_tensors 是内部派发优化参数,不属于调用者需要提供的 API 参数。

1. 可变参数识别
   根据自定义算子的 schema 和 alias information,识别带写别名的 Tensor、Tensor? 和 Tensor[] 参数。

2. 函数式克隆
   在执行算子前克隆可变参数,并让算子只修改克隆,保证调用者传入的原始张量不被原地修改。

3. 结果组织
   先返回原算子的输出,再按 schema 中可变参数的顺序返回更新后的克隆;无原始输出的算子以 None 作为首个返回值。

4. 设备和存储语义
   克隆及算子输出应保持输入所在设备,同时更新后的克隆应与原输入具有独立存储。

5. 错误边界
   传入没有可变参数的算子不符合该高阶算子的使用前提,应触发断言异常。
```

二、测试文件 test_auto_functionalized.py 完整验证该 API 的原因

```text
该测试文件从导出路径、核心功能、参数类型、返回协议、设备/存储语义和异常边界六个维度验证 torch._higher_order_ops.auto_functionalized:

1. 导出路径验证
   test_reexported_object_is_identical:验证 torch._higher_order_ops.auto_functionalized 与实现模块中的 auto_functionalized 为同一对象,确保任务指定导出路径正确。

2. 单个可变 Tensor 核心功能
   test_mutable_tensor_is_cloned_and_returned_on_device:验证原输入不变、克隆被正确更新、算子输出正确、输出和克隆保持 NPU 设备,并通过 data_ptr 验证克隆与原输入存储独立。

3. 可变 Tensor[] 分支
   test_mutable_tensor_list_is_cloned_on_device:同时覆盖空列表与非空列表,验证列表元素逐一克隆、逐一更新、保持设备且不污染源列表。

4. 多输出与多可变参数
   test_multiple_outputs_precede_mutable_tensors:验证两个算子输出位于两个更新后可变参数之前,并验证每个参数各自执行正确的原地语义。

5. 可变 Tensor? 分支
   test_optional_mutable_tensor_supports_none_and_tensor:覆盖 None 与非空张量,验证可选可变参数的两条核心路径。

6. 非法使用边界
   test_non_mutating_operator_is_rejected:验证无可变参数算子触发 AssertionError,明确 API 使用边界。

7. 社区覆盖补充
   PyTorch 的 test/inductor/test_auto_functionalize.py 主要覆盖内部 functionalization/Inductor 路径并使用 CPU-only 自定义算子;本文件直接调用任务指定导出对象,并补充真实 NPU 的设备保持和克隆存储独立性验证。

综上,该文件覆盖正常场景、空值/空列表边界、多参数多输出、异常路径以及真实 NPU 语义,可完整看护本 API 的关键行为。
```

三、NPU适配

```text
1. 真实 NPU 张量
   测试通过 torch.accelerator.current_accelerator() 获取当前加速器类型,并用该设备创建所有参与计算的 Tensor;NPU 环境下 DEVICE_TYPE 为 npu。

2. NPU 算子执行
   测试自定义算子注册为 CompositeExplicitAutograd,实现中的 add_、mul_、sum 等张量运算由 torch_npu 注册的 NPU 后端执行,更新结果及算子输出均保留在 npu:0。

3. 设备与存储断言
   用例显式断言结果和更新后克隆的 device.type,并使用 data_ptr 验证克隆与 NPU 原输入存储独立,防止只验证数值而遗漏设备语义。

4. 防止 CPU 回退
   上板运行器显式导入 torch_npu,要求 torch.npu.is_available() 为 True,并先创建 device='npu' 的冒烟张量、断言其设备为 npu:0,再执行原测试文件;CPU fallback 无法得到所附成功日志。

5. Triton-Ascend 依赖
   本用例直接验证 eager 高阶算子和基础 NPU 张量操作,不进入 torch.compile/Inductor/Triton 代码生成路径,因此不需要安装 Triton-Ascend。
```

# 【资料变更】
> > 不涉及

已检查 [`master` 分支 `docs/zh/api/native_api`](https://gitcode.com/Ascend/pytorch/tree/master/docs/zh/api/native_api)。`torch._higher_order_ops.auto_functionalized` 位于带下划线的 PyTorch 私有接口命名空间,没有对应公开资料条目;按 API 一致性任务书,PyTorch 私有接口无需补资料,因此不提交资料 PR。

# 【接口变更】
> 不涉及

API 已存在,本 PR 只新增 `test/test_auto_functionalized.py`,不修改接口实现、schema 或对外行为。


# 【功能验证】

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

测试场景:在 Ascend 910B2 上注册包含 `Tensor`、`Tensor[]`、`Tensor?`、多个可变参数和多个返回值的自定义算子,直接调用 `torch._higher_order_ops.auto_functionalized`,验证正常、边界和异常场景。

测试方法:使用独立虚拟环境,先完成 NPU 可用性及 `npu:0` 冒烟检查,再执行新增测试文件。上传文件与本地文件 SHA-256 均为 `53e99c73593ff5932420270cec9b663d15fdbab32eb4891f7029dec0ad8e7678`。

目标分支:`master`

源分支:`gcw_fiAo4tDr/pytorch:test-auto-functionalized-master`

已验证提交:`61f2b43ebc1af1100d1624c8ff19900be6946f26`

验证环境:aarch64、Ascend 910B2(Health `OK`)、Driver/npu-smi 25.5.2、CANN 9.1.0、Python 3.12.13。`master` 使用 `torch==2.14.0.dev20260719+cpu`,并从上述提交源码构建安装 `torch_npu==2.14.0+git61f2b43`。

执行结果如下:

```text
Virtual environment: /workspace/venvs/master
torch: 2.14.0.dev20260719+cpu
torch_npu: 2.14.0+git61f2b43
accelerator: npu
npu_available: True
npu_name: Ascend910B2
smoke_device: npu:0
......
----------------------------------------------------------------------
Ran 6 tests in 1.008s

OK
```

![master-hidevlab-log.png](https://raw.gitcode.com/user-images/assets/7404318/622c9e70-86c5-4f42-90e1-acdf7cfd7d8b/master-hidevlab-log.png 'master-hidevlab-log.png')



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

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


See merge request: Ascend/pytorch!45073
This commit is contained in:
gcw_fiAo4tDr
2026-09-04 11:32:35 +08:00
committed by ascend-robot
parent cf497ba393
commit 36a38cc9d9
+218
View File
@@ -0,0 +1,218 @@
# 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._higher_order_ops APIs on NPU:
1. PyTorch community lacks direct accelerator validation for
torch._higher_order_ops.auto_functionalized, so this file is added.
2. This file validates the exported object and functional cloning behavior
for mutable Tensor, optional Tensor, and Tensor list arguments (extendable).
"""
import torch
import torch._higher_order_ops
import torch._higher_order_ops.auto_functionalize
from torch.testing._internal.common_utils import run_tests, TestCase
DEVICE_TYPE = (
acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
)
class TestAutoFunctionalized(TestCase):
def test_reexported_object_is_identical(self):
self.assertIs(
torch._higher_order_ops.auto_functionalized,
torch._higher_order_ops.auto_functionalize.auto_functionalized,
)
def test_mutable_tensor_is_cloned_and_returned_on_device(self):
with torch.library._scoped_library(
"test_auto_functionalized", "FRAGMENT"
) as lib:
lib.define(
"mutate_and_sum(Tensor(a!) mutable, Tensor increment) -> Tensor"
)
def mutate_and_sum(mutable, increment):
mutable.add_(increment)
return mutable.sum()
lib.impl(
"mutate_and_sum", mutate_and_sum, "CompositeExplicitAutograd"
)
mutable = torch.tensor([1.0, 2.0, 3.0], device=DEVICE_TYPE)
increment = torch.tensor([4.0, 5.0, 6.0], device=DEVICE_TYPE)
original = mutable.clone()
result, updated_mutable = torch._higher_order_ops.auto_functionalized(
torch.ops.test_auto_functionalized.mutate_and_sum.default,
mutable=mutable,
increment=increment,
)
expected = original + increment
self.assertEqual(mutable, original)
self.assertEqual(updated_mutable, expected)
self.assertEqual(result, expected.sum())
self.assertEqual(result.device.type, DEVICE_TYPE)
self.assertEqual(updated_mutable.device.type, DEVICE_TYPE)
self.assertNotEqual(updated_mutable.data_ptr(), mutable.data_ptr())
def test_mutable_tensor_list_is_cloned_on_device(self):
with torch.library._scoped_library(
"test_auto_functionalized", "FRAGMENT"
) as lib:
lib.define(
"mutate_list(Tensor(a!)[] mutable, Tensor increment) -> ()"
)
def mutate_list(mutable, increment):
for tensor in mutable:
tensor.add_(increment)
lib.impl("mutate_list", mutate_list, "CompositeExplicitAutograd")
increment = torch.tensor([5.0, 6.0], device=DEVICE_TYPE)
cases = [
[],
[
torch.tensor([1.0, 2.0], device=DEVICE_TYPE),
torch.tensor([3.0, 4.0], device=DEVICE_TYPE),
],
]
for mutable in cases:
with self.subTest(length=len(mutable)):
original = [tensor.clone() for tensor in mutable]
result, updated_mutable = (
torch._higher_order_ops.auto_functionalized(
torch.ops.test_auto_functionalized.mutate_list.default,
mutable=mutable,
increment=increment,
)
)
self.assertIsNone(result)
self.assertEqual(mutable, original)
self.assertEqual(
updated_mutable,
[tensor + increment for tensor in original],
)
for updated, source in zip(updated_mutable, mutable):
self.assertEqual(updated.device.type, DEVICE_TYPE)
self.assertNotEqual(
updated.data_ptr(), source.data_ptr()
)
def test_multiple_outputs_precede_mutable_tensors(self):
with torch.library._scoped_library(
"test_auto_functionalized", "FRAGMENT"
) as lib:
lib.define(
"mutate_pair(Tensor(a!) first, Tensor(b!) second, "
"Tensor increment) -> (Tensor, Tensor)"
)
def mutate_pair(first, second, increment):
first.add_(increment)
second.mul_(increment)
return first.sum(), second.sum()
lib.impl("mutate_pair", mutate_pair, "CompositeExplicitAutograd")
first = torch.tensor([1.0, 2.0], device=DEVICE_TYPE)
second = torch.tensor([3.0, 4.0], device=DEVICE_TYPE)
increment = torch.tensor([2.0, 3.0], device=DEVICE_TYPE)
original_first = first.clone()
original_second = second.clone()
first_result, second_result, updated_first, updated_second = (
torch._higher_order_ops.auto_functionalized(
torch.ops.test_auto_functionalized.mutate_pair.default,
first=first,
second=second,
increment=increment,
)
)
expected_first = original_first + increment
expected_second = original_second * increment
self.assertEqual(first, original_first)
self.assertEqual(second, original_second)
self.assertEqual(first_result, expected_first.sum())
self.assertEqual(second_result, expected_second.sum())
self.assertEqual(updated_first, expected_first)
self.assertEqual(updated_second, expected_second)
self.assertEqual(updated_first.device.type, DEVICE_TYPE)
self.assertEqual(updated_second.device.type, DEVICE_TYPE)
def test_optional_mutable_tensor_supports_none_and_tensor(self):
with torch.library._scoped_library(
"test_auto_functionalized", "FRAGMENT"
) as lib:
lib.define(
"mutate_optional(Tensor(a!)? mutable, Tensor increment) -> ()"
)
def mutate_optional(mutable, increment):
if mutable is not None:
mutable.add_(increment)
lib.impl(
"mutate_optional", mutate_optional, "CompositeExplicitAutograd"
)
increment = torch.tensor([2.0, 3.0], device=DEVICE_TYPE)
for mutable in (
None,
torch.tensor([1.0, 1.0], device=DEVICE_TYPE),
):
with self.subTest(is_none=mutable is None):
original = mutable.clone() if mutable is not None else None
result, updated_mutable = (
torch._higher_order_ops.auto_functionalized(
torch.ops.test_auto_functionalized.mutate_optional.default,
mutable=mutable,
increment=increment,
)
)
self.assertIsNone(result)
if mutable is None:
self.assertIsNone(updated_mutable)
else:
self.assertEqual(mutable, original)
self.assertEqual(updated_mutable, original + increment)
self.assertEqual(updated_mutable.device.type, DEVICE_TYPE)
def test_non_mutating_operator_is_rejected(self):
with torch.library._scoped_library(
"test_auto_functionalized", "FRAGMENT"
) as lib:
lib.define("identity(Tensor value) -> Tensor")
value = torch.tensor([1.0], device=DEVICE_TYPE)
with self.assertRaises(AssertionError):
torch._higher_order_ops.auto_functionalized(
torch.ops.test_auto_functionalized.identity.default,
value=value,
)
if __name__ == "__main__":
run_tests()