Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / distributed_checkpoint / async_persist.py: 77%

313 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Copyright 2026 Huawei Technologies Co., Ltd. All rights reserved. 

2# 

3# Licensed under the Apache License, Version 2.0 (the "License"); 

4# you may not use this file except in compliance with the License. 

5# You may obtain a copy of the License at 

6# 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14# ============================================================================ 

15"""Tensor staging and persist for asynchronous distributed checkpoint save. 

16 

17Staging materializes a host-side snapshot of ``state_dict`` so ``async_save`` can 

18run persistence (plan + I/O) on a copy while training continues on the original tensors. 

19""" 

20 

21import os 

22import copy 

23import pickle 

24import dataclasses 

25import queue 

26import time 

27import threading 

28import traceback 

29import multiprocessing as mp 

30from pathlib import Path 

31from multiprocessing.connection import wait 

32from enum import Enum, auto 

33from argparse import Namespace 

34from collections.abc import Callable 

35from typing import Any, Optional, Union 

36from concurrent.futures import Future, ThreadPoolExecutor 

37 

38import numpy as np 

39import torch 

40import torch.distributed as dist 

41import torch.distributed.distributed_c10d as c10d 

42 

43from hyper_parallel.core.dtensor.dtensor import DTensor 

44from hyper_parallel.core.distributed_checkpoint.metadata import ( 

45 Metadata, 

46 CHUNK_INFO, 

47) 

48from hyper_parallel.core.distributed_checkpoint.planner import ( 

49 SavePlan, 

50 SavePlanner, 

51) 

52from hyper_parallel.core.distributed_checkpoint.storage import ( 

53 StorageWriter, 

54 WriteResult, 

55) 

56from hyper_parallel.core.distributed_checkpoint.standard_planner import ( 

57 StandardSavePlanner, 

58) 

59from hyper_parallel.core.distributed_checkpoint.utils import ( 

60 dcp_timer_decorator, 

61 logger, 

62) 

63 

64_COMPLETE_FLAG = b"\x00__PICKLE_WRITE_COMPLETE__\x00" 

65 

66# The join wait sits in the *training* process for as long as the child persists, 

67# so it blocks on the queue with a timeout rather than spinning. 

68_PERSIST_RESULT_POLL_SECONDS = 0.1 

69 

70 

71class DataCopier: 

72 """Type dispatched copy of ``state_dict`` values into host memory. 

73 

74 Copy handlers are registered per type through :meth:`register`; :meth:`copy` resolves the 

75 handler of an object by exact type first and by ``isinstance`` afterwards, falling back to 

76 a generic recursive deep copy for objects no handler was registered for. 

77 """ 

78 

79 _registry = {} 

80 

81 @classmethod 

82 def register(cls, *types: type) -> Callable: 

83 """Register the decorated function as the copy handler of every type given. 

84 

85 Args: 

86 *types (type): Types the handler is responsible for. 

87 

88 Returns: 

89 Callable: Decorator recording the handler and returning it unchanged. 

90 """ 

91 def decorator(func: Callable) -> Callable: 

92 """Record ``func`` against every registered type and hand it back.""" 

93 for t in types: 

94 cls._registry[t] = func 

95 return func 

96 

97 return decorator 

98 

99 @classmethod 

100 def dispatch(cls, obj: Any) -> Optional[Callable]: 

101 """ 

102 Resolve the copy handler of ``obj``: its exact type first, its most derived 

103 registered base class afterwards. 

104 

105 Registration order must not decide the handler. ``DTensor`` is registered after 

106 ``torch.Tensor`` and is a subclass of it, so scanning in registration order would 

107 hand a ``DTensor`` subclass to the plain tensor handler, staging it as a bare local 

108 tensor with its mesh and placements dropped. 

109 

110 Args: 

111 obj (Any): Object to find a copy handler for. 

112 

113 Returns: 

114 Optional[Callable]: The handler, or None when no registered type matches. 

115 """ 

116 if type(obj) in cls._registry: 

117 return cls._registry[type(obj)] 

118 

119 best_type = None 

120 for r_type in cls._registry: 

121 if not isinstance(obj, r_type): 

122 continue 

123 # Unrelated matches (neither one a subclass of the other) keep the first found. 

124 if best_type is None or issubclass(r_type, best_type): 

125 best_type = r_type 

126 return cls._registry[best_type] if best_type is not None else None 

127 

128 @classmethod 

129 def copy(cls, obj: Any) -> Any: 

130 """ 

131 Copy ``obj`` with its registered handler, or with a generic deep copy as fallback. 

132 

133 Args: 

134 obj (Any): Object to copy, of any type held by a state dict. 

135 

136 Returns: 

137 Any: Copy of ``obj``, with tensor leaves residing in host memory. 

138 """ 

139 copy_func = cls.dispatch(obj) 

140 if copy_func: 

141 return copy_func(obj) 

142 logger.warning( 

143 "The user define object %s not implement copy method and register " 

144 "to DataCopier. So, the general copy method will be used, which may cause " 

145 "unexpected copy behavior and incorrect data storage. Please verify this on your own.", 

146 type(obj)) 

147 return cls._copy_others(obj) 

148 

149 @staticmethod 

150 def _copy_others(obj): 

151 obj_c = copy.deepcopy(obj) 

152 for name, value in obj_c.__dict__.items(): 

153 if callable(value): 

154 continue 

155 setattr(obj_c, name, DataCopier.copy(value)) 

156 return obj_c 

157 

158 

159def _copy_tensor_to_cpu(tensor: torch.Tensor) -> torch.Tensor: 

160 """Return a host-memory copy of a tensor, detached from autograd.""" 

161 t = tensor.detach().to("cpu", copy=True) 

162 if hasattr(tensor, CHUNK_INFO): 

163 setattr(t, CHUNK_INFO, getattr(tensor, CHUNK_INFO)) 

164 return t 

165 

166 

167@DataCopier.register(int, float, complex, bool, str, type(None), Enum, torch.dtype) 

168def _copy_const(obj): 

169 return obj 

170 

171 

172@DataCopier.register(bytes, bytearray) 

173def _copy_bytes(obj): 

174 return bytes(obj) 

175 

176 

177@DataCopier.register(np.ndarray) 

178def _copy_ndarray(obj): 

179 return obj.copy() 

180 

181 

182@DataCopier.register(torch.Tensor) 

183def _copy_tensor(obj): 

184 result = _copy_tensor_to_cpu(obj) 

185 return result 

186 

187 

188@DataCopier.register(DTensor) 

189def _copy_dtensor(obj): 

190 """Stage a DTensor by copying its local shard to host memory, keeping mesh and placements.""" 

191 staged_local = _copy_tensor_to_cpu(obj.to_local()) 

192 # ``shape`` is required for RaggedShard: an unevenly-sharded DTensor cannot 

193 # recover its logical global shape from the local shard alone. 

194 result = DTensor.from_local( 

195 staged_local, 

196 obj.device_mesh, 

197 obj.placements, 

198 shape=tuple(obj.shape), 

199 ) 

200 return result 

201 

202 

203@DataCopier.register(Namespace) 

204def _copy_namespace(obj): 

205 c = DataCopier.copy(vars(obj)) 

206 return Namespace(**c) 

207 

208 

209@DataCopier.register(list) 

210def _copy_list(obj): 

211 result = [DataCopier.copy(item) for item in obj] 

212 return result 

213 

214 

215@DataCopier.register(tuple) 

216def _copy_tuple(obj): 

217 result = tuple(DataCopier.copy(item) for item in obj) 

218 return result 

219 

220 

221@DataCopier.register(dict) 

222def _copy_dict(obj): 

223 result = {} 

224 for k, v in obj.items(): 

225 result[DataCopier.copy(k)] = DataCopier.copy(v) 

226 return result 

227 

228 

229class AsyncPersistStatus(Enum): 

230 """Queue payload status from :func:`_async_persist_worker` to the parent join thread.""" 

231 

232 SUCCESS = auto() 

233 FAILURE = auto() 

234 

235 

236class FileType(Enum): 

237 

238 LOCAL_PLAN = auto() 

239 STORAGE_DATA = auto() 

240 

241 

242@dataclasses.dataclass 

243class AsyncSaveResponse: 

244 """Result of :func:`async_save`. 

245 

246 Host staging runs synchronously before :func:`async_save` returns; only checkpoint 

247 **persistence** is asynchronous. ``persist_completion`` completes when the child 

248 process finishes :func:`_save_impl` (plan, collectives, disk I/O) and supplies 

249 :class:`Metadata`. 

250 """ 

251 

252 persist_completion: Future[Metadata] 

253 process: Any = dataclasses.field(default=None, repr=False) 

254 join_thread: Any = dataclasses.field(default=None, repr=False) 

255 result_queue: Any = dataclasses.field(default=None, repr=False) 

256 _finalize_lock: Any = dataclasses.field(default_factory=threading.Lock, repr=False) 

257 

258 def finalize(self, result: Any, async_callback: Callable, exitcode: int) -> None: 

259 """Publish one persistence result under the same lock used by abort.""" 

260 with self._finalize_lock: 

261 if self.persist_completion.done(): 

262 return 

263 

264 if result is None: 

265 self.persist_completion.set_exception( 

266 RuntimeError( 

267 f"async_persist process exited with code {exitcode} and no result on queue" 

268 ) 

269 ) 

270 return 

271 

272 status, payload = result 

273 if status == AsyncPersistStatus.SUCCESS: 

274 try: 

275 # Future waiters can immediately start the next save, so publish 

276 # and restore its reusable plans before signalling completion. 

277 async_callback() 

278 StandardSavePlanner.cached_save_result.update(payload[1]) 

279 except Exception as exc: # pylint: disable=broad-except 

280 self.persist_completion.set_exception(exc) 

281 else: 

282 self.persist_completion.set_result(payload[0]) 

283 elif status == AsyncPersistStatus.FAILURE: 

284 # The child sends a formatted traceback rather than an exception 

285 # object; preserve that text in the error observed by Future waiters. 

286 self.persist_completion.set_exception(RuntimeError(payload)) 

287 else: 

288 self.persist_completion.set_exception( 

289 RuntimeError(f"async_persist queue returned unexpected status: {status!r}") 

290 ) 

291 

292 def abort(self, timeout: float = 5.0) -> None: 

293 """Discard unfinished persistence and reap its resources before recovery. 

294 

295 Args: 

296 timeout: Maximum seconds for each termination or join attempt. 

297 

298 Raises: 

299 RuntimeError: A process or result thread could not be stopped. 

300 """ 

301 # Cancellation and publication share a lock: after this returns, no late 

302 # callback can publish latest or repopulate the plan cache during rollback. 

303 if not self._finalize_lock.acquire(timeout=timeout): 

304 raise RuntimeError("async checkpoint publication did not finish before recovery") 

305 try: 

306 self.persist_completion.cancel() 

307 finally: 

308 self._finalize_lock.release() 

309 if self.process is not None: 

310 if self.process.is_alive(): 

311 self.process.terminate() 

312 self.process.join(timeout) 

313 if self.process.is_alive(): 

314 self.process.kill() 

315 self.process.join(timeout) 

316 if self.process.is_alive(): 

317 raise RuntimeError("async checkpoint process did not stop") 

318 if self.join_thread is not None: 

319 self.join_thread.join(timeout) 

320 if self.join_thread.is_alive(): 

321 raise RuntimeError("async checkpoint result thread did not stop") 

322 if self.result_queue is not None: 

323 self.result_queue.close() 

324 

325 def get_result(self, timeout: int = None) -> Optional[Metadata]: 

326 """Wait for the save to be persisted and return its metadata. 

327 

328 Args: 

329 timeout (int): Seconds to wait. Default ``None``, which waits indefinitely. 

330 

331 Returns: 

332 Optional[Metadata]: Metadata of the persisted checkpoint. 

333 """ 

334 return self.persist_completion.result(timeout=timeout) 

335 

336 

337@dcp_timer_decorator 

338def build_staged_state_dict(state_dict: dict[str, Any]) -> dict[str, Any]: 

339 """ 

340 Build a deep structural copy of ``state_dict`` with tensor / DTensor data 

341 copied to host memory so the original can be mutated while checkpoint I/O runs. 

342 

343 Uses the same flattening rules as :class:`StandardSavePlanner`. 

344 

345 Args: 

346 state_dict (dict[str, Any]): Nested or flat training state dict. 

347 

348 Returns: 

349 dict[str, Any]: New dict with identical nesting and keys; tensor leaves are staging copies. 

350 """ 

351 return DataCopier.copy(state_dict) 

352 

353 

354def _start_parent_monitor() -> None: 

355 """Exit an orphaned persist child when its training worker dies.""" 

356 parent = mp.parent_process() 

357 if parent is None: 

358 return 

359 

360 def _watch() -> None: 

361 wait([parent.sentinel]) 

362 # The worker may have been SIGKILLed, so Python finalizers cannot be 

363 # relied on to stop a child blocked on another rank's checkpoint files. 

364 os._exit(1) 

365 

366 threading.Thread(target=_watch, name="AsyncCheckpointParentMonitor", daemon=True).start() 

367 

368 

369def cleanup_and_reinit_process_group( 

370 master_addr: str, 

371 master_port: int, 

372 rank: int, 

373 world_size: int, 

374) -> None: 

375 """ 

376 Cleanup hccl process group and reinitialize gloo process group. 

377 

378 Args: 

379 master_addr (str): Address of the rendezvous the new group meets at. 

380 master_port (int): Port of that rendezvous. 

381 rank (int): Rank of this process in the new group. 

382 world_size (int): Number of processes in the new group. 

383 """ 

384 # Resetting the private c10d state is the only way to drop the process group inherited 

385 # from the parent process, so the accesses below are deliberate. 

386 # pylint: disable=protected-access 

387 

388 # Step 1: clear C++ ProcessGroupRegistry (avoids "already registered" error). 

389 if hasattr(c10d, "_unregister_all_process_groups"): 

390 try: 

391 c10d._unregister_all_process_groups() 

392 except Exception: # pylint: disable=broad-except 

393 pass 

394 

395 # Step 2: reset Python-layer _world to an uninitialised state. 

396 if hasattr(c10d, "_World"): 

397 try: 

398 c10d._world = c10d._World() 

399 except Exception: # pylint: disable=broad-except 

400 pass 

401 # Also reset the module-level init-method string (present in all versions). 

402 if hasattr(c10d, "_default_pg_init_method"): 

403 c10d._default_pg_init_method = None 

404 for attr in ("_default_pg", "_pg_map", "_pg_names", "_pg_group_ranks", 

405 "_pg_backend_config", "_group_count", "_tags_to_pg", 

406 "_pg_to_tag"): 

407 if not hasattr(c10d, attr): 

408 continue 

409 old_val = getattr(c10d, attr) 

410 if isinstance(old_val, dict): 

411 setattr(c10d, attr, {}) 

412 elif isinstance(old_val, int): 

413 setattr(c10d, attr, 0) 

414 else: 

415 setattr(c10d, attr, None) 

416 

417 # Step 3: build a fresh TCPStore on the dedicated gloo port and init. 

418 # rank-0 child is the store master; all others connect as clients. 

419 store = dist.PrefixStore( 

420 prefix=mp.current_process().name, 

421 store=dist.TCPStore( 

422 host_name=master_addr, 

423 port=master_port 

424 ), 

425 ) 

426 

427 # Step 4: init new process group with backend "gloo". 

428 dist.init_process_group( 

429 backend="gloo", 

430 store=store, 

431 rank=rank, 

432 world_size=world_size, 

433 ) 

434 

435 

436@dcp_timer_decorator 

437def execute_async_persist_with_gloo( 

438 result_queue: mp.Queue, 

439 staged: dict[str, Any], 

440 checkpoint_id: Optional[Union[Path, str]], 

441 storage_writer: Optional[StorageWriter], 

442 planner: Optional[SavePlanner], 

443 rank: int, 

444 world_size: int, 

445 master_addr: str, 

446 master_port: int, 

447) -> None: 

448 """Child-process entry for gloo-based async save. 

449 Reinitialises a **CPU-only gloo process group** on a dedicated port so that 

450 all collective communication (all_gather_object for plan exchange, 

451 all_gather_object for write_results) can run inside the child process, 

452 exactly mirroring what :func:`_save_impl` does synchronously. 

453 The parent process only stages tensors to CPU; all planning, collectives, 

454 disk I/O and metadata finalisation happen here. 

455 Design rationale 

456 ---------------- 

457 * The training group uses NCCL (or hccl on Ascend) and lives in C++ global 

458 state that is invalidated across ``fork``. We never touch it. 

459 * A fresh ``gloo`` group is initialised via a ``TCPStore`` client on the training 

460 rendezvous itself (``master_addr:master_port``), namespaced by a ``PrefixStore`` 

461 keyed on this process name. The name carries a per-``async_save`` counter, so each 

462 save gets its own key space on the same store; every rank must therefore reach the 

463 same number of gloo saves, or the prefixes diverge and the rendezvous hangs. 

464 * After :func:`_save_impl` completes the gloo group is destroyed so resources 

465 are released cleanly. 

466 

467 Args: 

468 result_queue: IPC queue for returning status / metadata to parent join thread. 

469 staged: CPU-resident staged state dict (output of build_staged_state_dict). 

470 checkpoint_id: Checkpoint directory path. 

471 storage_writer: Pre-constructed StorageWriter (or None → FileSystemWriter). 

472 planner: Pre-constructed SavePlanner (or None → StandardSavePlanner). 

473 rank: Global rank of this process (inherited from parent). 

474 world_size: Total world size (inherited from parent). 

475 master_addr: TCP rendezvous address for the gloo store. 

476 master_port: Training master port; the child connects to that store as a client. 

477 """ 

478 # ``api`` imports this module at load time, so this import stays function local: that is 

479 # what keeps the two from importing each other at load time. 

480 from hyper_parallel.core.distributed_checkpoint.api import _save_impl # pylint: disable=import-outside-toplevel 

481 _start_parent_monitor() 

482 try: 

483 # Clear the original communication group information and establish the gloo communication. 

484 cleanup_and_reinit_process_group( 

485 master_addr, 

486 master_port, 

487 rank, 

488 world_size 

489 ) 

490 meta = _save_impl( 

491 staged, 

492 checkpoint_id=checkpoint_id, 

493 storage_writer=storage_writer, 

494 planner=planner, 

495 ) 

496 # The plan cache is also returned and can be reused for the next dcp async save. 

497 result_queue.put((AsyncPersistStatus.SUCCESS, (meta, StandardSavePlanner.cached_save_result))) 

498 except Exception: # pylint: disable=broad-except 

499 result_queue.put((AsyncPersistStatus.FAILURE, traceback.format_exc())) 

500 finally: 

501 # Clean up the gloo group we created; ignore errors (process is exiting). 

502 if dist.is_initialized(): 

503 dist.destroy_process_group() 

504 

505 

506@dcp_timer_decorator 

507def execute_async_persist( 

508 result_queue: mp.Queue, 

509 staged: dict[str, Any], 

510 checkpoint_id: Optional[Union[Path, str]], 

511 storage_writer: Optional[StorageWriter], 

512 planner: Optional[SavePlanner], 

513 no_dist: bool, 

514 use_collectives: bool, 

515 use_storage_comm: bool, 

516) -> None: 

517 """ 

518 Perform asynchronous flushing to disk, 

519 which is not suitable for collective communication, 

520 or use the file system for collective communication. 

521 

522 Args: 

523 result_queue: IPC queue for returning status / metadata to parent join thread. 

524 staged: CPU-resident staged state dict (output of build_staged_state_dict). 

525 checkpoint_id: Checkpoint directory path. 

526 storage_writer: Pre-constructed StorageWriter (or None → FileSystemWriter). 

527 planner: Pre-constructed SavePlanner (or None → StandardSavePlanner). 

528 no_dist: Whether it is a distributed scenario or a standalone scenario. 

529 use_collectives: Total world size (inherited from parent). 

530 use_storage_comm: TCP rendezvous address for the gloo store. 

531 """ 

532 # ``api`` imports this module at load time, so this import has to stay function local. 

533 from hyper_parallel.core.distributed_checkpoint.api import _save_impl # pylint: disable=import-outside-toplevel 

534 _start_parent_monitor() 

535 try: 

536 meta = _save_impl( 

537 staged, 

538 checkpoint_id=checkpoint_id, 

539 storage_writer=storage_writer, 

540 planner=planner, 

541 no_dist=no_dist, 

542 use_collectives=use_collectives, 

543 use_storage_comm=use_storage_comm 

544 ) 

545 # The plan cache is also returned and can be reused for the next dcp async save. 

546 result_queue.put((AsyncPersistStatus.SUCCESS, (meta, StandardSavePlanner.cached_save_result))) 

547 except Exception: # pylint: disable=broad-except 

548 result_queue.put((AsyncPersistStatus.FAILURE, traceback.format_exc())) 

549 

550 

551def resolve_async_persist_result( 

552 proc: mp.Process, 

553 result_queue: mp.Queue, 

554 response: AsyncSaveResponse, 

555 async_callback: Callable[[], None], 

556) -> None: 

557 """Resolve a persist child's result without publishing cancelled saves. 

558 

559 Runs in the training process's result thread. Receive the child's result and 

560 wait for it to exit. On success, run the publication callback and merge the 

561 child's plan cache before completing ``response.persist_completion`` with the 

562 checkpoint metadata. Child failures, missing results, unexpected statuses and 

563 callback errors are recorded on that Future for the caller to observe. 

564 

565 Args: 

566 proc: Started child process performing checkpoint persistence. 

567 result_queue: IPC queue carrying the child's status and result payload. 

568 response: Save task holding the completion Future and finalization lock. 

569 async_callback: Collective-free callback publishing the completed save. 

570 

571 Note: 

572 Finalization shares a lock with ``AsyncSaveResponse.abort()``. If abort 

573 cancels the Future first, discard the result without publishing or 

574 updating the plan cache. If finalization acquires the lock first, abort 

575 waits for publication and Future completion before proceeding. 

576 """ 

577 result = None 

578 # Read before joining: a child may wait for its queue feeder to flush a large 

579 # payload. Timed reads also detect children that exit without returning one. 

580 while result is None: 

581 try: 

582 result = result_queue.get(timeout=_PERSIST_RESULT_POLL_SECONDS) 

583 except queue.Empty: 

584 if proc.is_alive(): 

585 continue 

586 # The child may have put its result and exited while the wait above was 

587 # timing out, so look once more before giving up on it. 

588 try: 

589 result = result_queue.get_nowait() 

590 except queue.Empty: 

591 pass 

592 break 

593 

594 proc.join() 

595 # Abort may race a result already received above. Keep the Future check, 

596 # publication and cache update under the same lock as cancellation. 

597 response.finalize(result, async_callback, proc.exitcode) 

598 

599 

600def batch_read_worker(file_batch: tuple[int], checkpoint_id: str, file_type: FileType) -> list: 

601 """ 

602 Read one batch of files, waiting for the files that the other ranks have not written yet. 

603 

604 Args: 

605 file_batch (tuple[int]): Contiguous file ids this worker is responsible for. 

606 checkpoint_id (str): Checkpoint directory holding the files. 

607 file_type (FileType): Which kind of file to read, local plan or storage data. 

608 

609 Returns: 

610 list: Content of every file of ``file_batch``, in the order of the batch. 

611 

612 Raises: 

613 TimeoutError: If some files are still unreadable after 1800 seconds. 

614 """ 

615 results = [None] * len(file_batch) 

616 file_to_read = file_batch 

617 first_file_id = file_batch[0] 

618 

619 # Read files in a round-robin manner, 

620 # If a file has not been generated yet, skip it and proceed to the next file. 

621 # Until all files have been read. 

622 timeout = 1800 

623 deadline = time.monotonic() + timeout 

624 while True: 

625 if not file_to_read: 

626 break 

627 if time.monotonic() > deadline: 

628 raise TimeoutError( 

629 f"After waiting for 1800 seconds, " 

630 f"the {file_type.name} files: {file_to_read} still have not been read completely." 

631 ) 

632 file_not_read = [] 

633 for file_id in file_to_read: 

634 ret = load_file(checkpoint_id, file_type, file_id) 

635 if ret is None: 

636 file_not_read.append(file_id) 

637 else: 

638 results[file_id - first_file_id] = ret 

639 file_to_read = tuple(file_not_read) 

640 

641 return results 

642 

643 

644@dcp_timer_decorator 

645def parallel_read_files( 

646 file_list: tuple[int], 

647 checkpoint_id: str, 

648 file_type: FileType, 

649 max_workers: int = 32 

650) -> list: 

651 """ 

652 Split the total file list into multiple batches 

653 based on the number of parallel threads, 

654 then perform multi-threaded parallel reading to improve read efficiency. 

655 """ 

656 if not file_list: 

657 return [] 

658 

659 batches, max_workers = construct_file_batches(file_list, max_workers) 

660 logger.info( 

661 "parallel read files, file type: %s, file count: %d, max read workers: %d", 

662 file_type.name, len(file_list), max_workers 

663 ) 

664 

665 # Use the thread pool to read data concurrently, improving the read efficiency. 

666 with ThreadPoolExecutor(max_workers=max_workers) as executor: 

667 all_results = tuple( 

668 executor.map(lambda b: batch_read_worker(b, checkpoint_id, file_type), batches) 

669 ) 

670 return [result for batch_results in all_results for result in batch_results] 

671 

672 

673def construct_file_batches(file_list: tuple[int], max_workers: int) -> (list[tuple[int]], int): 

674 """ 

675 Split the total file list into multiple batches 

676 based on the number of parallel threads 

677 """ 

678 n = len(file_list) 

679 max_workers = min(max_workers, n) 

680 if max_workers == 0: 

681 raise ValueError("Max workers number for parallel read batch file is 0!") 

682 batch_size = (n + max_workers - 1) // max_workers 

683 # Split the file list into max_workers sublists. 

684 batches = [ 

685 file_list[i * batch_size: (i + 1) * batch_size] 

686 for i in range(max_workers) 

687 ] 

688 batches = [b for b in batches if b] 

689 return batches, max_workers 

690 

691 

692@dcp_timer_decorator 

693def gather_all_results_from_storage( 

694 checkpoint_id: str, 

695 is_coordinator: bool, 

696 world_size: int, 

697 results: Union[SavePlan, WriteResult], 

698 file_type: FileType, 

699 file_id: int 

700) -> list: 

701 """ 

702 All node data is collected from the storage, 

703 which is classified into local plan and storage data. 

704 In the first step, each rank writes its own data. 

705 In the second step, for local plan, each rank reads the file written by all ranks. 

706 For storage data, only rank 0 reads the file written by all ranks. 

707 """ 

708 logger.info("gather all results from storage, file type: %s", file_type.name) 

709 write_file(checkpoint_id, file_type, file_id, results) 

710 if not is_coordinator and file_type != FileType.LOCAL_PLAN: 

711 return [] 

712 

713 # For LOCAL_PLAN, each node has 16 rank processes reading simultaneously. 

714 if file_type == FileType.LOCAL_PLAN: 

715 max_workers = min(16, max(os.cpu_count() // 32, 1)) 

716 else: 

717 max_workers = min(64, max(os.cpu_count() // 2, 1)) 

718 file_list = tuple(range(0, world_size)) 

719 gathered = parallel_read_files(file_list, 

720 checkpoint_id, 

721 file_type, 

722 max_workers=max_workers) 

723 return gathered 

724 

725 

726def assemble_file_path(checkpoint_id: str, file_type: FileType, file_id: int) -> str: 

727 """ 

728 Assemble file path to exchanges its results through. 

729 

730 Args: 

731 checkpoint_id (str): Checkpoint directory holding the exchange files. 

732 file_type (FileType): Which kind of file, local plan or storage data. 

733 file_id (int): Rank that owns the file. 

734 

735 Returns: 

736 str: Path of that rank's file. 

737 """ 

738 return f"{checkpoint_id}/{file_type.name}_{file_id}.pkl" 

739 

740 

741def _safe_remove_file(file_path: str) -> None: 

742 """ 

743 Delete a file that has been read, without letting the delete fail the load. 

744 

745 What it held has already been read, so a file that will not go is a leftover worth a 

746 warning rather than a reason to fail a save that has its data. One attempt is enough: 

747 what refuses here - a read-only mount, a directory this rank may not write in - does 

748 not clear by asking again. 

749 

750 Args: 

751 file_path (str): File to delete. 

752 """ 

753 try: 

754 os.remove(file_path) 

755 except FileNotFoundError: 

756 pass 

757 except Exception as e: # pylint: disable=broad-except 

758 logger.warning( 

759 "Could not remove the checkpoint exchange file %s, because the error: %s", file_path, e 

760 ) 

761 

762 

763def load_file(checkpoint_id: str, file_type: FileType, file_id: int) -> Any: 

764 """ 

765 Reads files from the storage. 

766 Currently, this function is mainly used to 

767 asynchronously save local plan and storage data files. 

768 

769 Args: 

770 checkpoint_id (str): Checkpoint directory holding the file. 

771 file_type (FileType): Which kind of file to read, local plan or storage data. 

772 file_id (int): Id of the file within that kind. 

773 

774 Returns: 

775 Any: The unpickled content of the file. 

776 """ 

777 file_path = assemble_file_path(checkpoint_id, file_type, file_id) 

778 

779 try: 

780 with open(file_path, "rb") as f: 

781 flag_len = len(_COMPLETE_FLAG) 

782 f.seek(0, os.SEEK_END) 

783 size = f.tell() 

784 # determining whether the file length is greater than the flag length 

785 if size < flag_len: 

786 return None 

787 f.seek(size - flag_len) 

788 # determining whether the file has a write complete flag 

789 if f.read(flag_len) != _COMPLETE_FLAG: 

790 return None 

791 f.seek(0) 

792 result = pickle.load(f) 

793 except FileNotFoundError: 

794 # The rank that owns this file has not written it yet; the caller comes back round. 

795 return None 

796 

797 # Other ranks may still be reading LOCAL_PLAN, so only delete STORAGE_DATA here. 

798 if file_type == FileType.STORAGE_DATA: 

799 _safe_remove_file(file_path) 

800 return result 

801 

802 

803@dcp_timer_decorator 

804def write_file( 

805 checkpoint_id: str, 

806 file_type: FileType, 

807 file_id: int, 

808 content: Union[SavePlan, WriteResult], 

809) -> None: 

810 """ 

811 Write files to the storage. 

812 Currently, this function is mainly used to 

813 asynchronously save local plan and storage data files. 

814 

815 Args: 

816 checkpoint_id (str): Checkpoint directory to write into. 

817 file_type (FileType): Which kind of file to write, local plan or storage data. 

818 file_id (int): Id of the file within that kind. 

819 content (Union[SavePlan, WriteResult]): What to pickle into it. 

820 """ 

821 final_path = assemble_file_path(checkpoint_id, file_type, file_id) 

822 

823 # To avoid read-write conflicts, the completion flag is appended last: a reader that 

824 # opens the file mid-write finds no flag at the end and retries on its next round. 

825 with open(final_path, "wb") as f: 

826 pickle.dump(content, f, protocol=pickle.HIGHEST_PROTOCOL) 

827 f.write(_COMPLETE_FLAG) 

828 

829 logger.info("write file type: %s, file path: %s", file_type.name, final_path)