Files
gcw_CHjSLYhf 709b3ea1a7 [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
2026-10-10 17:59:11 +08:00
..
2026-05-21 09:10:05 +08:00
2026-09-26 21:50:32 +08:00
2026-04-15 17:17:35 +08:00
2026-04-15 17:17:35 +08:00
2026-04-15 17:17:35 +08:00
2026-08-12 17:03:14 +08:00
2026-10-10 11:07:11 +08:00
2026-07-13 20:24:39 +08:00
2024-03-26 11:49:00 +00:00
2023-11-30 12:36:33 +00:00
2026-07-07 08:45:04 +08:00
2025-06-30 11:34:23 +00:00
2026-04-15 17:17:35 +08:00
2023-11-30 12:36:33 +00:00
2024-03-26 08:03:30 +00:00
2026-06-30 14:57:51 +08:00
2024-07-02 11:08:55 +00:00
2025-12-05 09:21:37 +08:00

简介

test目录为PTA相关的测试用例。

安装依赖

pip3 install -r requirements.txt

补全脚本

该操作需要联网

cd test
bash get_synchronized_files.sh

通过以上操作,会自动补齐testfiles_synchronized.txt和testfolder_synchronized.txt中的文件或文件夹。

跳过失败用例

export DISABLED_TESTS_FILE=./unsupported_test_cases/.pytorch-disabled-tests.json

如果不是在test目录下运行测试用例,需要传入.pytorch-disabled-tests.json的绝对路径。

执行方式

执行单个测试脚本

运行以test开头的文件。以test_autocast.py为例:

方式一:

python test_autocast.py

方式二:

python run_test.py -i test_autocast

说明:部分以test开头的脚本不是直接运行的脚本,比如jit中的测试脚本是通过test_jit.py执行的。

执行具体的用例

通过-k参数传入具体的用例名。以test_autocast.py为例:

方式一:

python test_autocast.py -v -k test_autocast_nn_fp32

方式二:

python run_test.py -v -i test_autocast -- -k test_autocast_nn_fp32

执行全量UT的方式

# 进入到test目录的上一级
cd ../

运行非分布式全量用例:

python ci/access_control_test.py --all

运行分布式全量用例:

python ci/access_control_test.py --distributed

FAQ

  1. 报错:"dictionary changed size during iteration".

    如果python 环境是3.8.1版本,报错在unitest/case.py中,可考虑是sys.modules被修改导致的。第三方包可能会有对sys.modules的修改,比如beartype。 此问题为python 3.8.1版本/3.9.0版本的已知bug,可按照 https://github.com/python/cpython/issues/73806 中修改方式修改,将 for v in sys.modules.values() 改为 for v in list(sys.modules.values())

    可用于复现问题的用例: python test_jit.py -v -k test_annotated_empty_dict

  2. test_public_bindings.py 用例的功能

    该用例是为了校验接口的公开规范性,如果该用例报错,请确认报错的接口是否要公开,并按照报错的提示进行修改。