|
| 1 | +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +# // SPDX-License-Identifier: BSD |
| 3 | + |
| 4 | +import io |
| 5 | +import logging |
| 6 | +import os |
| 7 | +from contextlib import contextmanager |
| 8 | +from pathlib import Path |
| 9 | +from typing import Generator, Union, Optional |
| 10 | + |
| 11 | +from s3torchconnectorclient._mountpoint_s3_client import S3Exception |
| 12 | +from tenacity import ( |
| 13 | + retry, |
| 14 | + stop_after_attempt, |
| 15 | + retry_if_exception_type, |
| 16 | + before_sleep_log, |
| 17 | + after_log, |
| 18 | + wait_random_exponential, |
| 19 | +) |
| 20 | +from torch.distributed.checkpoint.filesystem import ( |
| 21 | + FileSystemReader, |
| 22 | + FileSystemWriter, |
| 23 | + FileSystemBase, |
| 24 | +) |
| 25 | + |
| 26 | +from s3torchconnector._s3client import S3Client |
| 27 | +from s3torchconnector._s3dataset_common import parse_s3_uri |
| 28 | + |
| 29 | +logger = logging.getLogger(__name__) |
| 30 | + |
| 31 | + |
| 32 | +class S3FileSystem(FileSystemBase): |
| 33 | + def __init__(self, region: str, s3_client: Optional[S3Client] = None) -> None: |
| 34 | + self._path: Union[str, os.PathLike] = "" |
| 35 | + self._client = s3_client if s3_client is not None else S3Client(region) |
| 36 | + |
| 37 | + @contextmanager |
| 38 | + def create_stream( |
| 39 | + self, path: Union[str, os.PathLike], mode: str |
| 40 | + ) -> Generator[io.IOBase, None, None]: |
| 41 | + """ |
| 42 | + Create a stream for reading or writing to S3. |
| 43 | +
|
| 44 | + Args: |
| 45 | + path (Union[str, os.PathLike]): The S3 path to read or write. |
| 46 | + mode (str): The mode for the stream. Supports 'rb' for read mode and 'wb' for write mode. |
| 47 | +
|
| 48 | + Yields: |
| 49 | + io.BufferedIOBase: A stream for reading or writing to S3. |
| 50 | +
|
| 51 | + Raises: |
| 52 | + ValueError: If the mode is not 'rb' or 'wb'. |
| 53 | + """ |
| 54 | + path_str = _path_or_str_to_str(path) |
| 55 | + bucket, key = parse_s3_uri(path_str) |
| 56 | + |
| 57 | + if mode == "wb": # write mode |
| 58 | + logger.debug("create_stream writable for %s", path_str) |
| 59 | + with self._client.put_object(bucket, key) as stream: |
| 60 | + yield stream |
| 61 | + elif mode == "rb": # read mode |
| 62 | + logger.debug("create_stream readable for %s", path_str) |
| 63 | + with self._client.get_object(bucket, key) as stream: |
| 64 | + yield stream |
| 65 | + else: |
| 66 | + raise ValueError( |
| 67 | + f"Invalid {mode=} mode argument: create_stream only supports rb (read mode) & wb (write mode)" |
| 68 | + ) |
| 69 | + |
| 70 | + def concat_path(self, path: Union[str, os.PathLike], suffix: str) -> str: |
| 71 | + """ |
| 72 | + Concatenate a suffix to the given path. |
| 73 | +
|
| 74 | + Args: |
| 75 | + path (Union[str, os.PathLike]): The base path. |
| 76 | + suffix (str): The suffix to concatenate. |
| 77 | +
|
| 78 | + Returns: |
| 79 | + str: The concatenated path. |
| 80 | + """ |
| 81 | + logger.debug("concat paths %s and %s", path, suffix) |
| 82 | + path_str = os.fspath(path) |
| 83 | + result = os.path.join(path_str, suffix) |
| 84 | + return result |
| 85 | + |
| 86 | + def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]: |
| 87 | + """ |
| 88 | + Initialize the path for the filesystem. |
| 89 | +
|
| 90 | + Args: |
| 91 | + path (Union[str, os.PathLike]): The path to initialize. |
| 92 | +
|
| 93 | + Returns: |
| 94 | + Union[str, os.PathLike]: The initialized path. |
| 95 | + """ |
| 96 | + logger.debug("init_path for %s", path) |
| 97 | + self._path = path |
| 98 | + return self._path |
| 99 | + |
| 100 | + def rename( |
| 101 | + self, old_path: Union[str, os.PathLike], new_path: Union[str, os.PathLike] |
| 102 | + ) -> None: |
| 103 | + """Rename an object in S3. |
| 104 | +
|
| 105 | + This is emulated by copying it to a new path and deleting the old path. The deletion part is retried (see also |
| 106 | + :func:`S3FileSystem._delete_with_retry`). |
| 107 | +
|
| 108 | + Args: |
| 109 | + old_path (Union[str, os.PathLike]): The current path of the object. |
| 110 | + new_path (Union[str, os.PathLike]): The new path for the object. |
| 111 | +
|
| 112 | + Raises: |
| 113 | + ValueError: If the old and new paths point to different buckets. |
| 114 | + S3Exception: If there is an error with the S3 client. |
| 115 | + """ |
| 116 | + logger.debug("rename %s to %s", old_path, new_path) |
| 117 | + |
| 118 | + old_path_str = _path_or_str_to_str(old_path) |
| 119 | + new_path_str = _path_or_str_to_str(new_path) |
| 120 | + |
| 121 | + old_bucket, old_key = parse_s3_uri(old_path_str) |
| 122 | + new_bucket, new_key = parse_s3_uri(new_path_str) |
| 123 | + |
| 124 | + if old_bucket != new_bucket: |
| 125 | + raise ValueError( |
| 126 | + f"Source and destination buckets cannot be different (rename does not support cross-buckets operations)" |
| 127 | + ) |
| 128 | + |
| 129 | + self._client.copy_object( |
| 130 | + src_bucket=old_bucket, |
| 131 | + src_key=old_key, |
| 132 | + dst_bucket=new_bucket, |
| 133 | + dst_key=new_key, |
| 134 | + ) |
| 135 | + logger.debug("rename: copied %s to %s successfully", old_path_str, new_path_str) |
| 136 | + self._delete_with_retry(old_bucket, old_key) |
| 137 | + logger.debug("rename: s3://%s/%s successfully", old_bucket, old_key) |
| 138 | + |
| 139 | + def mkdir(self, path: Union[str, os.PathLike]) -> None: |
| 140 | + """No-op method for creating directories in S3 (not needed).""" |
| 141 | + pass |
| 142 | + |
| 143 | + def exists(self, path: Union[str, os.PathLike]) -> bool: |
| 144 | + logger.debug("exists %s", path) |
| 145 | + |
| 146 | + path_str = _path_or_str_to_str(path) |
| 147 | + bucket, key = parse_s3_uri(path_str) |
| 148 | + try: |
| 149 | + self._client.head_object(bucket, key) |
| 150 | + except S3Exception as e: |
| 151 | + if str(e) != "Service error: The object was not found": |
| 152 | + raise |
| 153 | + return False |
| 154 | + return True |
| 155 | + |
| 156 | + def rm_file(self, path: Union[str, os.PathLike]) -> None: |
| 157 | + logger.debug("remove %s", path) |
| 158 | + |
| 159 | + path_str = _path_or_str_to_str(path) |
| 160 | + bucket, key = parse_s3_uri(path_str) |
| 161 | + try: |
| 162 | + self._client.delete_object(bucket, key) |
| 163 | + except S3Exception: |
| 164 | + logger.exception("Failed to remove object from S3") |
| 165 | + |
| 166 | + @classmethod |
| 167 | + def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool: |
| 168 | + logger.debug("validate_checkpoint_id for %s", checkpoint_id) |
| 169 | + |
| 170 | + if isinstance(checkpoint_id, Path): |
| 171 | + return True |
| 172 | + |
| 173 | + try: |
| 174 | + parse_s3_uri(_path_or_str_to_str(checkpoint_id)) |
| 175 | + except ValueError: |
| 176 | + return False |
| 177 | + return True |
| 178 | + |
| 179 | + @retry( |
| 180 | + retry=retry_if_exception_type(S3Exception), |
| 181 | + stop=stop_after_attempt(3), |
| 182 | + wait=wait_random_exponential(multiplier=1, max=5), |
| 183 | + before_sleep=before_sleep_log(logger, logging.WARNING), |
| 184 | + after=after_log(logger, logging.ERROR), |
| 185 | + reraise=True, |
| 186 | + ) |
| 187 | + def _delete_with_retry(self, bucket_name: str, old_key: str): |
| 188 | + """Wrapper around :func:`S3Client.delete_object` to retry the deletion. |
| 189 | +
|
| 190 | + Will retry a maximum of 3 times, only for `S3Exception`s, and wait between retries. It will reraise the caught |
| 191 | + exception too, and logs retries and final error, if any.""" |
| 192 | + self._client.delete_object(bucket_name, old_key) |
| 193 | + |
| 194 | + |
| 195 | +class S3StorageWriter(FileSystemWriter): |
| 196 | + def __init__( |
| 197 | + self, |
| 198 | + region: str, |
| 199 | + path: Union[str, os.PathLike], |
| 200 | + single_file_per_rank: bool = True, |
| 201 | + thread_count: int = 1, |
| 202 | + per_thread_copy_ahead: int = 10_000_000, |
| 203 | + overwrite: bool = False, |
| 204 | + ) -> None: |
| 205 | + """ |
| 206 | + Initialize an S3 writer for distributed checkpointing. |
| 207 | +
|
| 208 | + Args: |
| 209 | + region (str): The AWS region for S3. |
| 210 | + path (Union[str, os.PathLike]): The S3 path to write checkpoints. |
| 211 | + single_file_per_rank (bool, optional): Whether to write a single file per rank. Defaults to True. |
| 212 | + thread_count (int, optional): The number of threads to use for writing. Defaults to 1. |
| 213 | + per_thread_copy_ahead (int, optional): The number of bytes to copy ahead per thread. Defaults to 10_000_000. |
| 214 | + overwrite (bool, optional): Whether to overwrite existing checkpoints. Defaults to False. |
| 215 | + """ |
| 216 | + super().__init__( |
| 217 | + path=path, |
| 218 | + single_file_per_rank=single_file_per_rank, |
| 219 | + sync_files=False, |
| 220 | + thread_count=thread_count, |
| 221 | + per_thread_copy_ahead=per_thread_copy_ahead, |
| 222 | + overwrite=overwrite, |
| 223 | + ) |
| 224 | + self.fs = S3FileSystem(region) # type: ignore |
| 225 | + self.path = self.fs.init_path(path) |
| 226 | + |
| 227 | + @classmethod |
| 228 | + def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool: |
| 229 | + return S3FileSystem.validate_checkpoint_id(checkpoint_id) |
| 230 | + |
| 231 | + |
| 232 | +class S3StorageReader(FileSystemReader): |
| 233 | + def __init__(self, region: str, path: Union[str, os.PathLike]) -> None: |
| 234 | + """ |
| 235 | + Initialize an S3 reader for distributed checkpointing. |
| 236 | +
|
| 237 | + Args: |
| 238 | + region (str): The AWS region for S3. |
| 239 | + path (Union[str, os.PathLike]): The S3 path to read checkpoints from. |
| 240 | + """ |
| 241 | + super().__init__(path) |
| 242 | + self.fs = S3FileSystem(region) # type: ignore |
| 243 | + self.path = self.fs.init_path(path) |
| 244 | + self.sync_files = False |
| 245 | + |
| 246 | + @classmethod |
| 247 | + def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool: |
| 248 | + return S3FileSystem.validate_checkpoint_id(checkpoint_id) |
| 249 | + |
| 250 | + |
| 251 | +def _path_or_str_to_str(path: Union[str, os.PathLike]) -> str: |
| 252 | + return path if isinstance(path, str) else str(path) |
0 commit comments