filesystem.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import dataclasses
  4. import io
  5. import operator
  6. import os
  7. import pickle
  8. import queue
  9. import threading
  10. import uuid
  11. import warnings
  12. from abc import ABC, abstractmethod
  13. from contextlib import contextmanager
  14. from dataclasses import dataclass
  15. from pathlib import Path
  16. from typing import (
  17. Any,
  18. Callable,
  19. cast,
  20. Dict,
  21. Generator,
  22. IO,
  23. Iterable,
  24. Iterator,
  25. List,
  26. Optional,
  27. Tuple,
  28. Union,
  29. )
  30. import torch
  31. from torch import Tensor
  32. from torch._utils import _get_available_device_type, _get_device_module
  33. from torch.distributed._shard._utils import narrow_tensor_by_index
  34. from torch.distributed.checkpoint.metadata import (
  35. Metadata,
  36. MetadataIndex,
  37. STATE_DICT_TYPE,
  38. StorageMeta,
  39. )
  40. from torch.distributed.checkpoint.planner import (
  41. LoadItemType,
  42. LoadPlan,
  43. LoadPlanner,
  44. ReadItem,
  45. SavePlan,
  46. SavePlanner,
  47. WriteItem,
  48. WriteItemType,
  49. )
  50. from torch.distributed.checkpoint.staging import BlockingAsyncStager
  51. from torch.distributed.checkpoint.storage import (
  52. StorageReader,
  53. StorageWriter,
  54. WriteResult,
  55. )
  56. from torch.distributed.checkpoint.utils import _create_file_view
  57. from torch.futures import Future
  58. __all__ = ["FileSystemWriter", "FileSystemReader", "FileSystem", "FileSystemBase"]
  59. _metadata_fn: str = ".metadata"
  60. @dataclass
  61. class _StorageInfo:
  62. """This is the per entry storage info."""
  63. relative_path: str
  64. offset: int
  65. length: int
  66. @dataclass
  67. class _StoragePrefix:
  68. prefix: str
  69. DEFAULT_SUFFIX = ".distcp"
  70. def _generate_uuid() -> str:
  71. return str(uuid.uuid4())
  72. class _TensorLoader(ABC):
  73. @abstractmethod
  74. def add(self, size: int, obj: object) -> None:
  75. pass
  76. @abstractmethod
  77. def start_loading(self) -> None:
  78. pass
  79. @abstractmethod
  80. def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
  81. pass
  82. class _SerialCpuLoader(_TensorLoader):
  83. def __init__(self, resolve_fun: Callable) -> None:
  84. self.resolve_fun = resolve_fun
  85. self.items: List[Tuple[int, object]] = []
  86. def add(self, size: int, obj: object) -> None:
  87. self.items.append((size, obj))
  88. def start_loading(self) -> None:
  89. pass
  90. def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
  91. for _, obj in self.items:
  92. tensor = self.resolve_fun(obj).detach()
  93. tensor = tensor.cpu()
  94. if tensor.storage().size() != tensor.numel():
  95. tensor = tensor.clone()
  96. yield (
  97. tensor,
  98. obj,
  99. )
  100. class _OverlappingCpuLoader(_TensorLoader):
  101. def __init__(
  102. self,
  103. resolve_fun: Callable,
  104. stream: Optional[torch.Stream] = None,
  105. inflight_threshhold: int = 1_000_000,
  106. ) -> None:
  107. self.resolve_fun = resolve_fun
  108. self.items: List[Tuple[int, object]] = []
  109. self.inflight_threshhold = inflight_threshhold
  110. self.in_flight_data = 0
  111. self.current_items: collections.deque = collections.deque()
  112. self.idx = 0
  113. self.started = False
  114. self.device_type = (
  115. stream.device_type if stream else _get_available_device_type()
  116. )
  117. self.device_module = _get_device_module(self.device_type)
  118. self.stream = cast(
  119. torch.cuda.Stream, stream or self.device_module.current_stream()
  120. )
  121. if self.stream != self.device_module.current_stream():
  122. self.stream.wait_stream(self.device_module.current_stream())
  123. @property
  124. def _done(self) -> bool:
  125. return self.idx >= len(self.items)
  126. def _drain(self) -> List[Tuple[torch.Tensor, object]]:
  127. drained = []
  128. if self.in_flight_data >= self.inflight_threshhold:
  129. self.stream.synchronize()
  130. while self.in_flight_data >= self.inflight_threshhold:
  131. val = self.current_items.popleft()
  132. self.in_flight_data -= val[0].numel() * val[0].element_size()
  133. drained.append(val)
  134. return drained
  135. def _refill(self) -> None:
  136. with self.device_module.stream(self.stream):
  137. while not self._done and self.in_flight_data < self.inflight_threshhold:
  138. _, obj = self.items[self.idx]
  139. self.idx += 1
  140. tensor = self.resolve_fun(obj).detach()
  141. if tensor.device.type == self.device_type:
  142. tensor = tensor.to(device="cpu", non_blocking=True)
  143. elif tensor.device == torch.device("cpu"):
  144. if (
  145. tensor.untyped_storage().size()
  146. != tensor.numel() * tensor.itemsize
  147. ):
  148. # this forces the tensor to be both contiguous and with minimal storage
  149. tensor = tensor.clone()
  150. self.current_items.append(
  151. (
  152. tensor,
  153. obj,
  154. )
  155. )
  156. self.in_flight_data += tensor.numel() * tensor.element_size()
  157. def _finish(self) -> Iterable[Tuple[torch.Tensor, object]]:
  158. assert self._done
  159. if len(self.current_items) > 0:
  160. self.stream.synchronize()
  161. return self.current_items
  162. def add(self, size: int, obj: object) -> None:
  163. if self.started:
  164. raise RuntimeError("cannot add items after loading started")
  165. self.items.append((size, obj))
  166. def start_loading(self) -> None:
  167. if self.started:
  168. return
  169. self.started = True
  170. self.items.sort(key=operator.itemgetter(0))
  171. self._refill()
  172. def values(self) -> Iterator[Tuple[torch.Tensor, object]]:
  173. self.start_loading()
  174. while not self._done:
  175. drained = self._drain()
  176. self._refill()
  177. yield from drained
  178. yield from self._finish()
  179. def _item_size(item: WriteItem) -> int:
  180. size = 1
  181. assert item.tensor_data is not None
  182. # can't use math.prod as PT needs to support older python
  183. for s in item.tensor_data.size:
  184. size *= s
  185. dtype = item.tensor_data.properties.dtype
  186. return size * torch._utils._element_size(dtype)
  187. def _split_by_size_and_type(bins: int, items: List[WriteItem]) -> List[List[WriteItem]]:
  188. if bins == 1:
  189. return [items]
  190. bytes_w = [wi for wi in items if wi.type == WriteItemType.BYTE_IO]
  191. tensor_w = [wi for wi in items if wi.type != WriteItemType.BYTE_IO]
  192. buckets: List[List[WriteItem]] = [[] for _ in range(bins)]
  193. bucket_sizes = [0 for _ in range(bins)]
  194. tensor_w.sort(key=_item_size, reverse=True)
  195. for i, wi in enumerate(bytes_w):
  196. buckets[i % bins].append(wi)
  197. for wi in tensor_w:
  198. # TODO replace with headq
  199. idx = min(enumerate(bucket_sizes), key=operator.itemgetter(1))[0]
  200. buckets[idx].append(wi)
  201. bucket_sizes[idx] += _item_size(wi)
  202. return buckets
  203. def _write_item(
  204. stream: io.IOBase,
  205. data: Union[io.BytesIO, torch.Tensor],
  206. write_item: WriteItem,
  207. storage_key: str,
  208. ) -> WriteResult:
  209. offset = stream.tell()
  210. if write_item.type == WriteItemType.BYTE_IO:
  211. assert isinstance(data, io.BytesIO)
  212. stream.write(data.getbuffer())
  213. else:
  214. assert isinstance(data, torch.Tensor)
  215. assert data.device == torch.device("cpu")
  216. torch.save(data, cast(IO[bytes], stream))
  217. length = stream.tell() - offset
  218. return WriteResult(
  219. index=write_item.index,
  220. size_in_bytes=length,
  221. storage_data=_StorageInfo(storage_key, offset, length),
  222. )
  223. def _write_files_from_queue(
  224. create_stream: Callable,
  225. file_queue: queue.Queue,
  226. result_queue: queue.Queue,
  227. planner: SavePlanner,
  228. inflight_threshhold: int,
  229. use_fsync: bool,
  230. thread_count: int,
  231. ) -> None:
  232. try:
  233. while True:
  234. file_name, storage_key, write_items = file_queue.get_nowait()
  235. loader: _TensorLoader
  236. custom_backend_name = torch._C._get_privateuse1_backend_name()
  237. custom_device_mod = getattr(torch, custom_backend_name, None)
  238. # TODO: Using the OverlappingCpuLoader with multiple threads creates significant
  239. # performance degredation, observed as being related to cuda stream syncs. We
  240. # should try to fix this and use _OverlappingCpuLoader for all threaded cases
  241. if (
  242. thread_count == 1
  243. and (
  244. torch.cuda.is_available()
  245. or (custom_device_mod and custom_device_mod.is_available())
  246. )
  247. and inflight_threshhold > 0
  248. ):
  249. loader = _OverlappingCpuLoader(
  250. planner.resolve_data,
  251. inflight_threshhold=inflight_threshhold,
  252. )
  253. else:
  254. loader = _SerialCpuLoader(
  255. planner.resolve_data,
  256. )
  257. tensor_w = [wi for wi in write_items if wi.type != WriteItemType.BYTE_IO]
  258. for write_item in tensor_w:
  259. loader.add(_item_size(write_item), write_item)
  260. loader.start_loading()
  261. bytes_w = [wi for wi in write_items if wi.type == WriteItemType.BYTE_IO]
  262. write_results = []
  263. with create_stream(file_name, "wb") as stream:
  264. for write_item in bytes_w:
  265. data = planner.resolve_data(write_item)
  266. write_results.append(
  267. _write_item(stream, data, write_item, storage_key)
  268. )
  269. for tensor, write_item in loader.values():
  270. assert tensor.is_cpu
  271. write_results.append(
  272. _write_item(stream, tensor, write_item, storage_key)
  273. )
  274. if use_fsync:
  275. try:
  276. os.fsync(stream.fileno())
  277. except AttributeError:
  278. os.sync()
  279. result_queue.put(write_results)
  280. except queue.Empty:
  281. pass
  282. class FileSystemBase(ABC):
  283. @contextmanager
  284. @abstractmethod
  285. def create_stream(
  286. self, path: Union[str, os.PathLike], mode: str
  287. ) -> Generator[io.IOBase, None, None]:
  288. ...
  289. @abstractmethod
  290. def concat_path(
  291. self, path: Union[str, os.PathLike], suffix: str
  292. ) -> Union[str, os.PathLike]:
  293. ...
  294. @abstractmethod
  295. def rename(
  296. self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
  297. ) -> None:
  298. ...
  299. @abstractmethod
  300. def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
  301. ...
  302. @abstractmethod
  303. def mkdir(self, path: Union[str, os.PathLike]) -> None:
  304. ...
  305. @classmethod
  306. @abstractmethod
  307. def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
  308. ...
  309. @abstractmethod
  310. def exists(self, path: Union[str, os.PathLike]) -> bool:
  311. ...
  312. @abstractmethod
  313. def rm_file(self, path: Union[str, os.PathLike]) -> None:
  314. ...
  315. class FileSystem(FileSystemBase):
  316. @contextmanager
  317. def create_stream(
  318. self, path: Union[str, os.PathLike], mode: str
  319. ) -> Generator[io.IOBase, None, None]:
  320. with cast(Path, path).open(mode) as stream:
  321. yield cast(io.IOBase, stream)
  322. def concat_path(
  323. self, path: Union[str, os.PathLike], suffix: str
  324. ) -> Union[str, os.PathLike]:
  325. return cast(Path, path) / suffix
  326. def init_path(self, path: Union[str, os.PathLike]) -> Union[str, os.PathLike]:
  327. if not isinstance(path, Path):
  328. path = Path(path)
  329. return path
  330. def rename(
  331. self, path: Union[str, os.PathLike], new_path: Union[str, os.PathLike]
  332. ) -> None:
  333. cast(Path, path).rename(cast(Path, new_path))
  334. def mkdir(self, path: Union[str, os.PathLike]) -> None:
  335. cast(Path, path).mkdir(parents=True, exist_ok=True)
  336. @classmethod
  337. def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
  338. if isinstance(checkpoint_id, Path):
  339. return True
  340. if "://" in str(checkpoint_id):
  341. return False
  342. for p in Path(checkpoint_id).parents:
  343. if p.exists() and os.access(str(p), os.W_OK):
  344. return True
  345. return False
  346. def exists(self, path: Union[str, os.PathLike]) -> bool:
  347. return cast(Path, path).exists()
  348. def rm_file(self, path: Union[str, os.PathLike]) -> None:
  349. cast(Path, path).unlink()
  350. class _FileSystemWriter(StorageWriter):
  351. """
  352. Basic implementation of StorageWriter using file IO.
  353. This implementation makes the following assumptions and simplifications:
  354. * The checkpoint path is an empty or non-existing directory.
  355. * File creation is atomic
  356. The checkpoint consist of one file per write request plus
  357. a `.metadata` file with the serialized metadata.
  358. """
  359. def __init__(
  360. self,
  361. path: Union[str, os.PathLike],
  362. single_file_per_rank: bool = True,
  363. sync_files: bool = True,
  364. thread_count: int = 1,
  365. per_thread_copy_ahead: int = 10_000_000,
  366. overwrite: bool = True,
  367. *args: Any,
  368. **kwargs: Any,
  369. ) -> None:
  370. """
  371. Initialize the writer pointing to `path`.
  372. Args:
  373. path: directory where the checkpoint will be written to.
  374. single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
  375. sync_files : force files to be synced to permanent storage. Default to True.
  376. thread_count: Number of IO threads to use to write. Default to 1.
  377. per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
  378. overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
  379. N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
  380. """
  381. super().__init__()
  382. self.fs = FileSystem()
  383. self.path = self.fs.init_path(path)
  384. self.single_file_per_rank = single_file_per_rank
  385. self.sync_files = sync_files
  386. self.thread_count = thread_count
  387. self.per_thread_copy_ahead = per_thread_copy_ahead
  388. self.save_id = _generate_uuid()
  389. self.overwrite = overwrite
  390. def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
  391. if checkpoint_id:
  392. self.path = self.fs.init_path(checkpoint_id)
  393. self.save_id = _generate_uuid()
  394. def set_up_storage_writer(self, is_coordinator: bool) -> None:
  395. pass
  396. def prepare_local_plan(self, plan: SavePlan) -> SavePlan:
  397. self.fs.mkdir(self.path)
  398. if self.fs.exists(self.metadata_path):
  399. if self.overwrite:
  400. warnings.warn(
  401. f"Detected an existing checkpoint in {self.metadata_path}, overwriting since {self.overwrite=}."
  402. " Past version 2.5 of PyTorch, `overwrite` will default to False. Set this variable to True to"
  403. " maintain this functionality or False to raise when an existing checkpoint is found."
  404. )
  405. else:
  406. raise RuntimeError(f"Checkpoint already exists and {self.overwrite=}.")
  407. return plan
  408. def prepare_global_plan(self, plans: List[SavePlan]) -> List[SavePlan]:
  409. new_plans = [
  410. dataclasses.replace(plan, storage_data=_StoragePrefix(f"__{i}_"))
  411. for i, plan in enumerate(plans)
  412. ]
  413. return new_plans
  414. def write_data(
  415. self,
  416. plan: SavePlan,
  417. planner: SavePlanner,
  418. ) -> Future[List[WriteResult]]:
  419. storage_plan: _StoragePrefix = plan.storage_data
  420. file_count = 0
  421. def gen_file():
  422. nonlocal file_count
  423. file_name = f"{storage_plan.prefix}{file_count}{DEFAULT_SUFFIX}"
  424. file_count += 1
  425. return file_name
  426. file_queue: queue.Queue = queue.Queue()
  427. if self.single_file_per_rank:
  428. for bucket in _split_by_size_and_type(self.thread_count, plan.items):
  429. file_name = gen_file()
  430. path = self.fs.concat_path(self.path, file_name)
  431. file_queue.put((path, file_name, bucket))
  432. else:
  433. for item in plan.items:
  434. file_name = gen_file()
  435. path = self.fs.concat_path(self.path, file_name)
  436. file_queue.put((path, file_name, [item]))
  437. result_queue: queue.Queue = queue.Queue()
  438. threads = []
  439. for _ in range(1, self.thread_count):
  440. t = threading.Thread(
  441. target=_write_files_from_queue,
  442. args=(
  443. self.fs.create_stream,
  444. file_queue,
  445. result_queue,
  446. planner,
  447. self.per_thread_copy_ahead,
  448. self.sync_files,
  449. self.thread_count,
  450. ),
  451. )
  452. t.start()
  453. threads.append(t)
  454. _write_files_from_queue(
  455. create_stream=self.fs.create_stream,
  456. file_queue=file_queue,
  457. result_queue=result_queue,
  458. planner=planner,
  459. inflight_threshhold=self.per_thread_copy_ahead,
  460. use_fsync=self.sync_files,
  461. thread_count=self.thread_count,
  462. )
  463. for t in threads:
  464. t.join()
  465. res = []
  466. try:
  467. while True:
  468. res += result_queue.get_nowait()
  469. except queue.Empty:
  470. pass
  471. fut: Future[List[WriteResult]] = Future()
  472. fut.set_result(res)
  473. return fut
  474. def finish(self, metadata: Metadata, results: List[List[WriteResult]]) -> None:
  475. storage_md = dict()
  476. for wr_list in results:
  477. storage_md.update({wr.index: wr.storage_data for wr in wr_list})
  478. metadata.storage_data = storage_md
  479. metadata.storage_meta = self.storage_meta()
  480. tmp_path = cast(Path, self.fs.concat_path(self.path, f"{_metadata_fn}.tmp"))
  481. with self.fs.create_stream(tmp_path, "wb") as metadata_file:
  482. pickle.dump(metadata, metadata_file)
  483. if self.sync_files:
  484. try:
  485. os.fsync(metadata_file.fileno())
  486. except AttributeError:
  487. os.sync()
  488. # delete in-case other checkpoints were present.
  489. if self.fs.exists(self.metadata_path):
  490. self.fs.rm_file(self.metadata_path)
  491. self.fs.rename(tmp_path, self.metadata_path)
  492. def storage_meta(self) -> Optional[StorageMeta]:
  493. return StorageMeta(checkpoint_id=self.checkpoint_id, save_id=self.save_id)
  494. @property
  495. def metadata_path(self) -> Union[str, os.PathLike]:
  496. return cast(Path, self.fs.concat_path(self.path, _metadata_fn))
  497. @property
  498. def checkpoint_id(self) -> Union[str, os.PathLike]:
  499. """
  500. return the checkpoint_id that will be used to save the checkpoint.
  501. """
  502. return self.path
  503. @classmethod
  504. def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
  505. return FileSystem.validate_checkpoint_id(checkpoint_id)
  506. class FileSystemReader(StorageReader):
  507. def __init__(self, path: Union[str, os.PathLike]) -> None:
  508. super().__init__()
  509. self.fs = FileSystem()
  510. self.path = self.fs.init_path(path)
  511. self.storage_data: Dict[MetadataIndex, _StorageInfo] = dict()
  512. self.load_id = _generate_uuid()
  513. def _slice_file(self, file, sinfo: _StorageInfo) -> io.IOBase:
  514. return _create_file_view(file, sinfo.offset, sinfo.length)
  515. def reset(self, checkpoint_id: Union[str, os.PathLike, None] = None) -> None:
  516. self.storage_data = dict()
  517. if checkpoint_id:
  518. self.path = self.fs.init_path(checkpoint_id)
  519. self.load_id = _generate_uuid()
  520. def read_data(self, plan: LoadPlan, planner: LoadPlanner) -> Future[None]:
  521. # group requests by file
  522. per_file: Dict[str, List[ReadItem]] = dict()
  523. for read_item in plan.items:
  524. item_md = self.storage_data[read_item.storage_index]
  525. path = item_md.relative_path
  526. per_file.setdefault(path, []).append(read_item)
  527. for relative_path, reqs in per_file.items():
  528. new_path = self.fs.concat_path(self.path, relative_path)
  529. with self.fs.create_stream(new_path, "rb") as stream:
  530. # TODO sort by offset and cache the reading
  531. for req in reqs:
  532. item_md = self.storage_data[req.storage_index]
  533. file_slice = self._slice_file(stream, item_md)
  534. if req.type == LoadItemType.BYTE_IO:
  535. read_bytes = io.BytesIO(file_slice.read(item_md.length))
  536. read_bytes.seek(0)
  537. planner.load_bytes(req, read_bytes)
  538. else:
  539. tensor = cast(
  540. Tensor,
  541. torch.load(
  542. cast(IO[bytes], file_slice),
  543. map_location="cpu",
  544. weights_only=True,
  545. ),
  546. )
  547. tensor = narrow_tensor_by_index(
  548. tensor, req.storage_offsets, req.lengths
  549. )
  550. target_tensor = planner.resolve_tensor(req).detach()
  551. assert (
  552. target_tensor.size() == tensor.size()
  553. ), f"req {req.storage_index} mismatch sizes {target_tensor.size()} vs {tensor.size()}"
  554. target_tensor.copy_(tensor)
  555. planner.commit_tensor(req, target_tensor)
  556. fut: Future = Future()
  557. fut.set_result(None)
  558. return fut
  559. # Implementing the abstract function in StorageReader
  560. def read_metadata(self) -> Metadata:
  561. path = self.fs.concat_path(self.path, ".metadata")
  562. with self.fs.create_stream(path, "rb") as metadata_file:
  563. metadata = pickle.load(metadata_file)
  564. if getattr(metadata, "storage_meta", None) is None:
  565. metadata.storage_meta = StorageMeta()
  566. metadata.storage_meta.load_id = self.load_id
  567. return metadata
  568. def set_up_storage_reader(self, metadata: Metadata, is_coordinator: bool) -> None:
  569. self.storage_data = metadata.storage_data
  570. assert self.storage_data is not None
  571. def prepare_local_plan(self, plan: LoadPlan) -> LoadPlan:
  572. return plan
  573. def prepare_global_plan(self, plans: List[LoadPlan]) -> List[LoadPlan]:
  574. return plans
  575. @property
  576. def checkpoint_id(self) -> Union[str, os.PathLike]:
  577. """
  578. return the checkpoint_id that will be used to save the checkpoint.
  579. """
  580. return self.path
  581. @classmethod
  582. def validate_checkpoint_id(cls, checkpoint_id: Union[str, os.PathLike]) -> bool:
  583. return FileSystem.validate_checkpoint_id(checkpoint_id)
  584. class FileSystemWriter(_FileSystemWriter, BlockingAsyncStager):
  585. """
  586. Basic implementation of StorageWriter using file IO.
  587. This implementation makes the following assumptions and simplifications:
  588. * The checkpoint path is an empty or non-existing directory.
  589. * File creation is atomic
  590. The checkpoint consist of one file per write request plus
  591. a `.metadata` file with the serialized metadata.
  592. """
  593. def __init__(
  594. self,
  595. path: Union[str, os.PathLike],
  596. single_file_per_rank: bool = True,
  597. sync_files: bool = True,
  598. thread_count: int = 1,
  599. per_thread_copy_ahead: int = 10_000_000,
  600. cache_staged_state_dict: bool = False,
  601. overwrite: bool = True,
  602. ) -> None:
  603. """
  604. Initialize the writer pointing to `path`.
  605. Args:
  606. path: directory where the checkpoint will be written to.
  607. single_file_per_rank: Produce one file per rank instead of one file per tensor/blob. Default to True.
  608. sync_files : force files to be synced to permanent storage. Default to True.
  609. thread_count: Number of IO threads to use to write. Default to 1.
  610. per_thread_copy_ahead: How many bytes to copy from the GPU ahead of saving then. Default 10Mb.
  611. cache_staged_state_dict: Whether to cache the staged state_dict. This option decreases staging latency
  612. at the cost of increases memory usage. Additionally, if this parameter is set to True, it's the expectation
  613. that the stager is maintained and re-used for multiple dcp.async_save calls. Default to False.
  614. overwrite: Whether to allow overwriting existing checkpoints. Defaults to True.
  615. N. B. If sync_files is disabled, there's no guarantee that the checkpoint will be consistent in the case of a failure.
  616. """
  617. super().__init__(
  618. path=path,
  619. single_file_per_rank=single_file_per_rank,
  620. sync_files=sync_files,
  621. thread_count=thread_count,
  622. per_thread_copy_ahead=per_thread_copy_ahead,
  623. cache_staged_state_dict=cache_staged_state_dict,
  624. overwrite=overwrite,
  625. )
  626. def stage(self, state_dict: STATE_DICT_TYPE) -> STATE_DICT_TYPE:
  627. """Override of AsyncStager.stage"""
  628. # in the async case, the state dict is already on CPU, so maintaining this
  629. # buffer makes no sense
  630. self.per_thread_copy_ahead = 0
  631. return super().stage(state_dict)