Co-authored-by: Jwerr<19166910919@163.com> # message auto-generated for no-merge-commit merge: !35323 merge test-StorageWriter-api-master into master test(distributed/checkpoint): Add StorageWriter storage_meta API tests Created-by: Jwerr Commit-by: Jwerr Merged-by: ascend-robot Description: <!-- PR描述模板更新日期:20260203 --> # 【合入来源】 关联 Issue:#1895 PyTorch 社区缺少对 `torch.distributed.checkpoint.StorageWriter.storage_meta`(实际类路径:`torch.distributed.checkpoint.storage.StorageWriter.storage_meta`)的直接 API 级测试,且未覆盖 NPU。本 PR 在 `test/distributed/checkpoint/test_StorageWriter_api.py` 补齐单卡 + 多卡 NPU 用例。 - [ ] 需求 - [x] 问题单 - [ ] issue/工单 - [ ] 重构优化 - [ ] 资料更新 # 【修改方案】 一、API功能说明 ``` torch.distributed.checkpoint.StorageWriter.storage_meta是 torch.distributed.checkpoint.StorageWriter 基类下的可选钩子,父类默认返回 None,子类可按需覆写并返回 torch.distributed.checkpoint.metadata.StorageMeta。 torch.distributed.checkpoint.metadata.StorageMeta 用于描述 checkpoint 存储元信息,包含 checkpoint_id、save_id、load_id、modules 等字段。其中 checkpoint_id 表示存储位置 ID,save_id 表示本次保存 UUID,modules 默认为空列表。 在保存流程中,writer.storage_meta() 返回的 torch.distributed.checkpoint.metadata.StorageMeta 会通过 torch.distributed.checkpoint.save 透传给 torch.distributed.checkpoint.planner.SavePlanner.set_up_planner(state_dict, storage_meta=...),用于保存规划阶段感知 writer 侧元数据。 ``` 二、测试文件 test_StorageWriter_api.py 验证内容 ``` 1. 基类默认行为验证 定义 _MinimalStorageWriter 作为 torch.distributed.checkpoint.storage.StorageWriter 最小实现类,仅实现抽象方法,不覆写 torch.distributed.checkpoint.storage.StorageWriter.storage_meta,验证: * torch.distributed.checkpoint.storage.StorageWriter.storage_meta 可调用; * 父类默认 storage_meta() 返回 None。 2. FileSystemWriter 覆写行为验证 通过 torch.distributed.checkpoint.FileSystemWriter 验证真实 writer 的 storage_meta 返回值: * 返回值类型为 torch.distributed.checkpoint.metadata.StorageMeta; * checkpoint_id 与初始化 checkpoint 目录一致; * save_id 为合法 UUID; * modules 默认为空列表; * reset(checkpoint_id=new_dir) 后 checkpoint_id 更新,save_id 变化。 3. 保存流程验证 通过 torch.distributed.checkpoint.save 验证 storage_meta 在实际保存流程中的可用性: * 使用 NPU Tensor 执行 torch.distributed.checkpoint.save(..., no_dist=True) 后,writer.storage_meta() 仍返回合法 torch.distributed.checkpoint.metadata.StorageMeta; * 空 state_dict 保存后,writer.storage_meta() 仍保持有效; * save -> reset -> save 后 save_id 发生变化,验证 writer 生命周期更新有效。 4. SavePlanner 透传验证 定义 _CapturingPlanner 继承 torch.distributed.checkpoint.default_planner.DefaultSavePlanner,在 set_up_planner 中捕获 storage_meta,验证: * torch.distributed.checkpoint.save 会将 writer.storage_meta() 返回值透传给 torch.distributed.checkpoint.planner.SavePlanner.set_up_planner; * planner 捕获到的 checkpoint_id、save_id 与 writer.storage_meta() 保持一致。 5. 多 NPU 分布式验证 TestStorageMetaDistributed 继承 torch.testing._internal.distributed._shard.sharded_tensor.ShardedTensorTestBase,通过 torch_npu.testing.common_distributed.with_comms 初始化 HCCL 进程组,并通过 torch_npu.testing.common_distributed.skipIfUnsupportMultiNPU(2) 限定 2 卡 NPU 环境运行,验证: * rank 0 创建共享 checkpoint 目录,并通过 torch.distributed.broadcast_object_list 广播给其他 rank; * 分布式 torch.distributed.checkpoint.save 后,各 rank 的 checkpoint_id 通过 torch.distributed.all_gather_object 收集并保持一致; * 分布式 save -> reset -> save 后 save_id 发生变化; * 分布式保存后 writer.storage_meta() 仍返回 torch.distributed.checkpoint.metadata.StorageMeta,且 save_id 为合法 UUID。 ``` 三、NPU适配 ``` torch.distributed.checkpoint.storage.StorageWriter.storage_meta 和 torch.distributed.checkpoint.metadata.StorageMeta 均属于 Python 层 checkpoint 元数据抽象,不涉及 NPU 算子、NPU kernel、设备内存管理或 HCCL 通信协议本身,因此 API 本身无需针对 NPU 修改。 本 PR 主要在测试用例层面验证 NPU 场景可用性: * 单卡用例继承 torch_npu.testing.testcase.TestCase,使用 torch.Tensor.npu() 构造 NPU Tensor 后进入 torch.distributed.checkpoint.save 流程; * 多卡用例通过 torch_npu.testing.common_distributed.with_comms 初始化 HCCL 进程组; * 通过 torch_npu.testing.common_distributed.skipIfUnsupportMultiNPU(2) 限定多 NPU 环境,避免设备数量不足时误失败; * 通过 torch.distributed.broadcast_object_list 保证各 rank 使用同一 checkpoint 目录; * 通过 torch.distributed.all_gather_object 验证 checkpoint_id 跨 rank 一致; * 测试结束后通过 destroy_pg 释放分布式进程组资源。 ``` # 【资料变更】 不涉及 # 【接口变更】 不涉及 # 【功能验证】 在2.7.1 2.9.0 2.10.0 2.11.0 2.12.0以及master版本上执行该用例,均通过,本分支对应master日志如下: ``` I0511 13:42:19.353000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 0 with pid 130263 I0511 13:42:19.355000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 1 with pid 130264 I0511 13:42:30.185000 130263 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 0 skipping test test_storage_meta_checkpoint_id_consistency_across_ranks for following reason: Multi-NPU 2 condition not satisfied I0511 13:42:30.322000 130264 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 1 skipping test test_storage_meta_checkpoint_id_consistency_across_ranks for following reason: Multi-NPU 2 condition not satisfied sI0511 13:42:33.087000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 0 with pid 130483 I0511 13:42:33.088000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 1 with pid 130484 I0511 13:42:43.797000 130484 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 1 skipping test test_storage_meta_returned_in_distributed_save for following reason: Multi-NPU 2 condition not satisfied I0511 13:42:43.938000 130483 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 0 skipping test test_storage_meta_returned_in_distributed_save for following reason: Multi-NPU 2 condition not satisfied sI0511 13:42:46.624000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 0 with pid 130675 I0511 13:42:46.625000 130119 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:895] Started process 1 with pid 130676 I0511 13:42:57.504000 130675 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 0 skipping test test_storage_meta_save_id_changes_after_reset_distributed for following reason: Multi-NPU 2 condition not satisfied I0511 13:42:57.625000 130676 pytorch-2.12.0-env/lib/python3.10/site-packages/torch/testing/_internal/common_distributed.py:973] Process 1 skipping test test_storage_meta_save_id_changes_after_reset_distributed for following reason: Multi-NPU 2 condition not satisfied s.../root/work/pytorch-2.12.0-env/lib/python3.10/site-packages/torch/distributed/checkpoint/utils.py:485: UserWarning: torch.distributed is disabled, unavailable or uninitialized, assuming the intent is to save in a single process. return func(*args, **kwargs) .[W511 13:43:04.696461912 NPUCachingAllocator.cpp:199] Warning: The current CANN and Soc versions require processing for 32 padding size, with memory allocation. (function operator()) ... ---------------------------------------------------------------------- Ran 10 tests in 45.440s OK (skipped=3) ``` # 【CheckList】 > PR提交人对以下CheckList自检项进行全量自检,自检通过或不涉及,均修改 [ ] 为 [x] - [x] 代码注释完备,正确记录错误日志 - [x] 代码实现进行了返回值、空指针等校验 - [x] PR标题正确使用类型标签,如:feat、fix、refactor、docs、test等 - [x] PR持续集成流水线(CI)执行通过,代码检查无异常 See merge request: Ascend/pytorch!35323
279 lines
11 KiB
Python
279 lines
11 KiB
Python
"""
|
|
PyTorch community lacks some torch.distributed.checkpoint.StorageWriter APIs validation, so this file is added.
|
|
|
|
This file validates the following apis:
|
|
torch.distributed.checkpoint.StorageWriter.storage_meta
|
|
(extendable)
|
|
"""
|
|
|
|
import os
|
|
import tempfile
|
|
import uuid
|
|
|
|
import torch
|
|
import torch.distributed as dist
|
|
import torch.distributed.checkpoint as dcp
|
|
from torch.distributed.checkpoint import FileSystemWriter
|
|
from torch.distributed.checkpoint.default_planner import DefaultSavePlanner
|
|
from torch.distributed.checkpoint.metadata import Metadata, StorageMeta
|
|
from torch.distributed.checkpoint.storage import StorageWriter, WriteResult
|
|
from torch.futures import Future
|
|
from torch.testing._internal.distributed._shard.sharded_tensor import (
|
|
ShardedTensorTestBase,
|
|
)
|
|
|
|
from torch_npu.testing.common_distributed import skipIfUnsupportMultiNPU, with_comms
|
|
from torch_npu.testing.testcase import run_tests, TestCase
|
|
|
|
|
|
device_type = acc.type if (acc := torch.accelerator.current_accelerator()) else "cpu"
|
|
|
|
|
|
class _MinimalStorageWriter(StorageWriter):
|
|
"""Minimal subclass implementing only abstractmethods to exercise the base
|
|
default storage_meta() which returns None.
|
|
"""
|
|
|
|
def reset(self, checkpoint_id: str | os.PathLike | None = None) -> None:
|
|
return None
|
|
|
|
def set_up_storage_writer(self, is_coordinator: bool) -> None:
|
|
return None
|
|
|
|
def prepare_local_plan(self, plan):
|
|
return plan
|
|
|
|
def prepare_global_plan(self, plans):
|
|
return plans
|
|
|
|
def write_data(self, plan, planner) -> Future[list[WriteResult]]:
|
|
fut: Future[list[WriteResult]] = Future()
|
|
fut.set_result([])
|
|
return fut
|
|
|
|
def finish(self, metadata: Metadata, results: list[list[WriteResult]]) -> None:
|
|
return None
|
|
|
|
@classmethod
|
|
def validate_checkpoint_id(cls, checkpoint_id: str | os.PathLike) -> bool:
|
|
return True
|
|
|
|
|
|
class TestStorageMetaSingleProcess(TestCase):
|
|
"""Single-process contract validation: base default, FileSystemWriter field
|
|
semantics, post-save validity, empty-state-dict boundary, reset lifecycle,
|
|
and SavePlanner propagation.
|
|
"""
|
|
|
|
# --------------------------------------------------------------------- #
|
|
# Base-class default #
|
|
# --------------------------------------------------------------------- #
|
|
def test_base_storage_meta_callable_and_returns_none(self):
|
|
self.assertTrue(callable(StorageWriter.storage_meta))
|
|
writer = _MinimalStorageWriter()
|
|
self.assertIsNone(writer.storage_meta())
|
|
|
|
# --------------------------------------------------------------------- #
|
|
# FileSystemWriter field semantics #
|
|
# --------------------------------------------------------------------- #
|
|
def _assert_storage_meta_fields(self, writer: FileSystemWriter, expected_dir: str):
|
|
meta = writer.storage_meta()
|
|
self.assertIsInstance(meta, StorageMeta)
|
|
self.assertEqual(str(meta.checkpoint_id), expected_dir)
|
|
self.assertIsInstance(meta.modules, list)
|
|
self.assertEqual(meta.modules, [])
|
|
self.assertIsInstance(uuid.UUID(meta.save_id), uuid.UUID)
|
|
|
|
def test_filesystem_writer_storage_meta_fields(self):
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
writer = FileSystemWriter(temp_dir)
|
|
self._assert_storage_meta_fields(writer, temp_dir)
|
|
|
|
def test_storage_meta_after_reset(self):
|
|
with tempfile.TemporaryDirectory() as d1, tempfile.TemporaryDirectory() as d2:
|
|
writer = FileSystemWriter(d1)
|
|
save_id_before = writer.storage_meta().save_id
|
|
|
|
writer.reset(checkpoint_id=d2)
|
|
meta_after = writer.storage_meta()
|
|
|
|
self.assertEqual(str(meta_after.checkpoint_id), d2)
|
|
self.assertNotEqual(save_id_before, meta_after.save_id)
|
|
|
|
# --------------------------------------------------------------------- #
|
|
# Save integration #
|
|
# --------------------------------------------------------------------- #
|
|
def test_storage_meta_valid_after_save(self):
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
state_dict = {"weight": torch.randn(4, 4).to(device_type)}
|
|
writer = FileSystemWriter(temp_dir)
|
|
dcp.save(state_dict, storage_writer=writer, no_dist=True)
|
|
self._assert_storage_meta_fields(writer, temp_dir)
|
|
|
|
def test_storage_meta_empty_state_dict(self):
|
|
"""Boundary: writer.storage_meta() must remain valid even when no tensors
|
|
are written (empty state_dict).
|
|
"""
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
writer = FileSystemWriter(temp_dir)
|
|
dcp.save({}, storage_writer=writer, no_dist=True)
|
|
self._assert_storage_meta_fields(writer, temp_dir)
|
|
|
|
def test_storage_meta_reset_between_saves(self):
|
|
"""save -> reset(new dir) -> save: save_id must change to guarantee
|
|
uniqueness across distinct save operations, preventing metadata collisions
|
|
in distributed checkpointing scenarios.
|
|
"""
|
|
with tempfile.TemporaryDirectory() as d1, tempfile.TemporaryDirectory() as d2:
|
|
writer = FileSystemWriter(d1)
|
|
dcp.save(
|
|
{"w": torch.randn(4, 4).to(device_type)},
|
|
storage_writer=writer,
|
|
no_dist=True,
|
|
)
|
|
save_id_1 = writer.storage_meta().save_id
|
|
|
|
writer.reset(checkpoint_id=d2)
|
|
dcp.save(
|
|
{"w": torch.randn(4, 4).to(device_type)},
|
|
storage_writer=writer,
|
|
no_dist=True,
|
|
)
|
|
save_id_2 = writer.storage_meta().save_id
|
|
|
|
self.assertNotEqual(save_id_1, save_id_2)
|
|
|
|
# --------------------------------------------------------------------- #
|
|
# SavePlanner propagation #
|
|
# --------------------------------------------------------------------- #
|
|
def test_storage_meta_passed_to_planner(self):
|
|
captured = {}
|
|
|
|
class _CapturingPlanner(DefaultSavePlanner):
|
|
def set_up_planner(
|
|
self, state_dict, storage_meta=None, is_coordinator=False
|
|
):
|
|
captured["meta"] = storage_meta
|
|
super().set_up_planner(state_dict, storage_meta, is_coordinator)
|
|
|
|
with tempfile.TemporaryDirectory() as temp_dir:
|
|
state_dict = {"w": torch.randn(4, 4).to(device_type)}
|
|
writer = FileSystemWriter(temp_dir)
|
|
expected = writer.storage_meta()
|
|
|
|
dcp.save(
|
|
state_dict,
|
|
storage_writer=writer,
|
|
planner=_CapturingPlanner(),
|
|
no_dist=True,
|
|
)
|
|
|
|
self.assertIsInstance(captured.get("meta"), StorageMeta)
|
|
self.assertEqual(
|
|
str(captured["meta"].checkpoint_id),
|
|
str(expected.checkpoint_id),
|
|
)
|
|
self.assertEqual(captured["meta"].save_id, expected.save_id)
|
|
|
|
|
|
class TestStorageMetaDistributed(ShardedTensorTestBase):
|
|
"""Multi-NPU contract: checkpoint_id must be consistent across ranks,
|
|
save_id must remain unique per writer instance, and storage_meta must be
|
|
obtainable directly from the writer after distributed save.
|
|
|
|
NOTE: We assert writer.storage_meta() rather than Metadata.storage_meta
|
|
because PyTorch 2.9+ leaves the latter None on the no_dist=True path
|
|
(community Issue #177887). The writer-side API contract is the stable
|
|
surface for validation.
|
|
"""
|
|
|
|
def tearDown(self):
|
|
super().tearDown()
|
|
self.destroy_pg()
|
|
|
|
def destroy_pg(self) -> None:
|
|
"""Best-effort cleanup: swallow exceptions to avoid masking the real
|
|
test result when the process group is already in a bad state.
|
|
"""
|
|
if dist.is_initialized():
|
|
dist.barrier()
|
|
dist.destroy_process_group()
|
|
|
|
@property
|
|
def world_size(self) -> int:
|
|
return 2
|
|
|
|
def _shared_temp_dir(self):
|
|
"""Yield a single checkpoint directory visible to all ranks.
|
|
Rank 0 creates the directory and broadcasts its path; all ranks
|
|
synchronize on teardown so rank 0 can safely remove it.
|
|
"""
|
|
|
|
class _SharedTempDirContext:
|
|
def __init__(self):
|
|
self._temp_dir_ctx = None
|
|
self.temp_dir = ""
|
|
|
|
def __enter__(self):
|
|
if dist.get_rank() == 0:
|
|
self._temp_dir_ctx = tempfile.TemporaryDirectory()
|
|
self.temp_dir = self._temp_dir_ctx.__enter__()
|
|
object_list = [self.temp_dir]
|
|
dist.broadcast_object_list(object_list, src=0)
|
|
self.temp_dir = object_list[0]
|
|
return self.temp_dir
|
|
|
|
def __exit__(self, exc_type, exc, tb):
|
|
dist.barrier()
|
|
if dist.get_rank() == 0 and self._temp_dir_ctx is not None:
|
|
self._temp_dir_ctx.__exit__(exc_type, exc, tb)
|
|
return False
|
|
|
|
return _SharedTempDirContext()
|
|
|
|
@skipIfUnsupportMultiNPU(2)
|
|
@with_comms
|
|
def test_storage_meta_checkpoint_id_consistency_across_ranks(self) -> None:
|
|
with self._shared_temp_dir() as temp_dir:
|
|
writer = FileSystemWriter(temp_dir)
|
|
dcp.save({"t": torch.randn(4, 4).to(device_type)}, storage_writer=writer)
|
|
|
|
local_id = str(writer.storage_meta().checkpoint_id)
|
|
gathered: list[str | None] = [None] * dist.get_world_size()
|
|
dist.all_gather_object(gathered, local_id)
|
|
for cid in gathered:
|
|
self.assertEqual(cid, gathered[0])
|
|
|
|
@skipIfUnsupportMultiNPU(2)
|
|
@with_comms
|
|
def test_storage_meta_save_id_changes_after_reset_distributed(self) -> None:
|
|
with self._shared_temp_dir() as temp_dir:
|
|
writer = FileSystemWriter(temp_dir)
|
|
dcp.save({"t": torch.randn(4, 4).to(device_type)}, storage_writer=writer)
|
|
save_id_1 = writer.storage_meta().save_id
|
|
|
|
dist.barrier()
|
|
writer.reset(checkpoint_id=temp_dir)
|
|
dcp.save({"t": torch.randn(4, 4).to(device_type)}, storage_writer=writer)
|
|
save_id_2 = writer.storage_meta().save_id
|
|
|
|
self.assertNotEqual(save_id_1, save_id_2)
|
|
|
|
@skipIfUnsupportMultiNPU(2)
|
|
@with_comms
|
|
def test_storage_meta_returned_in_distributed_save(self) -> None:
|
|
with self._shared_temp_dir() as temp_dir:
|
|
writer = FileSystemWriter(temp_dir)
|
|
dcp.save(
|
|
{f"rank_{dist.get_rank()}": torch.randn(4, 4).to(device_type)},
|
|
storage_writer=writer,
|
|
)
|
|
|
|
meta = writer.storage_meta()
|
|
self.assertIsInstance(meta, StorageMeta)
|
|
self.assertIsInstance(uuid.UUID(meta.save_id), uuid.UUID)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_tests()
|