Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / distributed_checkpoint / broadcast.py: 92%
142 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"""Sending a shard one rank read to the ranks that hold a copy of it.
17A checkpoint holds one copy of a replicated parameter, so on load exactly one rank of each
18replica set reads it and broadcasts it to the others. This module owns that half of a load:
19the communication groups it goes through, the sends themselves, and the batching that keeps
20small shards from each costing a round trip.
21"""
22from collections import deque
23from contextlib import contextmanager
24from typing import Any, Iterable, Optional, Union
26import torch
27import torch.distributed as dist
28from torch.distributed.distributed_c10d import _get_default_group
30from hyper_parallel.core.distributed_checkpoint.metadata import MetadataIndex
31from hyper_parallel.core.distributed_checkpoint.planner import BroadcastSource, ReadItem
32from hyper_parallel.core.distributed_checkpoint.ragged import get_ragged_box_tensor
33from hyper_parallel.core.distributed_checkpoint.utils import (
34 all_gather_object,
35 get_tensor_storage_size,
36 logger,
37)
38from hyper_parallel.core.dtensor.dtensor import DTensor
39from hyper_parallel.high_availability.group_registry import GroupRegistry
40from hyper_parallel.core.utils.communication import EXISTING_COMM_GROUPS
43def copy_each(dests: list, srcs: list) -> None:
44 """
45 Copy every pair in one fused operation rather than one at a time.
47 Measured on an Ascend card, five hundred copies of 64 KiB take 11.8 ms one at a
48 time and 1.4 ms fused: nearly all of what a small copy costs is starting it.
50 Args:
51 dests (list): Tensors written into.
52 srcs (list): Tensors read from, pairing with ``dests`` by position.
53 """
54 if dests:
55 torch._foreach_copy_(dests, srcs) # pylint: disable=protected-access
58def get_created_group(rank_list: Union[list[int], tuple[int, ...]]) -> Any:
59 """
60 The process group over these ranks that the process-wide cache already holds.
62 Args:
63 rank_list (Union[list[int], tuple[int, ...]]): The ranks the group would hold.
65 Returns:
66 Any: The cached group, or None when the cache holds none over these ranks.
67 """
68 return EXISTING_COMM_GROUPS.get(str(tuple(sorted(rank_list))))
71def synchronize() -> None:
72 """
73 Block the host until the work queued on the current device stream has finished.
75 Nothing can be queued on a device stream when the process has no device, and there are
76 two ways to have none: a CPU-only install carries no ``torch.npu`` at all, and a gloo run
77 on an accelerator box never initializes the one it has.
78 """
79 device = getattr(torch, "npu", None)
80 if device is None or not device.is_initialized():
81 return
82 device.current_stream().synchronize()
85# How many broadcasts one rank keeps going at once. Starting the next without waiting on
86# the last is what lets a read overlap the send before it, but each one in flight holds
87# resources inside the communication library, so the count is capped rather than left to
88# grow with the number of shards in the checkpoint.
89_MAX_BROADCASTS_IN_FLIGHT = 8
91# Shards smaller than this travel together rather than one at a time. A broadcast of
92# 64 KiB costs about as much as one of 1 MiB -- some 145 microseconds either way over
93# four Ascend ranks -- and only reaches full speed past a few megabytes, so below that a
94# load spends its time starting broadcasts rather than moving data. This sits just above
95# where the two meet, measured at around 4.6 MiB. Note that a batch is held until its
96# broadcast lands, so a load can have this much times the in-flight limit set aside.
97DEFAULT_BROADCAST_BATCH_BYTES = 6 * 1024 * 1024
100def _existing_group(group_ranks: tuple) -> Any:
101 """
102 A communication group over these ranks that is already there, or None if none is.
104 The cache is where a group that already exists is normally found: the mesh a model is
105 sharded over puts its tp columns and dp groups there, and they stay because training
106 still needs them. Only when it holds nothing is the world worth considering - a
107 parameter every rank has a copy of needs the group of every rank, which is the one the
108 job runs on. That one has been there since initialization and is not in the cache, but
109 it is no less already there, and remaking it would raise a second communicator over
110 every rank for the sake of one read.
112 Neither belongs to the load, so neither is destroyed when the load is done.
114 Args:
115 group_ranks (tuple): The ranks the group would hold.
117 Returns:
118 Any: The group, or None if it has to be created.
119 """
120 existing = get_created_group(group_ranks)
121 if existing is not None:
122 return existing
123 if group_ranks == tuple(range(dist.get_world_size())):
124 return _get_default_group()
125 return None
128def _build_broadcast_groups(
129 items: Iterable[ReadItem],
130 supplied: dict[tuple, Any],
131) -> tuple[dict[tuple, Any], set]:
132 """
133 The communication group of every shard this load broadcasts, and which of them it owns.
135 Every rank has to call this, including one with no shard to broadcast at all: it
136 all-gathers what is needed and takes part in creating all of it, and both of those are
137 collective. A rank that stayed out because it had nothing of its own to add would leave
138 the others waiting on it.
140 A group that already exists is reused rather than made a second time - the mesh a model
141 is sharded over has usually built the tp column or the dp group a replicated parameter
142 needs. But **whether to reuse has to be decided the same way on every rank**:
143 ``new_group`` is collective over the world, so a rank that skipped it because its own
144 cache held the group, while another went ahead, would hang everybody. The cache is not
145 symmetric on its own - ``DeviceMesh.from_group`` records only the group its rank is in -
146 so the decision is taken from the gathered reports rather than from the local cache: a
147 group is made afresh if it is absent on *any* rank that needs it, and reused only when
148 it is absent on none.
150 Groups made here are made with :func:`torch.distributed.new_group`, which creates exactly
151 the ranks it is given and hands the group straight back. The project's ``create_group``
152 would do more than is wanted: it takes the rank list as a *template*, expands it into a
153 whole partition of the world, and keeps every group of it in a process-wide cache. A load
154 uses each of these groups once - and the expansion refuses rank lists a pipeline-parallel
155 model produces, such as a parameter tied across two stages that are not neighbours.
157 Args:
158 items (Iterable[ReadItem]): The read items of this rank finalized plan.
159 supplied (dict[tuple, Any]): Communication groups the caller pre-built, keyed by
160 their rank tuple. Kept as they are and never counted as owned.
162 Returns:
163 tuple[dict[tuple, Any], set]: A group for every rank tuple this rank broadcasts
164 through, and the rank tuples whose groups this load made and must destroy.
165 """
166 needed = sorted({item.source.group_ranks for item in items
167 if item.source is not None and item.source.group_ranks not in supplied})
168 absent = tuple(ranks for ranks in needed if _existing_group(ranks) is None)
169 if absent:
170 logger.warning("There are missing groups %s. Then all gather the missing groups on each rank and "
171 "create them one by one, which will increase some time consumption.", absent)
173 gathered = all_gather_object(
174 (tuple(needed), absent), dist.get_world_size(), use_collectives=True
175 )
176 wanted = sorted({ranks for reported, _ in gathered for ranks in reported})
177 absent_somewhere = {ranks for _, reported in gathered for ranks in reported}
179 groups = dict(supplied)
180 owned = set()
181 create_group = dist.new_group
182 registry = getattr(create_group, "__self__", None)
183 if isinstance(registry, GroupRegistry):
184 # These groups are destroyed when loading finishes, so they must not
185 # enter the persistent recovery catalog or its sealed-group checks.
186 create_group = registry.call_original_new_group
187 for group_ranks in wanted:
188 # Both inputs to this came from the gather, so every rank takes the same branch.
189 fresh = create_group(ranks=list(group_ranks)) if group_ranks in absent_somewhere else None
190 if group_ranks not in needed:
191 continue
192 if fresh is None:
193 groups[group_ranks] = _existing_group(group_ranks)
194 continue
195 groups[group_ranks] = fresh
196 owned.add(group_ranks)
197 return groups, owned
200def _destroy_broadcast_groups(groups: dict[tuple, Any], owned: set) -> None:
201 """
202 Release the groups this load made, once it is done broadcasting through them.
204 The broadcasts have been waited on but are not necessarily finished: a collective that
205 has been waited on is only ordered against the device stream, so the transfer can still
206 be queued when the call returns. Tearing the communicator down at that point kills the
207 transfer - the receiving ranks silently keep whatever their buffer held - so drain the
208 stream first.
210 Releasing is then best effort: the tensors have really arrived by the time the loop
211 runs, so a group that refuses to go away is a leak worth a warning rather than a reason
212 to fail a load that already has its data.
214 Only what this load made is passed here, and only by a rank that belongs to it:
215 ``owned`` is built from this rank own reads, so a group it never joined never reaches
216 this.
218 Args:
219 groups (dict[tuple, Any]): Every group the load broadcast through, keyed by rank tuple.
220 owned (set): Rank tuples whose groups this load made and has to release.
221 """
222 if not owned:
223 return
224 synchronize()
225 # Destroying a group is collective over its members, so keep the same deterministic
226 # order they were created in.
227 for group_ranks in sorted(owned):
228 try:
229 dist.destroy_process_group(groups[group_ranks])
230 except Exception as e: # pylint: disable=broad-except
231 logger.warning("Failed to destroy the broadcast group %s: %s", group_ranks, e)
234@contextmanager
235def broadcast_groups_for_load(
236 items: Iterable[ReadItem],
237 groups: Optional[dict[tuple, Any]] = None,
238) -> Any:
239 """
240 The communication groups one load broadcasts through, destroyed once it is done.
242 A group made here exists to carry this load's broadcasts and nothing else, so it is torn
243 down on the way out rather than left behind: a communicator holds device memory for as
244 long as it lives, and a job that loads a checkpoint has no use for these afterwards.
246 Only what this load made is destroyed. A group the caller pre-built and passed in
247 belongs to the caller, and one that was already in the process-wide cache belongs to
248 whoever put it there - the device mesh, most often, which needs it for the rest of
249 training.
251 Destroying is done in rank-tuple order, which every rank works out the same way, and
252 only by the ranks of the group - the ones that reach the end of the read together.
254 Args:
255 items (Iterable[ReadItem]): The read items of this rank finalized plan.
256 groups (Optional[dict[tuple, Any]]): Communication groups the caller pre-built.
258 Yields:
259 dict[tuple, Any]: A group for every rank tuple this rank broadcasts through.
260 """
261 built, owned = _build_broadcast_groups(items, dict(groups or {}))
262 try:
263 yield built
264 finally:
265 _destroy_broadcast_groups(built, owned)
268def _start_broadcast(
269 in_flight: deque,
270 buffer: Any,
271 source: BroadcastSource,
272 groups: dict[tuple, Any],
273 after: Optional[Any] = None,
274) -> None:
275 """
276 Start one broadcast without waiting for it, making room for it first.
278 Args:
279 in_flight (deque): Broadcasts already going, oldest first. This one is added, after
280 waiting on the oldest should too many already be going.
281 buffer (Any): Contiguous memory to send from the source and receive into elsewhere.
282 source (BroadcastSource): Which ranks take part and which of them sends.
283 groups (dict[tuple, Any]): Communication groups, as :func:`broadcast_groups_for_load`
284 returns them.
285 after (Optional[Any]): Called once this broadcast has landed, for a send that is not
286 finished when the bytes arrive -- a batch still to be dealt out to the shards it
287 was gathered from.
288 """
289 while len(in_flight) >= _MAX_BROADCASTS_IN_FLIGHT:
290 _finish_broadcast(in_flight.popleft())
291 handle = dist.broadcast(buffer, source.src_rank, groups[source.group_ranks], async_op=True)
292 if handle is None:
293 if after is not None:
294 after()
295 return
296 in_flight.append((handle, after))
299def _finish_broadcast(pending: tuple) -> None:
300 """Wait on one broadcast and do whatever was left until it had landed."""
301 handle, after = pending
302 handle.wait()
303 if after is not None:
304 after()
307def broadcast_shard(
308 in_flight: deque,
309 state_dict: dict[str, Any],
310 item: ReadItem,
311 groups: dict[tuple, Any],
312) -> None:
313 """
314 Start sending one shard between the ranks that hold it, without waiting for it.
316 A shard travels whole rather than region by region: it is one local buffer, which is
317 contiguous where a single region of it generally is not, and every rank holding it has it
318 in the same shape. Shards are otherwise unrelated -- two of one tensor are two buffers,
319 two groups and two broadcasts.
321 Callers have to reach the shards of a group in the same order on every rank of it, since
322 ranks that enter a group collectives in different orders deadlock. The order the global
323 plan puts them in is the one thing every rank agrees on without asking.
325 Args:
326 in_flight (deque): Broadcasts already going, oldest first.
327 state_dict (dict[str, Any]): Flat state dict holding the shard to send.
328 item (ReadItem): Any item of the shard, which names it and who reads it.
329 groups (dict[tuple, Any]): Communication groups, as :func:`broadcast_groups_for_load`
330 returns them.
331 """
332 buffer = _shard_buffer(state_dict[item.dest_index.fqn], item.dest_index)
333 _start_broadcast(in_flight, buffer, item.source, groups)
336def wait_broadcasts(in_flight: deque) -> None:
337 """
338 Wait on every broadcast still going, oldest first.
340 The buffers being sent are the state dict tensors themselves, so a load that carried on
341 with one still in flight would be reading into memory a collective is still writing.
343 Args:
344 in_flight (deque): Broadcasts started so far. Emptied.
345 """
346 while in_flight:
347 _finish_broadcast(in_flight.popleft())
350class BroadcastBatcher:
351 """
352 Shards small enough that sending them one at a time would cost more than moving them.
354 A broadcast costs about the same whether it carries 64 KiB or 1 MiB -- around 145
355 microseconds either way, measured over four Ascend ranks, against 33 GiB/s once the
356 shards are large. Below that crossing point a load spends its time starting broadcasts
357 rather than moving data, and a checkpoint holds a great many small tensors: norms,
358 biases, scalars, step counters. So shards under ``batch_bytes`` are gathered into one
359 buffer, sent together, and dealt out again on the far side, while larger ones are sent
360 as they are, the fixed cost being small against what they carry.
362 Shards can only travel together when they agree on the group, the sending rank and the
363 dtype, so one batch is kept per combination. Every rank of a group meets that group
364 shards in the same order and so fills and sends the same batches at the same points,
365 which is what keeps its collectives in step -- the same thing that lets shards be sent
366 one at a time without agreeing on anything first.
367 """
369 def __init__(self, batch_bytes: int, groups: dict[tuple, Any]) -> None:
370 """
371 Args:
372 batch_bytes (int): Shards this size or larger are sent on their own, and a batch
373 is sent as soon as another shard would take it past this. Zero sends every
374 shard on its own.
375 groups (dict[tuple, Any]): Communication groups, as
376 :func:`broadcast_groups_for_load` yields them.
377 """
378 self._batch_bytes = batch_bytes
379 self._groups = groups
380 self._batches: dict[tuple, list] = {}
381 self._pending_bytes: dict[tuple, int] = {}
382 self.batched = 0
383 self.sent = 0
385 def add(self, in_flight: deque, state_dict: dict[str, Any], item: ReadItem) -> None:
386 """
387 Hand one shard over to be sent, on its own or with others.
389 Args:
390 in_flight (deque): Broadcasts already going, oldest first.
391 state_dict (dict[str, Any]): Flat state dict holding the shard to send.
392 item (ReadItem): Any item of the shard, which names it and who sends it.
393 """
394 buffer = _shard_buffer(state_dict[item.dest_index.fqn], item.dest_index)
395 nbytes = get_tensor_storage_size(buffer)
396 if nbytes >= self._batch_bytes:
397 self.sent += 1
398 _start_broadcast(in_flight, buffer, item.source, self._groups)
399 return
401 key = (item.source.group_ranks, item.source.src_rank, buffer.dtype)
402 if self._pending_bytes.get(key, 0) + nbytes > self._batch_bytes:
403 self._send(in_flight, key)
404 self._batches.setdefault(key, []).append(buffer)
405 self._pending_bytes[key] = self._pending_bytes.get(key, 0) + nbytes
407 def flush(self, in_flight: deque) -> None:
408 """
409 Send whatever is still waiting to go with something else.
411 Batches go in the order they were first added to, which follows the shards and so is
412 the same on every rank that holds them.
414 Args:
415 in_flight (deque): Broadcasts already going, oldest first.
416 """
417 for key in list(self._batches):
418 self._send(in_flight, key)
420 def _send(self, in_flight: deque, key: tuple) -> None:
421 """Send one batch, and arrange for it to be dealt out once it has landed."""
422 buffers = self._batches.pop(key, [])
423 self._pending_bytes.pop(key, None)
424 if not buffers:
425 return
427 group_ranks, src_rank = key[:2]
428 source = BroadcastSource(group_ranks=group_ranks, src_rank=src_rank)
429 self.sent += 1
430 if len(buffers) == 1:
431 # Nothing to gather it with, so gathering it would only cost a round trip.
432 _start_broadcast(in_flight, buffers[0], source, self._groups)
433 return
435 self.batched += len(buffers)
436 # Left uninitialized: the views below cover it exactly, and it is written
437 # whole either by gathering the shards into it or by the broadcast landing.
438 staging = torch.empty(
439 size=(sum(buffer.numel() for buffer in buffers),),
440 dtype=buffers[0].dtype,
441 device=getattr(buffers[0], "device", None),
442 )
443 views, offset = [], 0
444 for buffer in buffers:
445 views.append(staging[offset:offset + buffer.numel()].reshape(buffer.shape))
446 offset += buffer.numel()
448 if source.src_rank == dist.get_rank():
449 # The sender already holds every shard, so it gathers them and needs nothing back.
450 copy_each(views, buffers)
451 _start_broadcast(in_flight, staging, source, self._groups)
452 return
453 _start_broadcast(
454 in_flight, staging, source, self._groups,
455 after=lambda: copy_each(buffers, views),
456 )
459def _shard_buffer(obj: Any, index: MetadataIndex) -> Any:
460 """
461 The local buffer of one shard, which is what a single broadcast carries.
463 Mirrors what :meth:`StandardLoadPlanner.acquire_tensor` narrows into, so that the rank
464 reading a shard sends the same storage the others are waiting to have written.
466 Args:
467 obj (Any): The state dict entry the shard belongs to.
468 index (MetadataIndex): Names the shard, as a read item destination does.
470 Returns:
471 Any: A tensor view over the shard, writable in place by a collective.
472 """
473 if isinstance(obj, DTensor):
474 if obj.layout is not None and obj.layout.ragged_shard is not None:
475 return get_ragged_box_tensor(obj, index).detach()
476 return obj.to_local().detach()
477 return obj.detach()