Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / distributed_checkpoint / api.py: 96%
149 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« 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"""Hyper Parallel Checkpoint API"""
17import itertools
18import os
19import threading
20import multiprocessing as mp
21from collections.abc import Callable
22from concurrent.futures import Future
23from contextlib import nullcontext
24from pathlib import Path
25from typing import Any, Optional, Union
27import torch.distributed as dist
29from hyper_parallel.core.distributed_checkpoint.async_persist import (
30 AsyncSaveResponse,
31 FileType,
32 assemble_file_path,
33 build_staged_state_dict,
34 execute_async_persist_with_gloo,
35 execute_async_persist,
36 resolve_async_persist_result,
37 gather_all_results_from_storage,
38)
39from hyper_parallel.core.distributed_checkpoint.filesystem_storage import (
40 FileSystemReader,
41 FileSystemWriter,
42)
43from hyper_parallel.core.distributed_checkpoint.metadata import (
44 Metadata,
45)
46from hyper_parallel.core.distributed_checkpoint.planner import (
47 SavePlan,
48 SavePlanner,
49 LoadPlanner,
50)
51from hyper_parallel.core.distributed_checkpoint.standard_planner import (
52 StandardSavePlanner,
53 StandardLoadPlanner,
54)
55from hyper_parallel.core.distributed_checkpoint.storage import (
56 StorageReader,
57 StorageWriter,
58)
59from hyper_parallel.core.distributed_checkpoint.broadcast import (
60 broadcast_groups_for_load,
61 DEFAULT_BROADCAST_BATCH_BYTES,
62)
63from hyper_parallel.core.distributed_checkpoint.utils import (
64 all_gather_object,
65 dcp_timer_decorator,
66 logger,
67)
69# Names the gloo persist process of each async save, so several in one job stay apart.
70_async_save_counter = itertools.count()
73@dcp_timer_decorator
74def _save_impl(
75 state_dict: dict[str, Any],
76 *,
77 checkpoint_id: Optional[Union[Path, str]] = None,
78 storage_writer: Optional[StorageWriter] = None,
79 planner: Optional[SavePlanner] = None,
80 no_dist: bool = False,
81 use_collectives: bool = True,
82 use_storage_comm: bool = False,
83) -> Metadata:
84 """Distributed checkpoint save implement(shared by :func:`save` and :func:`async_save`)."""
85 # Convert checkpoint_id to Path if it's a string
86 checkpoint_id = Path(checkpoint_id) if isinstance(checkpoint_id, str) else checkpoint_id
88 # Determine if we're in distributed mode
89 use_collectives = False if no_dist else use_collectives
90 use_storage_comm = False if not use_collectives else use_storage_comm
92 # Set up storage writer
93 if storage_writer is None:
94 if checkpoint_id is None:
95 raise ValueError("Either storage_writer or checkpoint_id must be provided")
96 storage_writer = FileSystemWriter(checkpoint_id)
97 else:
98 if checkpoint_id:
99 storage_writer.initialize_writer(checkpoint_id)
100 else:
101 checkpoint_id = getattr(storage_writer, "checkpoint_dir", None)
103 if use_storage_comm and checkpoint_id is None:
104 raise ValueError(
105 "Coordinating through the storage needs a checkpoint directory to exchange the "
106 "plans and write results in: pass checkpoint_id, or a storage_writer exposing "
107 "checkpoint_dir."
108 )
110 # Set up planner
111 planner = StandardSavePlanner() if planner is None else planner
113 # Get rank and coordinator info
114 rank = dist.get_rank()
115 world_size = dist.get_world_size()
116 is_coordinator = rank == 0
118 # Configure planner
119 planner.configure_planner(
120 state_dict=state_dict,
121 is_coordinator=is_coordinator,
122 rank=rank,
123 use_collectives=use_collectives
124 )
126 # Configure storage writer (use_collectives for rank-local metadata when False)
127 storage_writer.configure_writer(
128 is_coordinator=is_coordinator,
129 rank=rank,
130 use_collectives=use_collectives
131 )
133 @dcp_timer_decorator
134 def generate_final_plan_and_metadata() -> tuple[SavePlan, Metadata]:
135 """Build this rank's final plan and the checkpoint metadata, caching both.
137 Returns:
138 tuple[SavePlan, Metadata]: The finalized local plan and the global metadata.
139 """
140 # Build local plan
141 local_plan = planner.build_local_plan()
142 local_plan = storage_writer.optimize_local_plan(local_plan)
144 #Gather all local plans and build global plan
145 all_local_plans = gather_all_results_from_storage(checkpoint_id,
146 is_coordinator,
147 world_size,
148 local_plan,
149 FileType.LOCAL_PLAN,
150 rank) if use_storage_comm \
151 else all_gather_object(local_plan, world_size, use_collectives)
152 # build_global_plan returns this rank's plan only: every rank runs it over the same
153 # gathered plans and writes just its own shards.
154 central_plan, global_metadata = planner.build_global_plan(all_local_plans)
155 central_plan = storage_writer.optimize_global_plan(central_plan)
157 # Finalize and cache plan
158 finalized_plan = planner.finalize_plan(central_plan)
159 # Add final plan and metadata to the cache
160 if hasattr(planner, 'cache_result'):
161 planner.cache_result(finalized_plan, global_metadata)
162 return finalized_plan, global_metadata
164 cached_res = planner.get_cached() if hasattr(planner, 'get_cached') else None
165 if cached_res:
166 # Get final plan and metadata from cache
167 logger.info("Hit final plan and metadata cache.")
168 final_plan, metadata = cached_res.final_plan, cached_res.metadata
169 else:
170 # First time generating a plan and metadata.
171 final_plan, metadata = generate_final_plan_and_metadata()
173 # Write data
174 write_results = storage_writer.execute_write(final_plan, planner)
176 # Finalize checkpoint
177 all_write_results = gather_all_results_from_storage(checkpoint_id,
178 is_coordinator,
179 world_size,
180 write_results,
181 FileType.STORAGE_DATA,
182 rank) if use_storage_comm \
183 else all_gather_object(write_results, world_size, use_collectives)
184 storage_writer.finalize_checkpoint(metadata, all_write_results)
186 return metadata
189@dcp_timer_decorator
190def save(
191 state_dict: dict[str, Any],
192 *,
193 checkpoint_id: Optional[Union[Path, str]] = None,
194 storage_writer: Optional[StorageWriter] = None,
195 planner: Optional[SavePlanner] = None,
196 no_dist: bool = False,
197 use_collectives: bool = True,
198) -> Metadata:
199 """
200 Save a distributed checkpoint in SPMD style.
202 This function saves a state_dict containing DTensors, where each rank
203 only saves their local shards.
205 Args:
206 state_dict (dict[str, Any]): The state_dict to save.
207 checkpoint_id (Optional[Union[Path, str]]): The ID/path of this checkpoint instance (can be Path or str).
208 Default None.
209 storage_writer (Optional[StorageWriter]): Instance of StorageWriter. If None, FileSystemWriter
210 will be created based on checkpoint_id. Default None.
211 planner (Optional[SavePlanner]): Instance of SavePlanner. If None, StandardSavePlanner will be used.
212 Default None.
213 no_dist (bool): If True, save in single process mode. Default False.
214 use_collectives (bool): If True, use collective communication for coordination.
215 If False, each rank saves its own shard data and rank-local metadata (.metadata_rank{rank}),
216 with no cross-rank interaction. Default True.
218 Returns:
219 Metadata: Metadata object for the saved checkpoint.
220 """
221 metadata = _save_impl(
222 state_dict,
223 checkpoint_id=checkpoint_id,
224 storage_writer=storage_writer,
225 planner=planner,
226 no_dist=no_dist,
227 use_collectives=use_collectives,
228 )
229 dist.barrier()
230 return metadata
233def _create_persist_process(
234 result_queue: mp.Queue,
235 staged: dict[str, Any],
236 checkpoint_id: Optional[Union[Path, str]],
237 storage_writer: Optional[StorageWriter],
238 planner: Optional[SavePlanner],
239 no_dist: bool,
240 use_collectives: bool,
241 use_gloo: bool,
242) -> mp.Process:
243 """
244 Build the child process persisting the staged state_dict for :func:`async_save`.
246 Depending on the caller, the child either runs the plan and write result collectives on a
247 dedicated gloo group it reinitialises itself, or exchanges those results through the
248 storage, or runs without any cross-rank interaction at all.
249 Storage coordination clears old exchange files and synchronizes the callers
250 before constructing the child process.
252 Args:
253 result_queue (mp.Queue): IPC queue the child returns its status and metadata on.
254 staged (dict[str, Any]): Host resident staged state_dict to persist.
255 checkpoint_id (Optional[Union[Path, str]]): Same as :func:`async_save`.
256 storage_writer (Optional[StorageWriter]): Same as :func:`async_save`.
257 planner (Optional[SavePlanner]): Same as :func:`async_save`.
258 no_dist (bool): Same as :func:`async_save`.
259 use_collectives (bool): Same as :func:`async_save`.
260 use_gloo (bool): Same as :func:`async_save`.
262 Returns:
263 mp.Process: The persist process, not started yet.
265 Raises:
266 AssertionError: If gloo communication is requested without MASTER_ADDR or MASTER_PORT.
267 """
268 world_size = dist.get_world_size()
269 need_comm = use_collectives and not no_dist and world_size > 1
270 if not need_comm or not use_gloo:
271 use_storage_comm = need_comm and not use_gloo
272 if use_storage_comm:
273 logger.info("use storage communication for dcp async save.")
274 _cleanup_stale_communication_files(checkpoint_id, storage_writer)
275 return mp.Process(
276 target=execute_async_persist,
277 args=(
278 result_queue,
279 staged,
280 checkpoint_id,
281 storage_writer,
282 planner,
283 no_dist,
284 use_collectives,
285 use_storage_comm,
286 ),
287 name="AsyncCheckpointPersist",
288 )
290 logger.info("use Gloo communication for dcp async save.")
291 rank = dist.get_rank()
292 master_addr = os.environ.get("MASTER_ADDR", None)
293 master_port = os.environ.get("MASTER_PORT", None)
294 if master_addr is None:
295 raise AssertionError("Async DCP needs MASTER_ADDR to use prefix store")
296 if master_port is None:
297 raise AssertionError("Async DCP needs MASTER_PORT to use prefix store")
298 master_port = int(master_port)
299 save_index = next(_async_save_counter)
300 proc = mp.Process(
301 target=execute_async_persist_with_gloo,
302 args=(
303 result_queue,
304 staged,
305 checkpoint_id,
306 storage_writer,
307 planner,
308 rank,
309 world_size,
310 master_addr,
311 master_port,
312 ),
313 name=f"AsyncCheckpointPersistGloo_{save_index}",
314 )
315 return proc
318def _cleanup_stale_communication_files(
319 checkpoint_id: Optional[Union[Path, str]],
320 storage_writer: Optional[StorageWriter],
321) -> None:
322 """Remove possible stale communication files before any new persist child starts."""
323 directory = checkpoint_id if checkpoint_id is not None else getattr(storage_writer, "checkpoint_dir", None)
324 if directory is None:
325 raise ValueError("Storage-coordinated async save requires checkpoint_id or storage_writer.checkpoint_dir")
326 rank = dist.get_rank()
327 for file_type in FileType:
328 try:
329 os.remove(assemble_file_path(directory, file_type, rank))
330 except FileNotFoundError:
331 pass
332 # Complete files from a previous attempt are indistinguishable from new
333 # results until every rank has removed its own files. Admit writers together.
334 dist.barrier()
337@dcp_timer_decorator
338def async_save(
339 state_dict: dict[str, Any],
340 *,
341 checkpoint_id: Optional[Union[Path, str]] = None,
342 storage_writer: Optional[StorageWriter] = None,
343 planner: Optional[SavePlanner] = None,
344 no_dist: bool = False,
345 use_collectives: bool = True,
346 use_gloo: bool = False,
347 callback: Optional[Callable[[], None]] = None,
348) -> AsyncSaveResponse:
349 """
350 Asynchronous version of :func:`save` using a **background child process** for persistence.
352 **Staging** (tensor / DTensor → host copy) runs **synchronously in the caller
353 process** via :func:`build_staged_state_dict`, so no process pool is used for
354 staging and the training stack sees a normal Python call path. When this
355 function returns successfully, host staging is done and the original
356 ``state_dict`` may be mutated.
358 **Persistence** (plan, collectives, disk I/O) runs in **one** background
359 :class:`multiprocessing.Process` that executes :func:`_save_impl` on the staged
360 dict. A small background **thread** only joins that process and fills
361 ``persist_completion``; it does not perform tensor work.
363 Neither the thread nor the child process is a daemon, so a caller that exits with a
364 checkpoint still in flight waits for it to land rather than losing it. Making only the
365 thread a daemon would not shorten that wait either, since ``multiprocessing`` joins the
366 non-daemon child at interpreter exit anyway; it would just drop ``persist_completion``
367 and ``callback`` on the floor.
369 The staged dict and ``storage_writer`` / ``planner`` must be picklable for the
370 persist child process (same constraints as before for the worker path).
372 .. warning::
373 Experimental API. Always wait on ``persist_completion`` for a fully persisted checkpoint.
375 Args:
376 state_dict (dict[str, Any]): The state_dict to save.
377 checkpoint_id (Optional[Union[Path, str]]): Same as :func:`save`.
378 storage_writer (Optional[StorageWriter]): Same as :func:`save`.
379 planner (Optional[SavePlanner]): Same as :func:`save`.
380 no_dist (bool): Same as :func:`save`.
381 use_collectives (bool): Same as :func:`save`.
382 use_gloo(bool): Whether to use Gloo. Default False.
383 callback(Callable): Async save callback function.
385 Returns:
386 AsyncSaveResponse: Contains ``persist_completion`` only; staging is synchronous.
387 """
388 # Copy the state_dict to cpu memory for async save
389 staged = build_staged_state_dict(state_dict)
391 persist_completion: Future[Metadata] = Future()
392 result_queue: mp.Queue = mp.Queue(maxsize=1)
393 proc = _create_persist_process(
394 result_queue,
395 staged,
396 checkpoint_id,
397 storage_writer,
398 planner,
399 no_dist,
400 use_collectives,
401 use_gloo,
402 )
404 # After the async save is completed, the user callback will be executed.
405 def async_callback() -> None:
406 """Run the user callback once the save has been persisted, if one was given."""
407 if callback is not None:
408 callback()
410 # Deliberately not a daemon: it has to outlive the training loop long enough to resolve
411 # persist_completion and run callback, and killing it early would not let the process exit
412 # any sooner because the persist child is joined at interpreter exit regardless.
413 response = AsyncSaveResponse(persist_completion, process=proc, result_queue=result_queue)
414 join_thread = threading.Thread(
415 target=resolve_async_persist_result,
416 args=(proc, result_queue, response, async_callback),
417 name="AsyncCheckpointPersistJoin",
418 )
419 response.join_thread = join_thread
420 proc.start()
421 join_thread.start()
422 dist.barrier()
423 return response
426def _open_checkpoint(
427 checkpoint_id: Optional[Path],
428 storage_reader: Optional[StorageReader],
429 rank: int,
430) -> tuple[StorageReader, Metadata, bool]:
431 """
432 The reader a load goes through, and what that reader says the checkpoint holds.
434 Args:
435 checkpoint_id (Optional[Path]): Where the checkpoint is, if the caller named it.
436 storage_reader (Optional[StorageReader]): The reader to read through, or None to
437 open a file system one on ``checkpoint_id``, which the caller has checked is
438 there to open one on.
439 rank (int): This rank, which names the rank-local metadata of a checkpoint that
440 has no shared one.
442 Returns:
443 tuple[StorageReader, Metadata, bool]: The reader, the metadata, and whether that
444 metadata came from the shared ``.metadata``. A checkpoint written without
445 collectives has only a ``{rank}.metadata`` apiece, and comes back False: its ranks
446 never agreed on one description of it, so a load of it has none to plan against
447 together either.
448 """
449 if storage_reader is None:
450 storage_reader = FileSystemReader(checkpoint_id)
451 elif checkpoint_id:
452 storage_reader.initialize_reader(checkpoint_id)
454 try:
455 return storage_reader, storage_reader.load_metadata(), True
456 except FileNotFoundError:
457 return storage_reader, storage_reader.load_metadata(rank=rank), False
460def load(
461 state_dict: dict[str, Any],
462 *,
463 checkpoint_id: Optional[Union[Path, str]] = None,
464 storage_reader: Optional[StorageReader] = None,
465 planner: Optional[LoadPlanner] = None,
466 no_dist: bool = False,
467 use_collectives: bool = True,
468 broadcast_replicated_tensors: bool = True,
469 broadcast_groups: Optional[dict[tuple, Any]] = None,
470 broadcast_batch_bytes: int = DEFAULT_BROADCAST_BATCH_BYTES,
471) -> None:
472 """
473 Load a distributed checkpoint into state_dict in SPMD style.
475 Each rank will try to read the least amount of data necessary
476 to fulfill the requested state_dict. When loading DTensor instances,
477 each rank only reads data for their local shards.
479 Args:
480 state_dict (dict[str, Any]): The state_dict to load the checkpoint into (modified in-place).
481 checkpoint_id (Optional[Union[Path, str]]): The ID/path of this checkpoint instance (can be Path or str).
482 Default None.
483 storage_reader (Optional[StorageReader]): Instance of StorageReader. If None, FileSystemReader
484 will be created based on checkpoint_id. Default None.
485 planner (Optional[LoadPlanner]): Instance of LoadPlanner. If None, StandardLoadPlanner will be used.
486 Default None.
487 no_dist (bool): If True, load without cross-rank synchronization. Default False.
488 use_collectives (bool): If False, each rank loads `.metadata` or `rank.metadata`,
489 there is no communication between ranks, and each rank loads its own data. Default True,
490 matching :func:`save`. A checkpoint written without it has no shared `.metadata`, and a
491 load falls back to the rank-local one and turns this off by itself, so the default costs
492 nothing to a checkpoint that cannot use it. What it does ask, as :func:`save` already
493 does, is that **every rank of the default process group call this together**: the plan
494 exchange runs on that group, so a rank that stays out of it leaves the others waiting on
495 a gather that never completes. A rank with nothing to load still takes part, passing an
496 empty state dict. Pass False to load on some of the ranks only.
497 broadcast_replicated_tensors (bool): If True, a tensor that several ranks load identically is
498 read by one of them and sent to the rest instead of every rank reading it. Which rank
499 reads which tensor is chosen so that the reads spread evenly over the group. Default
500 True, which divides what a load takes off storage by the number of ranks holding the
501 same copy. Only consulted together with ``use_collectives``: without the plan exchange
502 there is no way to tell which ranks load the same shard, so a load that asks for this
503 without it quietly reads every copy instead, which is correct but no faster.
504 broadcast_groups (dict): The Communication groups for broadcast, keyed by rank tuple.
505 Only valid together with broadcast_replicated_tensors; built on demand when not given.
506 broadcast_batch_bytes (int): Shards smaller than this are gathered into one buffer and
507 broadcast together, so that the cost of starting a broadcast is paid once for many
508 of them rather than once each. Larger shards are sent on their own. Zero turns the
509 gathering off. Only consulted together with broadcast_replicated_tensors.
510 Every rank must pass the same value: what a rank gathers together is worked
511 out from this and from the plan, without asking anybody, so ranks that
512 disagreed would broadcast in different shapes and wait on each other.
514 Returns:
515 None. The state_dict is modified in-place.
516 """
517 # Convert checkpoint_id to Path if it's a string
518 checkpoint_id = Path(checkpoint_id) if isinstance(checkpoint_id, str) else checkpoint_id
520 # Determine if we're in distributed mode
521 use_collectives = False if no_dist else use_collectives
523 # Check the arguments
524 if broadcast_groups and not broadcast_replicated_tensors:
525 raise ValueError("broadcast_groups is only used when broadcast_replicated_tensors is True.")
526 if storage_reader is None and checkpoint_id is None:
527 raise ValueError("Either storage_reader or checkpoint_id must be provided")
529 # Set up planner
530 planner = StandardLoadPlanner() if planner is None else planner
532 # ``no_dist`` must also work in a plain Python process. Keep the real rank
533 # when a process group exists so rank-local checkpoint metadata still
534 # resolves correctly for callers inside distributed jobs.
535 if no_dist and not dist.is_initialized():
536 rank = 0
537 world_size = 1
538 else:
539 rank = dist.get_rank()
540 world_size = dist.get_world_size()
541 is_coordinator = rank == 0
543 # Open the checkpoint. One saved without collectives has no shared metadata to plan
544 # against, so a load of it cannot exchange plans however it was asked to.
545 storage_reader, metadata, shared_metadata = _open_checkpoint(checkpoint_id, storage_reader, rank)
546 use_collectives = use_collectives and shared_metadata
548 # Configure planner
549 planner.configure_planner(
550 state_dict=state_dict,
551 metadata=metadata,
552 is_coordinator=is_coordinator,
553 rank=rank,
554 broadcast_replicated_tensors=broadcast_replicated_tensors,
555 use_collectives=use_collectives,
556 )
558 # Configure storage reader
559 storage_reader.configure_reader(
560 metadata=metadata,
561 is_coordinator=is_coordinator,
562 rank=rank,
563 )
565 # Build local plan
566 local_plan = planner.build_local_plan()
567 local_plan = storage_reader.optimize_local_plan(local_plan)
569 # Gather all local plans and build global plan. Only the identity of each read is sent:
570 # the global plan matches reads across ranks on that alone, so where they come from in
571 # the checkpoint stays with the rank that will do them. This rank puts its own full plan
572 # back over what it just sent itself, since that is the one it goes on to execute.
573 all_local_plans = all_gather_object(local_plan.identity(), world_size, use_collectives)
574 all_local_plans[rank if len(all_local_plans) > 1 else 0] = local_plan
575 # build_global_plan returns this rank's plan only: every rank runs it over the same
576 # gathered plans and reads just its own shards.
577 central_plan = planner.build_global_plan(all_local_plans)
578 central_plan = storage_reader.optimize_global_plan(central_plan)
580 # Finalize plan
581 final_plan = planner.finalize_plan(central_plan)
583 # Build the groups the broadcasts go through, and destroy them once the read is
584 # done. Creating one is collective, so what decides whether to do it has to be
585 # something every rank agrees on before anybody reads -- these three are, where
586 # "does this rank hold a shared shard" is not.
587 scope = (
588 broadcast_groups_for_load(final_plan.items, broadcast_groups)
589 if broadcast_replicated_tensors and use_collectives and world_size > 1
590 else nullcontext(broadcast_groups)
591 )
593 # Execute read
594 with scope as groups:
595 storage_reader.execute_read(final_plan, planner, groups, broadcast_batch_bytes)