Merged
[feat]: 为本地 FileSystemReader 增加可选 mmap 加载 #1074
[feat]: 为本地 FileSystemReader 增加可选 mmap 加载 #1074
Merged
AWWOLFAdd on Oct 22
Total: 4 files changed+222-0
@@ -212,6 +212,73 @@ def test_dcp_load_verifies_manifest_before_upstream_load():
212 assert events == ["verify manifest", "load checkpoint"]212 assert events == ["verify manifest", "load checkpoint"]
213 213 
214 214 
215+def _run_isolated_patch(script, *args):
216+ import subprocess
217+ 
218+ module_path = (
219+ Path(__file__).resolve().parents[5]
220+ / "torchtitan_npu/patches/torchtitan/distributed/checkpoint/filesystem.py"
221+ )
222+ subprocess.run([sys.executable, "-c", script, str(module_path), *map(str, args)], check=True)
223+ 
224+ 
225+def test_bounded_reader_does_not_read_past_blob():
226+ script = """
227+import importlib.util
228+import io
229+import sys
230+ 
231+spec = importlib.util.spec_from_file_location("dcp_mmap_filesystem_under_test", sys.argv[1])
232+module = importlib.util.module_from_spec(spec)
233+spec.loader.exec_module(module)
234+base = io.BytesIO(b"prefix" + b"blob" + b"trailing")
235+view = module._BoundedReader(base, 6, 4)
236+ 
237+view.seek(0)
238+assert view.read() == b"blob"
239+ 
240+view.seek(5)
241+assert view.read() == b""
242+ 
243+buffer = bytearray(8)
244+assert view.readinto(buffer) == 0
245+"""
246+ _run_isolated_patch(script)
247+ 
248+ 
249+def test_filesystem_reader_mmap_loads_local_dcp(tmp_path):
250+ script = """
251+import importlib.util
252+import sys
253+from pathlib import Path
254+ 
255+import torch
256+import torch.distributed.checkpoint as dcp
257+ 
258+spec = importlib.util.spec_from_file_location("dcp_mmap_filesystem_under_test", sys.argv[1])
259+module = importlib.util.module_from_spec(spec)
260+spec.loader.exec_module(module)
261+source = {
262+ "weight": torch.arange(4096, dtype=torch.float32).reshape(64, 64),
263+ "bias": torch.arange(257, dtype=torch.bfloat16),
264+}
265+checkpoint_id = Path(sys.argv[2])
266+dcp.save(source, checkpoint_id=checkpoint_id)
267+target = {
268+ "weight": torch.empty_like(source["weight"]),
269+ "bias": torch.empty_like(source["bias"]),
270+}
271+reader = dcp.FileSystemReader(checkpoint_id, mmap=True)
272+assert reader.mmap is True
273+dcp.load(target, storage_reader=reader)
274+torch.testing.assert_close(target["weight"], source["weight"])
275+torch.testing.assert_close(target["bias"], source["bias"])
276+del reader
277+del target
278+"""
279+ _run_isolated_patch(script, tmp_path / "checkpoint")
280+ 
281+ 
215def test_checkpoint_manager_uses_synchronous_writer():282def test_checkpoint_manager_uses_synchronous_writer():
216 manager = object.__new__(product_checkpoint.CheckpointManager)283 manager = object.__new__(product_checkpoint.CheckpointManager)
217 state_dict = {"state": torch.tensor(1)}284 state_dict = {"state": torch.tensor(1)}
@@ -11,6 +11,7 @@
11- https://github.com/pytorch/torchtitan/pull/473411- https://github.com/pytorch/torchtitan/pull/4734
12- https://github.com/pytorch/torchtitan/pull/470812- https://github.com/pytorch/torchtitan/pull/4708
13- https://github.com/pytorch/torchtitan/pull/476313- https://github.com/pytorch/torchtitan/pull/4763
14+- https://github.com/pytorch/pytorch/pull/201621
14-->15-->
15 16 
16# TorchTitan 临时补丁17# TorchTitan 临时补丁
@@ -23,6 +24,7 @@
23 24 
24 ```python25 ```python
25 # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/NNNN26 # Pending upstream PR: https://github.com/pytorch/torchtitan/pull/NNNN
27+ # Pending upstream PR: https://github.com/pytorch/pytorch/pull/NNNN
26 ```28 ```
27 29 
28- 模块 docstring 需说明补丁内容,并以 "Remove this module after the TorchTitan dependency includes the PR." 结尾。30- 模块 docstring 需说明补丁内容,并以 "Remove this module after the TorchTitan dependency includes the PR." 结尾。
@@ -56,6 +58,7 @@ grep -L "Pending upstream PR: https://github.com/pytorch/torchtitan/pull/" \
56| [#4664](https://github.com/pytorch/torchtitan/pull/4664) | 为每个 FSDP 参数组注册 TorchFT 梯度平均 hook,对应 `experiments/torchft/manager.py` |58| [#4664](https://github.com/pytorch/torchtitan/pull/4664) | 为每个 FSDP 参数组注册 TorchFT 梯度平均 hook,对应 `experiments/torchft/manager.py` |
57| [#4708](https://github.com/pytorch/torchtitan/pull/4708) | 修复 functionalize_recompute_mutations_pass 和 EpOverlap 的冲突 |59| [#4708](https://github.com/pytorch/torchtitan/pull/4708) | 修复 functionalize_recompute_mutations_pass 和 EpOverlap 的冲突 |
58| [#4763](https://github.com/pytorch/torchtitan/pull/4763) | 向 GraphTrainer graph pass 提供运行时上下文,用于 auto-overlap 调度时整图 profiling |60| [#4763](https://github.com/pytorch/torchtitan/pull/4763) | 向 GraphTrainer graph pass 提供运行时上下文,用于 auto-overlap 调度时整图 profiling |
61+| [#201621](https://github.com/pytorch/pytorch/pull/201621) | 为本地 FileSystemReader 增加可选 mmap 加载,对应 `distributed/checkpoint/filesystem` |
59 62 
60上述 6 个 TorchTitan PR(#4534、#4575、#4578、#4598、#4663、#4664)已在上游合入,但 `v0.3.0` 尚未包含这些修复。63上述 6 个 TorchTitan PR(#4534、#4575、#4578、#4598、#4663、#4664)已在上游合入,但 `v0.3.0` 尚未包含这些修复。
61 64 
@@ -7,6 +7,7 @@ from .components import checkpoint # noqa: F401, I001
7from . import trainer # noqa: F4017from . import trainer # noqa: F401
8from .components import metrics, optimizer, validate # noqa: F4018from .components import metrics, optimizer, validate # noqa: F401
9from .distributed import context_parallel, full_dtensor # noqa: F4019from .distributed import context_parallel, full_dtensor # noqa: F401
10+import torchtitan_npu.patches.torchtitan.distributed.checkpoint.filesystem # noqa: F401
10from .distributed.flex_shard import dist_muon # noqa: F40111from .distributed.flex_shard import dist_muon # noqa: F401
11from .experiments.graph_trainer import ( # noqa: F40112from .experiments.graph_trainer import ( # noqa: F401
12 chunked_loss,13 chunked_loss,
@@ -0,0 +1,151 @@
1+# Pending upstream PR: https://github.com/pytorch/pytorch/pull/201621
2+ 
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd. All rights reserved.
4+#
5+# This source code is licensed under the BSD-style license found in the
6+# LICENSE file in the root directory of this source tree.
7+ 
8+"""Minimal mmap backport for trusted local DCP checkpoints from PyTorch PR #201621.
9+ 
10+Remove this module after the pinned PyTorch dependency includes the PR.
11+"""
12+ 
13+from __future__ import annotations
14+ 
15+import collections
16+import io
17+import os
18+import zipfile
19+ 
20+import torch
21+import torch.distributed._shard._utils as shard_utils
22+import torch.distributed.checkpoint.filesystem
23+import torch.distributed.checkpoint.planner
24+import torch.distributed.checkpoint.utils
25+import torch.futures
26+import torch.serialization
27+ 
28+_ORIGINAL_INIT = torch.distributed.checkpoint.filesystem.FileSystemReader.__init__
29+_ORIGINAL_READ_DATA = torch.distributed.checkpoint.filesystem.FileSystemReader.read_data
30+ 
31+ 
32+class _UnsupportedZipRegion(Exception): # noqa: N818
33+ """Compressed or encrypted storage. Caller falls back to torch.load."""
34+ 
35+ 
36+class _BoundedReader(torch.distributed.checkpoint.utils._ReaderView):
37+ """Correct SEEK_END for one blob. Not installed on the global _ReaderView."""
38+ 
39+ def seek(self, offset: int, whence: int = os.SEEK_SET, /) -> int:
40+ if whence == os.SEEK_CUR:
41+ offset += self.tell()
42+ elif whence == os.SEEK_END:
43+ offset += self.len
44+ elif whence != os.SEEK_SET:
45+ raise ValueError(f"invalid whence: {whence}")
46+ if offset < 0:
47+ raise ValueError(f"negative seek value {offset}")
48+ self.base_stream.seek(self.offset + offset)
49+ return offset
50+ 
51+ def read(self, size=-1):
52+ max_size = self.len - self.tell()
53+ if max_size <= 0:
54+ return b""
55+ if size < 0 or size > max_size:
56+ size = max_size
57+ return self.base_stream.read(size)
58+ 
59+ def readinto(self, b):
60+ data = self.read(len(b))
61+ b[: len(data)] = data
62+ return len(data)
63+ 
64+ 
65+def _load_zip_region(zip_view, overall_storage, storage_base_offset: int):
66+ position = zip_view.tell()
67+ view = _BoundedReader(zip_view.base_stream, zip_view.offset, zip_view.len)
68+ try:
69+ region_length = view.seek(0, os.SEEK_END)
70+ view.seek(0)
71+ with zipfile.ZipFile(view) as archive:
72+ for info in archive.infolist():
73+ if not info.filename.split("/", 1)[-1].startswith("data/"):
74+ continue
75+ if info.flag_bits & 0x1 or info.compress_type != zipfile.ZIP_STORED:
76+ raise _UnsupportedZipRegion
77+ view.seek(0)
78+ with torch.serialization._open_zipfile_reader(view) as zip_file: # pyrefly: ignore [bad-argument-type]
79+ # Offsets from this reader are relative to the blob, matching the slice.
80+ region = overall_storage[storage_base_offset : storage_base_offset + region_length]
81+ return torch.serialization._load(
82+ zip_file,
83+ "cpu",
84+ torch.serialization._weights_only_unpickler,
85+ overall_storage=region,
86+ weights_only=True,
87+ )
88+ finally:
89+ zip_view.seek(position)
90+ 
91+ 
92+def _patched_init(self, path, *args, mmap: bool = False, **kwargs) -> None:
93+ _ORIGINAL_INIT(self, path, *args, **kwargs)
94+ self.mmap = mmap
95+ 
96+ 
97+def _patched_read_data(self, plan, planner):
98+ storage_data = self.storage_data
99+ if (
100+ not self.mmap
101+ or type(self.fs) is not torch.distributed.checkpoint.filesystem.FileSystem
102+ or any(storage_data[item.storage_index].transform_descriptors or () for item in plan.items)
103+ ):
104+ return _ORIGINAL_READ_DATA(self, plan, planner)
105+ 
106+ per_file = collections.defaultdict(list)
107+ for item in plan.items:
108+ per_file[storage_data[item.storage_index].relative_path].append(item)
109+ 
110+ for relative_path, reqs in per_file.items():
111+ path = self.fs.concat_path(self.path, relative_path)
112+ with self.fs.create_stream(path, "rb") as stream:
113+ mapped = None
114+ file_size = None
115+ for req in reqs: # pyrefly: ignore [bad-assignment]
116+ item_md = storage_data[req.storage_index]
117+ blob = self._slice_file(stream, item_md)
118+ if req.type == torch.distributed.checkpoint.planner.LoadItemType.BYTE_IO:
119+ planner.load_bytes(req, io.BytesIO(blob.read(-1)))
120+ continue
121+ if file_size is None:
122+ file_size = os.fstat(stream.fileno()).st_size
123+ if item_md.offset < 0 or item_md.length <= 0 or item_md.offset + item_md.length > file_size:
124+ raise RuntimeError("DCP storage range is outside the backing file")
125+ if mapped is None:
126+ mapped = torch.UntypedStorage.from_file(os.fspath(path), shared=False, nbytes=file_size)
127+ try:
128+ tensor = _load_zip_region(blob, mapped, item_md.offset)
129+ except _UnsupportedZipRegion:
130+ blob.seek(0)
131+ tensor = torch.load( # pyrefly: ignore [bad-argument-type]
132+ blob, map_location="cpu", weights_only=True
133+ )
134+ tensor = shard_utils.narrow_tensor_by_index(tensor, req.storage_offsets, req.lengths)
135+ target = planner.resolve_tensor(req).detach()
136+ if target.size() != tensor.size():
137+ raise AssertionError(f"req {req.storage_index} mismatch sizes {target.size()} vs {tensor.size()}")
138+ target.copy_(tensor)
139+ planner.commit_tensor(req, target)
140+ 
141+ fut = torch.futures.Future()
142+ fut.set_result(None)
143+ return fut
144+ 
145+ 
146+def apply() -> None:
147+ torch.distributed.checkpoint.filesystem.FileSystemReader.__init__ = _patched_init
148+ torch.distributed.checkpoint.filesystem.FileSystemReader.read_data = _patched_read_data
149+ 
150+ 
151+apply()