1 Commits
Author SHA1 Message Date
honorn 4cac9b6f63 [test]Add typedStorage_is{shared|pinned|hpu} API test case
Co-authored-by: honorn<838107180@qq.com>



# message auto-generated for no-merge-commit merge:
!45162 merge TypedStorage_is_shared_pinned_hpu-master into master

[test]Add typedStorage_is{shared|pinned|hpu} API test case

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

# 【合入来源】

[#3780](https://gitcode.com/Ascend/pytorch/issues/3780)
[#3779](https://gitcode.com/Ascend/pytorch/issues/3779)
[#3778](https://gitcode.com/Ascend/pytorch/issues/3778)

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

公开issue:

- `torch.TypedStorage.is_shared`:[【社区任务】8月社区任务第一期-Ascend for PyTorch API 一致性开发(47)](https://gitcode.com/Ascend/pytorch/issues/3780)
- `torch.TypedStorage.is_pinned`:[【社区任务】8月社区任务第一期-Ascend for PyTorch API 一致性开发(46)](https://gitcode.com/Ascend/pytorch/issues/3779)
- `torch.TypedStorage.is_hpu`:[【社区任务】8月社区任务第一期-Ascend for PyTorch API 一致性开发(45)](https://gitcode.com/Ascend/pytorch/issues/3778)

# 一. API 功能说明:

- `torch.TypedStorage.is_shared()` :判断当前 Storage 是否位于共享内存中。
- `torch.TypedStorage.is_pinned()`:判断一个 CPU Storage 是否为指定加速设备分配的页锁定内存,也叫 Pinned Memory。
- `torch.TypedStorage.is_hpu()`:判断 Storage 是否位于 HPU 设备上。HPU 是 Habana Processing Unit,主要指 Intel Habana Gaudi 系列加速器。

| API | 接口性质 | 是否与设备相关 | torch-npu 测试建议 |
|---|---|---|---|
| `torch.TypedStorage.is_shared` | Python 包装接口,实际查询底层 `UntypedStorage` | 是,依赖底层存储及共享内存实现 | 建议补充 NPU 冒烟测试 |
| `torch.TypedStorage.is_pinned` | Python 包装接口,实际查询设备的固定内存分配器 | 强相关 | 必须补充 NPU 用例 |
| `torch.TypedStorage.is_hpu` | Python 属性,比较 `device.type == "hpu"` | 仅查询设备元数据 | 无需专门适配,但可补充 NPU 返回 `False` 的测试 |

**注意** `HPU` 指 `Habana Gaudi HPU`

PyTorch 2.7 中三者的实现分别是:

```python
def is_shared(self):
    _warn_typed_storage_removal()
    return self._is_shared()

def _is_shared(self):
    return self._untyped_storage.is_shared()


def is_pinned(self, device="cuda"):
    _warn_typed_storage_removal()
    return self._untyped_storage.is_pinned(device)


@property
def is_hpu(self):
    _warn_typed_storage_removal()
    return self._untyped_storage.device.type == "hpu"
```

可以看到,`is_shared()` 和 `is_pinned()` 都会继续调用底层 `UntypedStorage`;`is_hpu()` 则是简单的 Python 设备类型判断。


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

| API | 上游检查结果 | NPU 覆盖缺口 |
|---|---|---|
| `TypedStorage.is_shared()` | `test_storage_meta_errors` 对 meta TypedStorage 断言 `is_shared() == False` | 没有覆盖 NPU |
| `TypedStorage.is_pinned()` | 核心 `test_torch.py` 中未发现该方法的独立正反例;CUDA 测试包含 Tensor 层固定内存测试 | 没有检查 `device="npu"` 及 NPU pinned allocator |
| `TypedStorage.is_hpu` | 核心 Storage 测试中未发现独立断言 | 没有验证 NPU Storage 必须返回 `False` |

因此需要补充这三个API的测试用例,这三个API可以直接放到一个完整的测试文件中进行测试。

# 三. 资料情况检查:

- `torch.TypedStorage.is_shared`
- `torch.TypedStorage.is_pinned`
- `torch.TypedStorage.is_hpu`

这些API的资料补充在各个分支都存在,但是 `torch.TypedStorage.is_shared` 和`torch.TypedStorage.is_pinned`对A5芯片的支持程度描述有误,需要进行资料修改,`torch.TypedStorage.is_hpu`由于与hpu硬件相关,因此都不支持,资料补充正确无误,结果如下截图所示。

![image.png](https://raw.gitcode.com/user-images/assets/7404318/e7b7de04-f9d6-446f-ac6e-7982ca1dd740/image.png 'image.png')
![image.png](https://raw.gitcode.com/user-images/assets/7404318/2eb2cb32-745e-490c-bea1-1cf47533d8d9/image.png 'image.png')
![image.png](https://raw.gitcode.com/user-images/assets/7404318/d5a39808-6369-4635-b90f-a2adaeda84a5/image.png 'image.png')

# 四. API功能性验证

测试核心代码

```python
class TestTypedStorageAPIs(TestCase):

    @staticmethod
    def _get_typed_storage(tensor):
        return tensor.storage()

    def test_typed_storage_is_shared_for_cpu(self):
        cpu_tensor = torch.arange(
            8,
            dtype=torch.float32,
            device="cpu",
        )
        expected_tensor = cpu_tensor.clone()
        cpu_storage = self._get_typed_storage(cpu_tensor)

        self.assertIsInstance(
            cpu_storage,
            torch.TypedStorage,
        )
        self.assertEqual(
            cpu_storage.device.type,
            "cpu",
        )

        # 场景1:普通CPU TypedStorage不在共享内存中
        self.assertFalse(cpu_storage.is_shared())
        self.assertEqual(
            cpu_storage.is_shared(),
            cpu_tensor.untyped_storage().is_shared(),
        )

        # 场景2:CPU TypedStorage移动到共享内存
        returned_storage = cpu_storage.share_memory_()

        self.assertIs(
            returned_storage,
            cpu_storage,
        )
        self.assertTrue(cpu_storage.is_shared())
        self.assertTrue(cpu_tensor.is_shared())
        self.assertTrue(
            cpu_tensor.untyped_storage().is_shared()
        )

        # share_memory_不能改变Storage中的数据
        self.assertEqual(
            cpu_tensor,
            expected_tensor,
        )

    def test_typed_storage_is_shared_for_tensor_view(self):
        base_tensor = torch.arange(
            16,
            dtype=torch.float32,
            device="cpu",
        )
        view_tensor = base_tensor[::2]

        base_storage = self._get_typed_storage(
            base_tensor
        )
        view_storage = self._get_typed_storage(
            view_tensor
        )

        # 场景3:Base Tensor和View共享同一底层Storage
        self.assertEqual(
            base_storage.data_ptr(),
            view_storage.data_ptr(),
        )
        self.assertFalse(base_storage.is_shared())
        self.assertFalse(view_storage.is_shared())

        base_storage.share_memory_()

        self.assertTrue(base_storage.is_shared())
        self.assertTrue(view_storage.is_shared())
        self.assertTrue(base_tensor.is_shared())
        self.assertTrue(view_tensor.is_shared())
        self.assertEqual(
            base_storage.data_ptr(),
            view_storage.data_ptr(),
        )

    def test_typed_storage_is_shared_for_npu(self):
        npu_tensor = torch.empty(
            16,
            dtype=torch.float32,
            device="npu",
        )
        npu_storage = self._get_typed_storage(
            npu_tensor
        )

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

        is_shared_before = npu_storage.is_shared()
        data_ptr_before = npu_storage.data_ptr()
        nbytes_before = npu_storage.nbytes()

        self.assertIsInstance(
            is_shared_before,
            bool,
        )
        self.assertEqual(
            is_shared_before,
            npu_tensor.untyped_storage().is_shared(),
        )

        # 场景4:NPU/PrivateUse1 Storage不迁移到POSIX共享内存。
        #
        # 不硬编码NPU is_shared()为True或False,是因为不同PyTorch
        # 版本可能调整非CPU设备的共享状态定义;TypedStorage必须
        # 与底层UntypedStorage一致,并且share_memory_应为no-op。
        returned_storage = npu_storage.share_memory_()
        is_shared_after = npu_storage.is_shared()

        self.assertIs(
            returned_storage,
            npu_storage,
        )
        self.assertEqual(
            is_shared_after,
            is_shared_before,
        )
        self.assertEqual(
            is_shared_after,
            npu_tensor.untyped_storage().is_shared(),
        )
        self.assertEqual(
            npu_storage.data_ptr(),
            data_ptr_before,
        )
        self.assertEqual(
            npu_storage.nbytes(),
            nbytes_before,
        )

    def test_typed_storage_is_pinned_for_normal_storage(self):
        test_dtypes = [
            torch.float16,
            torch.float32,
            torch.int32,
            torch.int64,
        ]

        # 场景5:普通CPU/NPU TypedStorage均不是NPU pinned memory
        for device in ["cpu", "npu"]:
            for dtype in test_dtypes:
                with self.subTest(
                    device=device,
                    dtype=dtype,
                ):
                    tensor = torch.empty(
                        16,
                        dtype=dtype,
                        device=device,
                    )
                    storage = self._get_typed_storage(
                        tensor
                    )

                    result_by_string = storage.is_pinned(
                        device="npu"
                    )
                    result_by_device = storage.is_pinned(
                        device=torch.device("npu")
                    )
                    untyped_result = (
                        tensor.untyped_storage().is_pinned(
                            device="npu"
                        )
                    )

                    self.assertIsInstance(
                        result_by_string,
                        bool,
                    )
                    self.assertFalse(result_by_string)
                    self.assertFalse(result_by_device)
                    self.assertEqual(
                        result_by_string,
                        result_by_device,
                    )
                    self.assertEqual(
                        result_by_string,
                        untyped_result,
                    )

    def test_typed_storage_is_pinned_for_pinned_cpu(self):
        test_dtypes = [
            torch.float16,
            torch.float32,
            torch.int32,
            torch.int64,
        ]

        # 场景6:CPU TypedStorage转换为NPU pinned memory
        for dtype in test_dtypes:
            with self.subTest(dtype=dtype):
                source_tensor = torch.arange(
                    1,
                    9,
                    dtype=dtype,
                    device="cpu",
                )
                source_storage = (
                    self._get_typed_storage(
                        source_tensor
                    )
                )
                source_values = (
                    source_storage.tolist()
                )

                self.assertFalse(
                    source_storage.is_pinned(
                        device="npu"
                    )
                )

                pinned_storage = (
                    source_storage.pin_memory(
                        device="npu"
                    )
                )

                self.assertIsInstance(
                    pinned_storage,
                    torch.TypedStorage,
                )
                self.assertIsNot(
                    pinned_storage,
                    source_storage,
                )
                self.assertEqual(
                    pinned_storage.device.type,
                    "cpu",
                )
     

See merge request: Ascend/pytorch!45162
2026-10-10 17:40:43 +08:00