Source code for multistorageclient.contrib.torch.filesystem

  1# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
  2# SPDX-License-Identifier: Apache-2.0
  3#
  4# Licensed under the Apache License, Version 2.0 (the "License");
  5# you may not use this file except in compliance with the License.
  6# You may obtain a copy of the License at
  7#
  8# http://www.apache.org/licenses/LICENSE-2.0
  9#
 10# Unless required by applicable law or agreed to in writing, software
 11# distributed under the License is distributed on an "AS IS" BASIS,
 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13# See the License for the specific language overning permissions and
 14# limitations under the License.
 15
 16import io
 17import os
 18from collections.abc import Generator
 19from concurrent.futures import ThreadPoolExecutor
 20from contextlib import contextmanager
 21from typing import cast
 22
 23from torch.distributed.checkpoint.filesystem import FileSystemBase, FileSystemReader, FileSystemWriter
 24from torch.distributed.checkpoint.planner import (
 25    LoadPlan,
 26    LoadPlanner,
 27    ReadItem,
 28)
 29from torch.futures import Future
 30
 31from ...pathlib import MultiStoragePath
 32from ...types import StreamingWriterOptions
 33
 34
[docs] 35class MultiStorageFileSystem(FileSystemBase): 36 """ 37 A filesystem implementation that uses the MultiStoragePath class to handle paths. 38 """ 39 40 def __init__(self, writer_options: StreamingWriterOptions | None = None) -> None: 41 """ 42 :param writer_options: Stream files opened with mode ``"wb"`` through bounded multipart uploads. 43 """ 44 self._writer_options = writer_options 45
[docs] 46 @contextmanager 47 def create_stream(self, path: str | os.PathLike, mode: str) -> Generator[io.IOBase, None, None]: 48 # always download the file here (used for checkpointing) 49 writer_options = self._writer_options if mode == "wb" else None 50 with MultiStoragePath(path).open(mode=mode, prefetch_file=True, writer_options=writer_options) as fp: 51 yield fp
52
[docs] 53 def concat_path(self, path: str | os.PathLike, suffix: str) -> str | os.PathLike: 54 return MultiStoragePath(path) / suffix
55
[docs] 56 def rename(self, path: str | os.PathLike, new_path: str | os.PathLike) -> None: 57 MultiStoragePath(path).rename(new_path)
58
[docs] 59 def init_path(self, path: str | os.PathLike) -> str | os.PathLike: 60 return MultiStoragePath(path)
61
[docs] 62 def mkdir(self, path: str | os.PathLike) -> None: 63 MultiStoragePath(path).mkdir(parents=True, exist_ok=True)
64
[docs] 65 @classmethod 66 def validate_checkpoint_id(cls, checkpoint_id: str | os.PathLike) -> bool: 67 try: 68 MultiStoragePath(checkpoint_id) 69 except ValueError: 70 return False 71 72 return True
73
[docs] 74 def exists(self, path: str | os.PathLike) -> bool: 75 return MultiStoragePath(path).exists()
76
[docs] 77 def rm_file(self, path: str | os.PathLike) -> None: 78 MultiStoragePath(path).unlink()
79
[docs] 80 def ls(self, path: str | os.PathLike) -> list[str]: 81 return [str(p) for p in MultiStoragePath(path).iterdir()]
82 83 84def _prefetch_objects(fs: MultiStorageFileSystem, urls: list[MultiStoragePath], thread_count: int) -> None: 85 """ 86 Efficiently pre-downloads files from object storage using parallel threads, storing them in cache when enabled for optimized subsequent access. 87 """ 88 89 def _prefetch(url: MultiStoragePath) -> None: 90 with fs.create_stream(url, "rb") as _: 91 pass 92 93 with ThreadPoolExecutor(max_workers=thread_count) as executor: 94 futures = [executor.submit(_prefetch, url) for url in urls] 95 for future in futures: 96 future.result() 97 98
[docs] 99class MultiStorageFileSystemReader(FileSystemReader): 100 """ 101 A reader implementation that uses the MultiStorageFileSystem class to handle file system operations. 102 """ 103 104 def __init__(self, path: str | os.PathLike, thread_count: int = 1) -> None: 105 """ 106 Initialize the MultiStorageFileSystemReader with the MultiStorageFileSystem. 107 108 :param path: The path to the checkpoint. 109 :param thread_count: The number of threads to use for prefetching. 110 """ 111 super().__init__(path) 112 self.fs = MultiStorageFileSystem() 113 self.path = self.fs.init_path(path) 114 self.thread_count = thread_count 115
[docs] 116 def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]: 117 """ 118 Override the method to prefetch objects from object storage. 119 """ 120 if self.thread_count > 1: 121 # group requests by file 122 per_file: dict[str, list[ReadItem]] = {} 123 for read_item in plan.items: 124 item_md = self.storage_data[read_item.storage_index] 125 path = item_md.relative_path 126 per_file.setdefault(path, []).append(read_item) 127 128 # prefetch objects 129 urls = [cast(MultiStoragePath, self.path) / rel_path for rel_path, _ in per_file.items()] 130 _prefetch_objects(self.fs, urls, self.thread_count) 131 132 return super().read_data(plan, planner)
133
[docs] 134 @classmethod 135 def validate_checkpoint_id(cls, checkpoint_id: str | os.PathLike) -> bool: 136 return MultiStorageFileSystem.validate_checkpoint_id(checkpoint_id)
137 138
[docs] 139class MultiStorageFileSystemWriter(FileSystemWriter): 140 """ 141 A writer implementation that uses the MultiStorageFileSystem class to handle file system operations. 142 """ 143 144 def __init__( 145 self, 146 path: str | os.PathLike, 147 single_file_per_rank: bool = True, 148 sync_files: bool = True, 149 thread_count: int = 1, 150 per_thread_copy_ahead: int = 10_000_000, 151 cache_staged_state_dict: bool = False, 152 overwrite: bool = True, 153 writer_options: StreamingWriterOptions | None = None, 154 ) -> None: 155 """ 156 Initialize the MultiStorageFileSystemWriter with the MultiStorageFileSystem. 157 158 :param writer_options: Stream checkpoint files through bounded multipart uploads instead of buffering them. 159 """ 160 super().__init__( 161 path, 162 single_file_per_rank, 163 sync_files, 164 thread_count, 165 per_thread_copy_ahead, 166 cache_staged_state_dict, 167 overwrite=overwrite, 168 ) 169 self.fs = MultiStorageFileSystem(writer_options=writer_options) 170 self.path = self.fs.init_path(path) 171
[docs] 172 @classmethod 173 def validate_checkpoint_id(cls, checkpoint_id: str | os.PathLike) -> bool: 174 return MultiStorageFileSystem.validate_checkpoint_id(checkpoint_id)