Files
TorchNPU/test/distributed/checkpoint/test_broadcasting_reader.py
T
xh-zhan e265debdaa test(distributed):add test for validate_checkpoint_id, reset, set_up_storage_reader from BroadcastingTorchSaveReader for master(fixed)
Co-authored-by: xh-zhan<zhanxuhan@sjtu.edu.cn>



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

test(distributed):add test for validate_checkpoint_id, reset, set_up_storage_reader from BroadcastingTorchSaveReader for master(fixed)

Created-by: xh-zhan
Commit-by: xh-zhan
Merged-by: ascend-robot
Description: /kind feature

### What does this PR do / why do we need it:

本次 PR 为 `BroadcastingTorchSaveReader` 类中的三个核心 API 新增了单元测试用例,以确保其在 `torch_npu` 环境下的行为与 PyTorch 原生行为保持一致。

测试用例路径:`test/distributed/checkpoint/test_broadcasting_reader.py`

### API 功能说明:

- **`torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.validate_checkpoint_id`**:纯逻辑 API,用于检查给定的 checkpoint 文件路径是否存在。
- **`torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.reset`**:纯逻辑 API,用于重置 `BroadcastingTorchSaveReader` 实例的 `checkpoint_id` 属性,支持更新为新的路径或 `None`。
- **`torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.set_up_storage_reader`**:用于设置存储读取器的元数据及协调者(coordinator)状态。包含协调者身份校验和 `checkpoint_id` 非空检查。

### 用例完备性说明:

由于Pytorch社区无上述三个API的测试用例,故本次PR新增用例`test_broadcasting_reader.py`。本次提交的测试用例覆盖了以下场景,确保 API 的健壮性:

- `validate_checkpoint_id`:
  - ✅ 存在的文件路径 → 返回 `True`
  - ✅ 不存在的文件路径 → 返回 `False`
- `reset`:
  - ✅ 更新为新路径 → `checkpoint_id` 正确变更
  - ✅ 更新为 `None` → `checkpoint_id` 正确变更为 `None`
- `set_up_storage_reader`:
  - ✅ 正确设置 `is_coordinator` 属性
  - ✅ 协调者 rank 不匹配时抛出 `AssertionError`
  - ✅ `checkpoint_id` 为 `None` 时抛出 `AssertionError`

> 注:测试中使用 `unittest.mock` 模拟 `torch.distributed.get_rank`,以在单进程环境下验证分布式协调者校验逻辑,避免对真实多进程环境的依赖。

### 适配方案:

经分析,这三个 API 均为纯 Python 逻辑,不依赖任何 NPU 特定算子或硬件特性。本次提交 **无需对 API 本身进行任何代码适配**,仅增加单元测试以完成 NPU 环境下的兼容性验证。

### Which issue(s) this PR fixes:

Fixes [#1680](https://gitcode.com/Ascend/pytorch/issues/1680) 

### Related PR
This PR is a follow-up fix to the previously merged [PR #33733](https://gitcode.com/Ascend/pytorch/pull/33733).

### Special notes for your reviewers:

1. **测试文件路径**:`test/distributed/checkpoint/test_broadcasting_reader.py`
2. **本地验证结果**:所有测试用例已在昇腾 NPU 环境下成功运行,且本地2.6.0,2.7.1,2.8.0,2.9.0,2.10.0,2.11.0版本下都运行成功,输出如下:
Ran 7 tests in 0.011s
OK
3. **命名规范**:测试文件命名符合 `torch-npu` 仓库规范(`test_` 开头 + 核心关键词),文件内添加了完整 API 名称和测试维度注释,便于后续检索和维护。
4. **需合入的分支**:本PR合入`master` 分支。
5. **备注**:本PR在原有基础上,将文件路径改为相对路径,并确保tensor在npu环境下执行。

See merge request: Ascend/pytorch!33996
2026-04-21 09:57:22 +08:00

112 lines
4.9 KiB
Python

"""
Add validation cases for BroadcastingTorchSaveReader APIs:
1. pytorch/test/distributed/checkpoint/test_format_utils.py from PyTorch community lacks sufficient API validations, so this file is added.
2. This file validates the following APIs:
torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.reset
torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.set_up_storage_reader
torch.distributed.checkpoint.format_utils.BroadcastingTorchSaveReader.validate_checkpoint_id
(extendable)
"""
import os
import tempfile
from unittest.mock import patch
import torch
import torch_npu
from torch.distributed.checkpoint.format_utils import BroadcastingTorchSaveReader
from torch.testing._internal.common_utils import TestCase, run_tests
class TestBroadcastingTorchSaveReader(TestCase):
"""Independent unit tests for pure logic APIs of BroadcastingTorchSaveReader.
This test uses mocks for distributed functions, allowing full validation
of all APIs without starting a process group.
"""
def setUp(self):
"""Runs before each test method: creates a valid temporary checkpoint file."""
fd, self.temp_file_path = tempfile.mkstemp(suffix=".pt", dir=".")
os.close(fd)
tensor = torch.tensor([1, 2, 3], device="npu")
torch.save({"dummy": tensor}, self.temp_file_path)
self.valid_checkpoint_id = self.temp_file_path
def tearDown(self):
"""Runs after each test method: deletes the temporary file to clean up."""
if os.path.exists(self.valid_checkpoint_id):
os.unlink(self.valid_checkpoint_id)
self.assertFalse(
os.path.exists(self.valid_checkpoint_id),
f"tearDown failed to cleanup file: {self.valid_checkpoint_id}"
)
def test_validate_checkpoint_id_valid_path(self):
"""Passing a path to an existing file should return True."""
result = BroadcastingTorchSaveReader.validate_checkpoint_id(self.valid_checkpoint_id)
self.assertTrue(result, "valid checkpoint file should return True")
def test_validate_checkpoint_id_invalid_path(self):
"""Passing a path to a non-existent file should return False."""
non_existent = "does_not_exist_12345.pt"
result = BroadcastingTorchSaveReader.validate_checkpoint_id(non_existent)
self.assertFalse(result, "non-existent file should return False")
def test_reset_updates_checkpoint_id(self):
"""Verify that the reset method correctly updates the internal checkpoint_id."""
reader = BroadcastingTorchSaveReader(checkpoint_id="old_path.pt")
new_path = "new_path.pt"
reader.reset(new_path)
self.assertEqual(reader.checkpoint_id, new_path, "reset should update checkpoint_id")
def test_reset_none(self):
"""Verify that reset with None correctly sets checkpoint_id to None."""
reader = BroadcastingTorchSaveReader(checkpoint_id="abc")
reader.reset(None)
self.assertIsNone(reader.checkpoint_id)
class DummyMetadata:
"""Placeholder Metadata class used for testing."""
pass
@patch("torch.distributed.get_rank")
def test_set_up_storage_reader_sets_coordinator_flag(self, mock_get_rank):
"""Verify that set_up_storage_reader correctly sets the is_coordinator attribute."""
mock_get_rank.return_value = 0
reader = BroadcastingTorchSaveReader(checkpoint_id=self.valid_checkpoint_id)
metadata = self.DummyMetadata()
reader.set_up_storage_reader(metadata, is_coordinator=True)
self.assertTrue(reader.is_coordinator, "is_coordinator should be set to True")
reader.set_up_storage_reader(metadata, is_coordinator=False)
self.assertFalse(reader.is_coordinator, "is_coordinator should be set to False")
@patch("torch.distributed.get_rank")
def test_set_up_storage_reader_coordinator_rank_mismatch_raises(self, mock_get_rank):
"""Verify that an AssertionError is raised when is_coordinator=True
but the current rank does not match coordinator_rank."""
mock_get_rank.return_value = 1
reader = BroadcastingTorchSaveReader(checkpoint_id=self.valid_checkpoint_id, coordinator_rank=0)
metadata = self.DummyMetadata()
with self.assertRaises(AssertionError, msg="Should raise AssertionError when coordinator rank mismatches"):
reader.set_up_storage_reader(metadata, is_coordinator=True)
def test_set_up_storage_reader_requires_checkpoint_id(self):
"""Verify that an AssertionError is raised when checkpoint_id is None."""
reader = BroadcastingTorchSaveReader(checkpoint_id=None)
metadata = self.DummyMetadata()
with patch("torch.distributed.get_rank", return_value=0):
with self.assertRaises(AssertionError, msg="checkpoint_id not set should raise AssertionError"):
reader.set_up_storage_reader(metadata, is_coordinator=True)
if __name__ == "__main__":
run_tests()