[test] Add torch.untypedstorage{filename|hpu|nbytes|new} API test case

Co-authored-by: gcw_CHjSLYhf<2839668818@qq.com>



# message auto-generated for no-merge-commit merge:
!45157 merge untypedstorage_filename_hpu_nbytes_new-master into master

[test] Add torch.untypedstorage{filename|hpu|nbytes|new} API test case

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

# 【合入来源】

- [ ] 需求
- [ ] 问题单
- [x] issue/工单 https://gitcode.com/Ascend/pytorch/issues/3739 https://gitcode.com/Ascend/pytorch/issues/3750 https://gitcode.com/Ascend/pytorch/issues/3760 https://gitcode.com/Ascend/pytorch/issues/3761
- [ ] 重构优化
- [ ] 资料更新

公开issue:

- `torch.UntypedStorage.filename`:[8月社区任务第一期-Ascend for PyTorch API 一致性开发(78)](https://gitcode.com/Ascend/pytorch/issues/3739)
- `torch.UntypedStorage.hpu`:[8月社区任务第一期-Ascend for PyTorch API 一致性开发(89)](https://gitcode.com/Ascend/pytorch/issues/3750)
- `torch.UntypedStorage.nbytes`:[8月社区任务第一期-Ascend for PyTorch API 一致性开发(99)](https://gitcode.com/Ascend/pytorch/issues/3760)
- `torch.UntypedStorage.new`: [8月社区任务第一期-Ascend for PyTorch API 一致性开发(100) ](https://gitcode.com/Ascend/pytorch/issues/3761)

# 一. API 功能说明:

## 1. torch.UntypedStorage.filename

`filename` 是`torch.UntypedStorage`这个类的一个只读属性,用于获取与当前 Storage 关联的内存映射文件路径。因此和平台设备有关联,需要增加一个快速的验证性测试。

PyTorch 2.7 中的实现为:

```python
@property
def filename(self):
    return self._get_filename()
```

因此它属于 Python 属性封装,但实际结果由底层 Storage 元数据接口 `_get_filename()` 提供。

## 2. torch.UntypedStorage.hpu

`torch.UntypedStorage.hpu()` 用于 返回一个在 HPU(Habana Gaudi 加速器)上的存储副本,如果该对象已在HPU内存中且位于正确的设备上,则不执行复制,直接返回原始对象。因为该API与HPU平台设备具有强绑定关系。

参数说明:

- `device`:目标 HPU 设备编号,默认使用当前 HPU 设备;
- `non_blocking`:如果源内存满足异步复制条件,则允许异步复制。

PyTorch 2.7 中的核心实现为:

```python
def hpu(self, device=None, non_blocking=False):
    device2 = (
        torch.device("hpu", device)
        if device
        else torch.device("hpu")
    )
    return self.to(
        device=device2,
        non_blocking=non_blocking,
    )
```

## 3. torch.UntypedStorage.nbytes

`torch.UntypedStorage.nbytes()` 返回当前底层 Storage 实际占用的字节数,返回类型为 `int`。

但要注意,`nbytes()` 查询的是整个 Storage 的大小,而不是当前 Tensor View 的逻辑数据量。

例如:

```python
base = torch.empty(16, dtype=torch.float32)
view = base[::2]

base.untyped_storage().nbytes() == 64
view.untyped_storage().nbytes() == 64

# view只有8个逻辑元素
view.numel() * view.element_size() == 32
```

这是因为 `view` 和 `base` 共享同一个底层 Storage。

接口本身主要读取底层 Storage 元数据,不执行计算算子,但它读取的是 NPU Storage 的实际字节范围,可以验证 NPU Tensor 到 UntypedStorage 的连接是否正确,因此需要增加 NPU 功能测试。

## 4. torch.UntypedStorage.new

`torch.UntypedStorage.new`在当前 Storage 所在设备上,创建一个新的、大小为 0 的 UntypedStorage。torch.UntypedStorage.new() 由底层 Storage 实现提供。NPU Storage 调用该接口时,需要正确处理 PrivateUse1/NPU 设备信息。因此需要补充这个API在torch-npu平台上的测试用例。

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

检查 PyTorch 上游 Storage 相关测试后,结果如下:

| API | 上游是否存在独立直接用例 | 检查结果 |
|---|---:|---|
| ` torch.UntypedStorage.filename` | 未发现 | 上游核心`test/test_torch.py`中未发现直接读取`.filename`的独立用例 |
| `torch.UntypedStorage.hpu` | 未发现 | 上游核心Storage测试中未发现直接调用`.hpu()`的独立用例 |
| `torch.UntypedStorage.nbytes` | 存在部分覆盖 | 上游在Storage Meta测试中调用了`s.nbytes()`并比较不同Storage的字节数 |
| `torch.UntypedStorage.new` | 存在部分覆盖 | 上游在Storage Meta测试中调用了`s.nbytes()`并比较不同Storage的字节数 |


# 三. 资料情况检查:

- `torch.UntypedStorage.filename`:在torch上游社区存在独立条目,同时在当前项目中该API资料已经存在,但是A5支持情况有误,因此需要进行资料修正。

![image.png](https://raw.gitcode.com/user-images/assets/7404318/e9e62e9c-a679-46cf-ba7e-614957ecab2e/image.png 'image.png')

- `torch.UntypedStorage.hpu`:在torch上游社区存在独立条目,同时在当前项目中该API资料已经存在,由于该API与hpu平台存在硬编码,系统支持情况,因此不需要进行资料补充和修正。

![image.png](https://raw.gitcode.com/user-images/assets/7404318/341d11c7-861d-4089-bb7b-2b376c4a0dee/image.png 'image.png')

- `torch.UntypedStorage.nbytes`在torch上游社区存在独立条目,同时在当前项目中该API资料有误,因此需要进行资料修正。

![image.png](https://raw.gitcode.com/user-images/assets/7404318/bbbee34b-9ae5-46a9-89e5-ac4090473e59/image.png 'image.png')

- `torch.UntypedStorage.new` torch上游社区存在独立条目,同时在当前项目中该API资料有误,因此需要进行资料修正。

![image.png](https://raw.gitcode.com/user-images/assets/7404318/b0846e88-c213-444f-838d-522d07436468/image.png 'image.png')

资料修正补充pr: https://gitcode.com/Ascend/pytorch/pull/46583

# 四. API功能性验证

## 1. 测试场景
# torch.UntypedStorage API 功能性验证

## 1. 测试场景

| 编号 | API | 测试场景 | 预期结果 |
| --- | --- | --- | --- |
| 1 | `torch.UntypedStorage.filename` | 获取普通 CPU Tensor 底层 Storage 的 `filename` | 普通 CPU Storage 未关联内存映射文件,返回 `None` |
| 2 | `torch.UntypedStorage.filename` | 使用 `from_file(shared=True)` 创建共享文件映射 Storage | `filename` 返回字符串,并且规范化路径与映射文件路径一致 |
| 3 | `torch.UntypedStorage.filename` | 使用 `from_file(shared=False)` 创建私有文件映射 Storage | 私有映射的 `filename` 返回 `None` |
| 4 | `torch.UntypedStorage.filename` | 获取 NPU Tensor 底层 Storage 的 `filename` | Storage 位于 NPU,且未关联 CPU 文件映射,返回 `None` |
| 5 | `torch.UntypedStorage.hpu` | 在纯 torch-npu 环境中调用默认参数 `hpu()` | 因未加载 HPU 设备模块,抛出包含 `HPU device module is not loaded` 的 `AssertionError` |
| 6 | `torch.UntypedStorage.hpu` | 指定 `device=1, non_blocking=True` 调用 `hpu()` | 参数可以被接口正常解析;因未加载 HPU 模块,抛出预期 `AssertionError` |
| 7 | `torch.UntypedStorage.nbytes` | 验证 `float16` Tensor 的 CPU/NPU Storage 字节数 | CPU、NPU 结果均等于 `numel × element_size` |
| 8 | `torch.UntypedStorage.nbytes` | 验证 `float32` Tensor 的 CPU/NPU Storage 字节数 | CPU、NPU 结果均等于 `numel × element_size` |
| 9 | `torch.UntypedStorage.nbytes` | 验证 `int32` Tensor 的 CPU/NPU Storage 字节数 | CPU、NPU 结果均等于 `numel × element_size` |
| 10 | `torch.UntypedStorage.nbytes` | 验证 `int64` Tensor 的 CPU/NPU Storage 字节数 | CPU、NPU 结果均等于 `numel × element_size` |
| 11 | `torch.UntypedStorage.nbytes` | 直接在 CPU/NPU 上构造指定字节数的 UntypedStorage | `nbytes()`、`size()` 和 `len()` 均返回构造时指定的字节数 |
| 12 | `torch.UntypedStorage.nbytes` | 创建大小为 0 的空 NPU Storage | `nbytes()`、`size()` 和 `len()` 均返回 0 |
| 13 | `torch.UntypedStorage.nbytes` | 获取非连续 NPU Tensor View 的底层 Storage 字节数 | View 与原 Tensor 共享底层 Storage,返回整个底层 Storage 的字节数 |
| 14 | `torch.UntypedStorage.new` | 对 CPU Storage 调用 `new()` | 返回独立、大小为 0、设备类型仍为 CPU 的 UntypedStorage |
| 15 | `torch.UntypedStorage.new` | 对 NPU Storage 调用 `new()` | 返回独立、大小为 0、设备类型仍为 NPU 的 UntypedStorage |
| 16 | `torch.UntypedStorage.new` | 对 `new()` 返回的 Storage 执行 `resize_()` | 新 Storage 的大小发生变化,原 Storage 的大小不受影响 |
| 17 | `torch.UntypedStorage.new` | 对共享文件映射 Storage 调用 `new()` | 返回普通空 CPU Storage,不继承原 Storage 的文件映射关系 |

## 2. 测试核心代码

```python
class TestUntypedStorageAPIs(TestCase):

    def test_untyped_storage_filename(self):
        # 场景1:普通CPU Storage不关联内存映射文件
        cpu_storage = torch.empty(
            8,
            dtype=torch.float32,
            device="cpu",
        ).untyped_storage()

        self.assertEqual(cpu_storage.device.type, "cpu")
        self.assertIsNone(cpu_storage.filename)

        # 场景2和3:共享文件映射与私有文件映射Storage
        with tempfile.TemporaryDirectory() as temp_dir:
            file_path = os.path.join(
                temp_dir,
                "untyped_storage.bin",
            )

            shared_storage = torch.UntypedStorage.from_file(
                file_path,
                shared=True,
                nbytes=32,
            )

            self.assertEqual(shared_storage.device.type, "cpu")
            self.assertEqual(shared_storage.nbytes(), 32)
            self.assertIsInstance(
                shared_storage.filename,
                str,
            )
            self.assertEqual(
                os.path.realpath(shared_storage.filename),
                os.path.realpath(file_path),
            )

            # 释放共享映射后再创建私有映射
            del shared_storage

            private_storage = torch.UntypedStorage.from_file(
                file_path,
                shared=False,
                nbytes=32,
            )

            self.assertEqual(private_storage.device.type, "cpu")
            self.assertEqual(private_storage.nbytes(), 32)
            self.assertIsNone(private_storage.filename)

            del private_storage

        # 场景4:NPU Storage不关联CPU内存映射文件
        npu_storage = torch.empty(
            8,
            dtype=torch.float32,
            device="npu",
        ).untyped_storage()

        self.assertEqual(npu_storage.device.type, "npu")
        self.assertIsNone(npu_storage.filename)

    def test_untyped_storage_hpu(self):
        npu_storage = torch.empty(
            8,
            dtype=torch.float32,
            device="npu",
        ).untyped_storage()

        self.assertEqual(
            npu_storage.device.type,
            "npu",
        )

        # 场景5:在torch-npu平台使用默认参数调用hpu()
        with self.assertRaisesRegex(
            AssertionError,
            r"HPU device module is not loaded",
        ):
            npu_storage.hpu()

        # 场景6:在torch-npu平台指定device和non_blocking参数
        with self.assertRaisesRegex(
            AssertionError,
            r"HPU device module is not loaded",
        ):
            npu_storage.hpu(
                device=1,
                non_blocking=True,
            )

    def test_untyped_storage_nbytes_for_tensor_dtypes(self):
        test_cases = [
            (torch.float16, 6),
            (torch.float32, 6),
            (torch.int32, 6),
            (torch.int64, 6),
        ]

        # 场景7至10:不同dtype的CPU/NPU Storage字节数
        for dtype, numel in test_cases:
            with self.subTest(dtype=dtype):
                cpu_tensor = torch.empty(
                    numel,
                    dtype=dtype,
                    device="cpu",
                )
                npu_tensor = torch.empty(
                    numel,
                    dtype=dtype,
                    device="npu",
                )

                cpu_storage = cpu_tensor.untyped_storage()
                npu_storage = npu_tensor.untyped_storage()

                expected_nbytes = (
                    numel * cpu_tensor.element_size()
                )

                self.assertEqual(
                    cpu_storage.nbytes(),
                    expected_nbytes,
                )
                self.assertEqual(
                    npu_storage.nbytes(),
                    expected_nbytes,
                )
                self.assertEqual(
                    cpu_storage.nbytes(),
                    npu_storage.nbytes(),
                )

                # UntypedStorage的长度单位也是字节
                self.assertEqual(
                    len(cpu_storage),
                    expected_nbytes,
                )
                self.a

See merge request: Ascend/pytorch!45157
This commit is contained in:
gcw_CHjSLYhf
2026-10-10 17:59:11 +08:00
committed by ascend-robot
parent b651b67466
commit 709b3ea1a7
@@ -0,0 +1,301 @@
# 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.UntypedStorage APIs on NPU.
This file validates torch.UntypedStorage.filename,
torch.UntypedStorage.hpu, torch.UntypedStorage.nbytes,
and torch.UntypedStorage.new on CPU and NPU.
"""
import os
import tempfile
import torch
from torch_npu.testing.testcase import TestCase, run_tests
class TestUntypedStorageAPIs(TestCase):
def test_untyped_storage_filename(self):
# Scenario 1: Regular CPU storage is not associated with a memory-mapped file
cpu_storage = torch.empty(
8,
dtype=torch.float32,
device="cpu",
).untyped_storage()
self.assertEqual(cpu_storage.device.type, "cpu")
self.assertIsNone(cpu_storage.filename)
# Scenarios 2 and 3: Shared and private file-backed storage mappings
with tempfile.TemporaryDirectory() as temp_dir:
file_path = os.path.join(
temp_dir,
"untyped_storage.bin",
)
shared_storage = torch.UntypedStorage.from_file(
file_path,
shared=True,
nbytes=32,
)
self.assertEqual(shared_storage.device.type, "cpu")
self.assertEqual(shared_storage.nbytes(), 32)
self.assertIsInstance(
shared_storage.filename,
str,
)
self.assertEqual(
os.path.realpath(shared_storage.filename),
os.path.realpath(file_path),
)
# Release the shared mapping before creating the private mapping
del shared_storage
private_storage = torch.UntypedStorage.from_file(
file_path,
shared=False,
nbytes=32,
)
self.assertEqual(private_storage.device.type, "cpu")
self.assertEqual(private_storage.nbytes(), 32)
self.assertIsNone(private_storage.filename)
del private_storage
# Scenario 4: NPU storage is not associated with a CPU memory-mapped file
npu_storage = torch.empty(
8,
dtype=torch.float32,
device="npu",
).untyped_storage()
self.assertEqual(npu_storage.device.type, "npu")
self.assertIsNone(npu_storage.filename)
def test_untyped_storage_hpu(self):
npu_storage = torch.empty(
8,
dtype=torch.float32,
device="npu",
).untyped_storage()
self.assertEqual(
npu_storage.device.type,
"npu",
)
# Scenario 5: Call hpu() with default arguments on the torch-npu platform
with self.assertRaisesRegex(
AssertionError,
r"HPU device module is not loaded",
):
npu_storage.hpu()
# Scenario 6: Specify device and non_blocking when calling hpu() on the torch-npu platform
with self.assertRaisesRegex(
AssertionError,
r"HPU device module is not loaded",
):
npu_storage.hpu(
device=1,
non_blocking=True,
)
def test_untyped_storage_nbytes_for_tensor_dtypes(self):
test_cases = [
(torch.float16, 6),
(torch.float32, 6),
(torch.int32, 6),
(torch.int64, 6),
]
# Scenarios 7 to 10: CPU/NPU storage byte counts for different dtypes
for dtype, numel in test_cases:
with self.subTest(dtype=dtype):
cpu_tensor = torch.empty(
numel,
dtype=dtype,
device="cpu",
)
npu_tensor = torch.empty(
numel,
dtype=dtype,
device="npu",
)
cpu_storage = cpu_tensor.untyped_storage()
npu_storage = npu_tensor.untyped_storage()
expected_nbytes = (
numel * cpu_tensor.element_size()
)
self.assertEqual(
cpu_storage.nbytes(),
expected_nbytes,
)
self.assertEqual(
npu_storage.nbytes(),
expected_nbytes,
)
self.assertEqual(
cpu_storage.nbytes(),
npu_storage.nbytes(),
)
# The length of UntypedStorage is also measured in bytes
self.assertEqual(
len(cpu_storage),
expected_nbytes,
)
self.assertEqual(
len(npu_storage),
expected_nbytes,
)
def test_untyped_storage_nbytes_for_direct_storage(self):
# Scenario 11: Directly construct CPU/NPU storage with a specified byte count
for device in ["cpu", "npu"]:
with self.subTest(device=device):
storage = torch.UntypedStorage(
37,
device=device,
)
self.assertEqual(
storage.device.type,
device,
)
self.assertEqual(storage.nbytes(), 37)
self.assertEqual(storage.size(), 37)
self.assertEqual(len(storage), 37)
def test_untyped_storage_nbytes_for_empty_storage(self):
# Scenario 12: Empty NPU storage has zero bytes
empty_npu_storage = torch.UntypedStorage(
0,
device="npu",
)
self.assertEqual(
empty_npu_storage.nbytes(),
0,
)
self.assertEqual(
empty_npu_storage.size(),
0,
)
self.assertEqual(
len(empty_npu_storage),
0,
)
def test_untyped_storage_nbytes_for_tensor_view(self):
# Scenario 13: A tensor view reports the byte count of the entire underlying storage
base_tensor = torch.empty(
(4, 4),
dtype=torch.float32,
device="npu",
)
view_tensor = base_tensor[:, ::2]
base_storage = base_tensor.untyped_storage()
view_storage = view_tensor.untyped_storage()
base_expected_nbytes = (
base_tensor.numel()
* base_tensor.element_size()
)
view_logical_nbytes = (
view_tensor.numel()
* view_tensor.element_size()
)
self.assertEqual(
base_storage.nbytes(),
base_expected_nbytes,
)
self.assertEqual(
view_storage.data_ptr(),
base_storage.data_ptr(),
)
self.assertEqual(
view_storage.nbytes(),
base_storage.nbytes(),
)
self.assertGreater(
view_storage.nbytes(),
view_logical_nbytes,
)
def test_untyped_storage_new_for_cpu_and_npu(self):
# Verify the basic properties of storage returned by new() on CPU and NPU
for device in ["cpu", "npu"]:
with self.subTest(device=device):
source_storage = torch.empty(
8,
dtype=torch.float32,
device=device,
).untyped_storage()
source_nbytes = source_storage.nbytes()
new_storage = source_storage.new()
self.assertIsInstance(
new_storage,
torch.UntypedStorage,
)
self.assertIsNot(
new_storage,
source_storage,
)
self.assertEqual(
new_storage.device.type,
source_storage.device.type,
)
self.assertEqual(
new_storage.nbytes(),
0,
)
self.assertEqual(
len(new_storage),
0,
)
# Calling new() must not modify the original storage
self.assertEqual(
source_storage.nbytes(),
source_nbytes,
)
def test_untyped_storage_new_invalid_argument(self):
# new() does not accept arguments such as size
source_storage = torch.empty(
8,
dtype=torch.float32,
device="npu",
).untyped_storage()
with self.assertRaises(TypeError):
source_storage.new(1)
if __name__ == "__main__":
run_tests()