Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / fully_shard / param_group.py: 96%
550 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
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# Adapted from https://github.com/pytorch/pytorch/blob/release/2.6/torch/distributed/fsdp/_fully_shard
16# ==========================================================================
17"""Fused parameter communication for Torch fully_shard.
19Instead of issuing one collective per parameter, the managed parameters of a
20fully_shard unit are packed into contiguous buckets and communicated with a
21single collective each, which cuts kernel-launch overhead and improves
22bandwidth utilization.
24Bucketing: parameters are not fused into one global buffer. Each collective
25splits its parameters into buckets keyed by the attributes that must be uniform
26within one call -- ``(process group, dtype)`` -- because a collective cannot mix
27communication groups or element types:
29- ``AllGatherBucket``: one fused all-gather, keyed by (shard group, param dtype).
30 Owns the optional zero-copy ``flat_param_buffer`` that parameter shards are
31 rebased onto, so the gather reads parameter storage directly.
32- ``ReduceScatterBucket``: one fused reduce-scatter, keyed by (shard group,
33 reduce dtype). Packs gradients whose shard dim may differ per parameter.
34- ``AllReduceBucket``: the optional HSDP/replicate stage paired with one
35 reduce-scatter bucket; it takes over the completed RS output and reduces it
36 in place without per-parameter repacking.
38``ParamGroupCommCtx`` tracks which ``HSDPParamGroup`` owns each in-flight backward
39stage so the next module's backward can wait on it, giving the three-way
40overlap: layer N reduce-scatter with layer N-1 backward compute, and layer N
41all-reduce with layer N-1 reduce-scatter.
42"""
43from contextlib import ExitStack
44from dataclasses import dataclass
45from typing import List, Optional
47import torch
48import torch.distributed as dist
50from hyper_parallel.core.fully_shard.hsdp_utils import apply_gradient_scaling_factor
51from hyper_parallel.core.fully_shard.hsdp_scheduler import ParamGroupCommCtx
52from hyper_parallel.core.fully_shard.utils import DDPMeshInfo, FSDPMeshInfo
53from hyper_parallel.core.fully_shard.hsdp_param import HSDPParamV2
56@dataclass
57class AllGatherMetadata:
58 """Describe the rank-local layout of one fused all-gather bucket."""
60 param_input_dtypes: list[list[torch.dtype]]
61 param_input_numels: list[list[int]]
62 dtype: torch.dtype
63 inp_split_sizes: list[int]
64 total_input_numel: int
67@dataclass
68class AllGatherResult:
69 """Keep one all-gather input, output, and handle alive until copy-out."""
71 all_gather_input: Optional[torch.Tensor]
72 all_gather_output: Optional[torch.Tensor]
73 handle: Optional[dist.Work]
76@dataclass
77class AllGatherBucket:
78 """Own parameters and buffers sharing one all-gather group and dtype."""
80 hsdp_params: list[HSDPParamV2]
81 shard_group: dist.ProcessGroup
82 shard_rank: int
83 shard_world_size: int
84 dtype: torch.dtype
85 metadata: AllGatherMetadata
86 all_gather_result: Optional[AllGatherResult] = None
87 flat_param_buffer: Optional[torch.Tensor] = None
89 def init_flat_param_buffer(self, device: Optional[torch.device]) -> None:
90 """Rebase this bucket's homogeneous shards into one persistent flat buffer.
92 Side effect: rebinds every parameter's ``_sharded_param_data`` and
93 ``sharded_param`` onto a view of the new buffer, so the original shard
94 storages are dropped. Leaves ``flat_param_buffer`` as ``None`` when the
95 bucket mixes storage dtypes or holds offloaded/meta parameters, which is
96 the signal that the zero-copy path does not apply.
97 """
98 storage_dtype = self.hsdp_params[0]._sharded_param_data.dtype
99 if any(
100 hsdp_param._sharded_param_data.dtype != storage_dtype
101 for hsdp_param in self.hsdp_params[1:]
102 ):
103 self.flat_param_buffer = None
104 return
105 if any(
106 hsdp_param.offload_to_cpu or hsdp_param.sharded_param.device.type == "meta"
107 for hsdp_param in self.hsdp_params
108 ):
109 self.flat_param_buffer = None
110 return
112 total_numel = sum(hsdp_param._sharded_param_data.numel() for hsdp_param in self.hsdp_params)
113 flat_param_buffer = torch.empty(total_numel, dtype=storage_dtype, device=device)
114 flat_offset = 0
115 for hsdp_param in self.hsdp_params:
116 param_numel = hsdp_param._sharded_param_data.numel()
117 flat_param_view = flat_param_buffer.narrow(0, flat_offset, param_numel)
118 flat_param_view.copy_(hsdp_param._sharded_param_data)
119 hsdp_param._sharded_param_data = flat_param_view
120 padded_local_param = flat_param_view.view(hsdp_param.padded_sharded_param_size)
121 local_param = padded_local_param.narrow(
122 hsdp_param.hsdp_placement.dim,
123 0,
124 hsdp_param.sharded_size[hsdp_param.hsdp_placement.dim],
125 )
126 requires_grad = hsdp_param.sharded_param.requires_grad
127 hsdp_param.sharded_param._local_tensor = local_param
128 hsdp_param.sharded_param.data = local_param
129 if requires_grad:
130 local_param.requires_grad_(True)
131 hsdp_param.sharded_param.requires_grad_(True)
132 flat_offset += param_numel
133 self.flat_param_buffer = flat_param_buffer
135 def is_flat_buffer_valid(self) -> bool:
136 """Return whether this bucket's parameter shards still use its flat storage.
138 Parameter storage can be replaced behind this bucket's back (optimizer
139 surgery, ``load_state_dict``), which silently invalidates the zero-copy
140 rebase; comparing storage pointers is what detects that.
141 """
142 if self.flat_param_buffer is None:
143 return False
144 # Storage identity keeps empty shards and FakeTensors distinct, so the
145 # check only accepts a buffer the parameters actually alias.
146 flat_storage = self.flat_param_buffer.untyped_storage()
147 return all(
148 hsdp_param._sharded_param_data.untyped_storage() is flat_storage
149 for hsdp_param in self.hsdp_params
150 )
152 @torch.no_grad()
153 def copy_out(self) -> None:
154 """Wait this bucket's all-gather and copy it into stable unsharded buffers.
156 Blocks on the in-flight handle, then releases the bucket's all-gather
157 input/output references so the fused communication buffers can be freed
158 before the next bucket runs. No-op when the bucket has no pending result.
159 """
160 all_gather_result = self.all_gather_result
161 if all_gather_result is None or all_gather_result.all_gather_output is None:
162 return
163 if all_gather_result.handle is not None:
164 all_gather_result.handle.wait()
165 all_gather_result.handle = None
166 all_gather_output = all_gather_result.all_gather_output
167 metadata = self.metadata
168 split_with_sizes_out = []
169 for input_numels, input_dtypes, hsdp_param in zip(
170 metadata.param_input_numels,
171 metadata.param_input_dtypes,
172 self.hsdp_params,
173 ):
174 hsdp_param.init_unsharded_param_buffers(
175 input_numels,
176 input_dtypes,
177 self.shard_world_size,
178 all_gather_output.device,
179 )
180 hsdp_param.alloc_unsharded_param_buffers()
181 split_with_sizes_out.extend(hsdp_param.unsharded_param_buffers)
183 gathered_rows = all_gather_output.view(self.shard_world_size, -1)
184 output_rows = [
185 output_buffer.view(self.shard_world_size, -1)
186 for output_buffer in split_with_sizes_out
187 ]
188 non_inference_outputs = [output for output in output_rows if not output.is_inference()]
189 # PyTorch 2.6 accepts only one tensor per context manager. no_grad does
190 # not suppress version-counter bumps from the copy-out operations.
191 # pylint: disable=W0212
192 with ExitStack() as stack:
193 for output in non_inference_outputs:
194 stack.enter_context(torch.autograd._unsafe_preserve_version_counter(output))
195 if all(
196 hsdp_param.hsdp_placement.dim == 0
197 for hsdp_param in self.hsdp_params
198 ):
199 torch.split_with_sizes_copy(
200 gathered_rows,
201 metadata.inp_split_sizes,
202 dim=1,
203 out=output_rows,
204 )
205 else:
206 column_offset = 0
207 for input_numels, hsdp_param in zip(
208 metadata.param_input_numels,
209 self.hsdp_params,
210 ):
211 if hsdp_param.hsdp_placement.dim != 0 and len(input_numels) != 1:
212 raise NotImplementedError(
213 "Fused non-dim-0 all-gather expects one local shard tensor per parameter."
214 )
215 for input_numel, output_buffer in zip(
216 input_numels,
217 hsdp_param.unsharded_param_buffers,
218 ):
219 gathered_param = gathered_rows.narrow(1, column_offset, input_numel)
220 if hsdp_param.hsdp_placement.dim == 0:
221 output_buffer.view(self.shard_world_size, -1).copy_(gathered_param)
222 else:
223 packed_shape = list(hsdp_param.sharded_size)
224 packed_shape[0] *= self.shard_world_size
225 packed_param = gathered_param.contiguous().view(packed_shape)
226 param_chunks = torch.chunk(
227 packed_param,
228 self.shard_world_size,
229 dim=0,
230 )
231 torch.cat(
232 param_chunks,
233 dim=hsdp_param.hsdp_placement.dim,
234 out=output_buffer.view(hsdp_param._orig_size),
235 )
236 column_offset += input_numel
237 if column_offset != gathered_rows.size(1):
238 raise AssertionError(
239 "Fused all-gather copy-out consumed an unexpected number of elements: "
240 f"{column_offset} != {gathered_rows.size(1)}"
241 )
242 all_gather_result.all_gather_input = None
243 all_gather_result.all_gather_output = None
244 self.all_gather_result = None
247@dataclass
248class GradientBucketLayout:
249 """Describe the shared per-parameter layout of an RS-to-AR bucket chain."""
251 hsdp_params: list[HSDPParamV2]
252 param_offsets: list[int]
253 param_numels: list[int]
254 total_numel: int
257@dataclass
258class ReduceScatterBucket:
259 """Own one fused reduce-scatter operation and its temporary buffers.
261 Bucket construction records only communication metadata and the source
262 gradients. Buffer preparation, gradient scaling, collective launch, and
263 final result placement are separate execution phases on ``HSDPParamGroup``.
265 The shard group plus reduce dtype is this bucket's identity across
266 micro-steps and keys its parked partial output.
267 """
269 layout: GradientBucketLayout
270 unsharded_grads: list[torch.Tensor]
271 shard_group: Optional[dist.ProcessGroup]
272 shard_world_size: int
273 dtype: torch.dtype
274 reduce_op: dist.ReduceOp
275 needs_avg_div: bool
276 reduce_scatter_input: Optional[torch.Tensor] = None
277 reduce_scatter_output: Optional[torch.Tensor] = None
278 handle: Optional[dist.Work] = None
280 @property
281 def hsdp_params(self) -> list[HSDPParamV2]:
282 """Return parameters in their fused-buffer order."""
283 return self.layout.hsdp_params
285 @property
286 def param_offsets(self) -> list[int]:
287 """Return parameter offsets in the reduce-scatter output."""
288 return self.layout.param_offsets
290 @property
291 def bucket_key(self) -> tuple:
292 """Identity of this bucket's reduce-scatter fusion class."""
293 return (id(self.shard_group), self.dtype)
295 @property
296 def uses_collective(self) -> bool:
297 """Return whether this bucket needs an actual reduce-scatter call."""
298 return self.shard_group is not None and self.shard_world_size > 1
300 def move_reducescatter_output(self) -> torch.Tensor:
301 """Transfer exclusive ownership of the completed output to the next stage."""
302 if self.reduce_scatter_output is None:
303 raise RuntimeError("Reduce-scatter output has already been released.")
304 reduce_scatter_output = self.reduce_scatter_output
305 self.reduce_scatter_output = None
306 return reduce_scatter_output
309@dataclass
310class AllReduceBucket:
311 """Own the final stage of one fused RS-to-AR bucket chain.
313 The bucket shares its parameter layout with exactly one source
314 reduce-scatter bucket. Once RS completes, it takes over that bucket's whole
315 output tensor and all-reduces it in place without per-parameter repacking.
316 """
318 layout: GradientBucketLayout
319 source_reduce_scatter_bucket: ReduceScatterBucket
320 replicate_group: dist.ProcessGroup
321 replicate_world_size: int
322 dtype: torch.dtype
323 reduce_op: dist.ReduceOp
324 needs_avg_div: bool
325 all_reduce_output: Optional[torch.Tensor] = None
326 handle: Optional[dist.Work] = None
328 @property
329 def hsdp_params(self) -> list[HSDPParamV2]:
330 """Return parameters in their fused-buffer order."""
331 return self.layout.hsdp_params
333 @property
334 def param_numels(self) -> list[int]:
335 """Return padded parameter sizes in the all-reduce output."""
336 return self.layout.param_numels
338 @property
339 def param_offsets(self) -> list[int]:
340 """Return parameter offsets in the all-reduce output."""
341 return self.layout.param_offsets
343 @property
344 def uses_collective(self) -> bool:
345 """Return whether this bucket needs an actual all-reduce call."""
346 return self.replicate_world_size > 1
349def get_all_gather_metadata(hsdp_params: list[HSDPParamV2]) -> AllGatherMetadata:
350 """Build metadata for parameters with one all-gather communication dtype."""
351 param_input_dtypes = []
352 param_input_numels = []
353 inp_split_sizes = []
354 total_input_numel = 0
355 dtype = None
356 for hsdp_param in hsdp_params:
357 inputs = hsdp_param.all_gather_inputs
358 if dtype is None:
359 dtype = inputs[0].dtype
360 if any(tensor.dtype != dtype for tensor in inputs):
361 raise ValueError("All parameters in an all-gather bucket must have the same dtype.")
362 input_dtypes = [tensor.dtype for tensor in inputs]
363 input_numels = [tensor.numel() for tensor in inputs]
364 param_input_dtypes.append(input_dtypes)
365 param_input_numels.append(input_numels)
366 inp_split_sizes.extend(input_numels)
367 total_input_numel += sum(input_numels)
368 if dtype is None:
369 raise ValueError("Cannot build all-gather metadata for an empty parameter bucket.")
370 return AllGatherMetadata(
371 param_input_dtypes=param_input_dtypes,
372 param_input_numels=param_input_numels,
373 dtype=dtype,
374 inp_split_sizes=inp_split_sizes,
375 total_input_numel=total_input_numel,
376 )
379def all_gather_copy_in(
380 all_gather_inputs: list[torch.Tensor],
381 all_gather_output: torch.Tensor,
382 inp_split_sizes: list[int],
383 all_gather_input_numel: int,
384 rank: int,
385) -> tuple[torch.Tensor, torch.Tensor]:
386 """Copy local parameter shards into this rank's fused output slice."""
387 all_gather_input = all_gather_output.narrow(
388 0,
389 all_gather_input_numel * rank,
390 all_gather_input_numel,
391 )
392 copy_destinations = torch.split(all_gather_input, inp_split_sizes)
393 with torch.no_grad():
394 # pylint: disable=W0212
395 torch._foreach_copy_(copy_destinations, all_gather_inputs)
396 return all_gather_input, all_gather_output
399def reduce_scatter_copy_in(
400 hsdp_params: list[HSDPParamV2],
401 unsharded_grads: list[torch.Tensor],
402 reduce_scatter_input: torch.Tensor,
403 world_size: int,
404) -> None:
405 """Pack gradients into the rank rows of a fused reduce-scatter input.
407 Args:
408 hsdp_params: Parameters in bucket order.
409 unsharded_grads: Local source gradients in the same order.
410 reduce_scatter_input: Flat communication buffer sized by the bucket layout.
411 world_size: Number of shards in the reduce-scatter group.
412 """
413 if len(hsdp_params) != len(unsharded_grads):
414 raise AssertionError(
415 "reduce_scatter_copy_in expects one hsdp_param per unsharded_grad, but got "
416 f"{len(hsdp_params)} params and {len(unsharded_grads)} grads"
417 )
418 packed_rows = reduce_scatter_input.view(world_size, -1)
419 expected_width = sum(param.padded_sharded_param_size.numel() for param in hsdp_params)
420 if packed_rows.size(1) != expected_width:
421 raise AssertionError(
422 f"reduce_scatter_copy_in expected {expected_width} elements per rank, got {packed_rows.size(1)}"
423 )
424 # The first chunk of each parameter defines its padded shard size. A single
425 # ChunkCat can pack dense dim-0 inputs of one source dtype and widen into out.
426 enable_chunkcat_cast_fused = len(unsharded_grads) > 1 and all(
427 param.hsdp_placement.dim == 0 and grad.dtype == unsharded_grads[0].dtype and grad.is_contiguous()
428 for param, grad in zip(hsdp_params, unsharded_grads)
429 )
430 if enable_chunkcat_cast_fused:
431 with torch.no_grad():
432 torch._chunk_cat(unsharded_grads, dim=0, num_chunks=world_size, out=packed_rows)
433 return
434 column_offset = 0
435 with torch.no_grad():
436 for hsdp_param, unsharded_grad in zip(hsdp_params, unsharded_grads):
437 padded_shard_numel = hsdp_param.padded_sharded_param_size.numel()
438 packed_grad_slot = packed_rows.narrow(1, column_offset, padded_shard_numel)
439 shard_dim = hsdp_param.hsdp_placement.dim
440 if shard_dim == 0:
441 # pylint: disable=W0212
442 torch._chunk_cat(
443 [unsharded_grad],
444 dim=0,
445 num_chunks=world_size,
446 out=packed_grad_slot,
447 )
448 else:
449 grad_chunks = torch.chunk(unsharded_grad, world_size, dim=shard_dim)
450 packed_grad = torch.cat(grad_chunks, dim=0).contiguous().view(world_size, -1)
451 packed_grad_slot.copy_(packed_grad)
452 column_offset += padded_shard_numel
455class HSDPParamGroup:
456 """Fuse communication for the managed parameters in one fully_shard unit.
458 Packs parameter shards into contiguous buckets so communication is issued
459 once per compatible route and dtype instead of once per parameter.
461 Lifecycle within one training iteration:
462 1. Forward -- ``unshard()`` builds the all-gather buckets on first use
463 and issues one ``all_gather_into_tensor`` per bucket.
464 2. Forward (wait) -- ``wait_for_unshard()`` waits each bucket and copies
465 the gathered data out into the per-parameter unsharded buffers.
466 3. Backward -- ``foreach_reduce()`` packs the unsharded gradients and
467 issues one fused ``reduce_scatter_tensor`` per bucket, then parks
468 itself on ``ParamGroupCommCtx`` so a later module's backward waits for it.
469 4. Backward (finalize) -- ``wait_reduce_scatter_and_issue_all_reduce()``
470 waits the RS buckets and launches the HSDP all-reduces;
471 ``wait_all_reduce_and_save_grad()`` waits those and exposes each
472 parameter's reduced-gradient view.
474 Steps 3 and 4 are deliberately split across modules: that is what allows one
475 module's communication to overlap the next module's backward compute. The
476 root backward hook drains whatever is still parked when backward ends.
478 Gradient accumulation is held at bucket granularity in
479 ``reduce_partial_outputs``, keyed by the reduce-scatter bucket key. A
480 micro-step with ``requires_all_reduce=False`` keeps its whole reduce-scatter
481 output there and skips the all-reduce entirely; the next synchronizing
482 micro-step adds it back with a single whole-buffer ``add_`` and lets the
483 fused all-reduce see the total. The dict lives on the group rather than on
484 the bucket because ``foreach_reduce`` rebuilds the buckets every micro-step,
485 and holds whole buffers rather than per-parameter views so accumulation
486 costs one kernel per bucket instead of one per parameter.
487 """
489 def __init__(
490 self,
491 hsdp_params: list[HSDPParamV2],
492 device: Optional[torch.device] = None,
493 enable_zero_copy: bool = True,
494 comm_ctx: Optional[ParamGroupCommCtx] = None,
495 ) -> None:
496 self.device = device
497 self.hsdp_params = hsdp_params
498 self.comm_ctx = comm_ctx or ParamGroupCommCtx()
499 self.enable_zero_copy = enable_zero_copy
500 self.gradient_scaling_factor = None
501 self.requires_all_reduce = True
502 self.all_gather_buckets: list[AllGatherBucket] = []
503 self.reduce_scatter_buckets: list[ReduceScatterBucket] = []
504 self.all_reduce_buckets: list[AllReduceBucket] = []
505 self.reduce_partial_outputs: dict[tuple, torch.Tensor] = {}
507 def _init_all_gather_buckets(self) -> None:
508 """Build ordered all-gather buckets from each parameter's communication facts."""
509 params_by_bucket = {}
510 bucket_groups = {}
511 for hsdp_param in self.hsdp_params:
512 if hsdp_param.shard_world_size <= 1:
513 continue
514 if not isinstance(hsdp_param.mesh_info, FSDPMeshInfo):
515 raise ValueError(
516 f"Fused all-gather expects FSDPMeshInfo, got {type(hsdp_param.mesh_info)}"
517 )
518 shard_group = hsdp_param.mesh_info.shard_process_group
519 communication_dtype = hsdp_param.param_dtype or hsdp_param.orig_dtype
520 bucket_key = (id(shard_group), communication_dtype)
521 if bucket_key not in params_by_bucket:
522 params_by_bucket[bucket_key] = []
523 bucket_groups[bucket_key] = shard_group
524 params_by_bucket[bucket_key].append(hsdp_param)
526 self.all_gather_buckets = []
527 for bucket_key, hsdp_params in params_by_bucket.items():
528 shard_group = bucket_groups[bucket_key]
529 param_input_numels = [
530 [hsdp_param._sharded_param_data.numel()] for hsdp_param in hsdp_params
531 ]
532 inp_split_sizes = [input_numels[0] for input_numels in param_input_numels]
533 allgather_metadata = AllGatherMetadata(
534 param_input_dtypes=[[bucket_key[1]] for _ in hsdp_params],
535 param_input_numels=param_input_numels,
536 dtype=bucket_key[1],
537 inp_split_sizes=inp_split_sizes,
538 total_input_numel=sum(inp_split_sizes),
539 )
540 self.all_gather_buckets.append(
541 AllGatherBucket(
542 hsdp_params=hsdp_params,
543 shard_group=shard_group,
544 shard_rank=shard_group.rank(),
545 shard_world_size=shard_group.size(),
546 dtype=bucket_key[1],
547 metadata=allgather_metadata,
548 )
549 )
551 def unshard(self, async_op: bool = False) -> None:
552 """Launch fused all-gathers for every communication bucket."""
553 if self.all_gather_buckets and any(
554 bucket.all_gather_result is not None for bucket in self.all_gather_buckets
555 ):
556 # already triggered by pre_module.prefetch(), return directly.
557 return
558 self.foreach_all_gather(async_op)
560 @torch.no_grad()
561 def foreach_all_gather(self, async_op: bool = False) -> None:
562 """Initialize ordered buckets and launch their all-gathers."""
563 if not self.all_gather_buckets:
564 self._init_all_gather_buckets()
565 for hsdp_param in self.hsdp_params:
566 if hsdp_param.shard_world_size <= 1:
567 # fast path, skip copy_in process.
568 hsdp_param.unshard(async_op)
569 for all_gather_bucket in self.all_gather_buckets:
570 if all_gather_bucket.all_gather_result is not None:
571 continue
572 if self.enable_zero_copy and not all_gather_bucket.is_flat_buffer_valid():
573 all_gather_bucket.init_flat_param_buffer(self.device)
575 metadata = all_gather_bucket.metadata
576 all_gather_output = torch.empty(
577 metadata.total_input_numel * all_gather_bucket.shard_world_size,
578 dtype=all_gather_bucket.dtype,
579 device=self.device,
580 )
581 if self.enable_zero_copy and all_gather_bucket.is_flat_buffer_valid():
582 if all_gather_bucket.flat_param_buffer.dtype == all_gather_bucket.dtype:
583 all_gather_input = all_gather_bucket.flat_param_buffer
584 else:
585 all_gather_input = all_gather_bucket.flat_param_buffer.to(all_gather_bucket.dtype)
586 else:
587 all_gather_inputs = []
588 for hsdp_param in all_gather_bucket.hsdp_params:
589 all_gather_inputs.extend(hsdp_param.all_gather_inputs)
590 all_gather_input, all_gather_output = all_gather_copy_in(
591 all_gather_inputs,
592 all_gather_output,
593 metadata.inp_split_sizes,
594 metadata.total_input_numel,
595 all_gather_bucket.shard_rank,
596 )
598 handle = dist.all_gather_into_tensor(
599 all_gather_output,
600 all_gather_input,
601 group=all_gather_bucket.shard_group,
602 async_op=async_op,
603 )
604 all_gather_bucket.all_gather_result = AllGatherResult(
605 all_gather_input=all_gather_input,
606 all_gather_output=all_gather_output,
607 handle=handle,
608 )
610 def wait_for_unshard(self) -> None:
611 """Wait all fused all-gathers and install stable unsharded parameters."""
612 for all_gather_bucket in self.all_gather_buckets:
613 all_gather_bucket.copy_out()
614 for hsdp_param in self.hsdp_params:
615 hsdp_param.wait_for_unshard()
617 def _build_reduce_scatter_buckets(
618 self,
619 reduce_scatter_reduce_op: dist.ReduceOp,
620 ) -> list[ReduceScatterBucket]:
621 """Build ordered reduce-scatter metadata for active gradients.
623 This method deliberately has no tensor or communication side effects:
624 it does not allocate buffers, pack gradients, apply scaling, clear
625 source gradients, or launch collectives.
626 """
627 params_by_bucket = {}
628 grads_by_bucket = {}
629 bucket_groups = {}
630 for hsdp_param in self.hsdp_params:
631 if not hasattr(hsdp_param, "_unsharded_param") or not hsdp_param.sharded_param.requires_grad:
632 continue
633 if hsdp_param.unsharded_accumulated_grad is not None:
634 unsharded_grad = hsdp_param.unsharded_accumulated_grad_data
635 elif hsdp_param.unsharded_param.grad is not None:
636 unsharded_grad = hsdp_param.unsharded_grad_data
637 else:
638 continue
639 shard_group = (
640 hsdp_param.mesh_info.shard_process_group
641 if isinstance(hsdp_param.mesh_info, FSDPMeshInfo)
642 else None
643 )
644 reduce_dtype = hsdp_param.reduce_comm_dtype(unsharded_grad)
645 bucket_key = (id(shard_group), reduce_dtype)
646 if bucket_key not in params_by_bucket:
647 params_by_bucket[bucket_key] = []
648 grads_by_bucket[bucket_key] = []
649 bucket_groups[bucket_key] = shard_group
650 params_by_bucket[bucket_key].append(hsdp_param)
651 grads_by_bucket[bucket_key].append(unsharded_grad)
653 reduce_scatter_buckets = []
654 for bucket_key, hsdp_params in params_by_bucket.items():
655 shard_group = bucket_groups[bucket_key]
656 shard_world_size = hsdp_params[0].shard_world_size
657 if any(
658 hsdp_param.shard_world_size != shard_world_size
659 for hsdp_param in hsdp_params
660 ):
661 raise ValueError("A reduce-scatter bucket must use one shard world size.")
662 needs_avg_div = reduce_scatter_reduce_op == dist.ReduceOp.AVG
663 communication_op = dist.ReduceOp.SUM if needs_avg_div else reduce_scatter_reduce_op
664 param_offsets = []
665 param_numels = []
666 flat_offset = 0
667 for hsdp_param in hsdp_params:
668 param_numel = hsdp_param.padded_sharded_param_size.numel()
669 param_offsets.append(flat_offset)
670 param_numels.append(param_numel)
671 flat_offset += param_numel
672 reduce_scatter_buckets.append(
673 ReduceScatterBucket(
674 layout=self._build_gradient_bucket_layout_from(hsdp_params),
675 unsharded_grads=grads_by_bucket[bucket_key],
676 shard_group=shard_group,
677 shard_world_size=shard_world_size,
678 dtype=bucket_key[1],
679 reduce_op=communication_op,
680 needs_avg_div=needs_avg_div,
681 )
682 )
683 return reduce_scatter_buckets
685 @staticmethod
686 def _build_gradient_bucket_layout_from(hsdp_params):
687 param_offsets = []
688 param_numels = []
689 flat_offset = 0
690 for hsdp_param in hsdp_params:
691 param_numel = hsdp_param.padded_sharded_param_size.numel()
692 param_offsets.append(flat_offset)
693 param_numels.append(param_numel)
694 flat_offset += param_numel
695 return GradientBucketLayout(
696 hsdp_params,
697 param_offsets,
698 param_numels,
699 flat_offset
700 )
702 @staticmethod
703 def _build_all_reduce_buckets(
704 reduce_scatter_buckets: list[ReduceScatterBucket],
705 ) -> list[AllReduceBucket]:
706 """Build one optional all-reduce stage for each RS bucket."""
707 all_reduce_buckets = []
708 for reduce_scatter_bucket in reduce_scatter_buckets:
709 representative_param = reduce_scatter_bucket.hsdp_params[0]
710 if not isinstance(representative_param.mesh_info, DDPMeshInfo):
711 # FSDP, no need allreduce on replicate mesh dim. skip build relative allreduce-bucket.
712 if any(
713 isinstance(hsdp_param.mesh_info, DDPMeshInfo)
714 for hsdp_param in reduce_scatter_bucket.hsdp_params[1:]
715 ):
716 raise ValueError(
717 "A reduce-scatter bucket cannot mix parameters with and without "
718 "a subsequent all-reduce."
719 )
720 continue
721 replicate_group = representative_param.mesh_info.replicate_process_group
722 replicate_world_size = representative_param.replicate_world_size
723 for hsdp_param in reduce_scatter_bucket.hsdp_params[1:]:
724 if (
725 not isinstance(hsdp_param.mesh_info, DDPMeshInfo)
726 or hsdp_param.mesh_info.replicate_process_group is not replicate_group
727 or hsdp_param.replicate_world_size != replicate_world_size
728 ):
729 raise ValueError(
730 "All parameters in a reduce-scatter bucket must share one "
731 "subsequent all-reduce group."
732 )
733 all_reduce_buckets.append(
734 AllReduceBucket(
735 layout=reduce_scatter_bucket.layout,
736 source_reduce_scatter_bucket=reduce_scatter_bucket,
737 replicate_group=replicate_group,
738 replicate_world_size=replicate_world_size,
739 dtype=reduce_scatter_bucket.dtype,
740 reduce_op=reduce_scatter_bucket.reduce_op,
741 needs_avg_div=reduce_scatter_bucket.needs_avg_div,
742 )
743 )
744 return all_reduce_buckets
746 def _issue_reduce_scatter_buckets(self, async_op: bool) -> None:
747 """Prepare RS buffers, release source gradients, and launch communication."""
748 for reduce_scatter_bucket in self.reduce_scatter_buckets:
749 reduce_scatter_input = torch.empty(
750 reduce_scatter_bucket.layout.total_numel * reduce_scatter_bucket.shard_world_size,
751 dtype=reduce_scatter_bucket.dtype,
752 device=reduce_scatter_bucket.unsharded_grads[0].device,
753 )
754 reduce_scatter_copy_in(
755 reduce_scatter_bucket.hsdp_params,
756 reduce_scatter_bucket.unsharded_grads,
757 reduce_scatter_input,
758 reduce_scatter_bucket.shard_world_size,
759 )
760 apply_gradient_scaling_factor(reduce_scatter_input, self.gradient_scaling_factor)
761 reduce_scatter_bucket.reduce_scatter_input = reduce_scatter_input
762 if not reduce_scatter_bucket.uses_collective:
763 reduce_scatter_bucket.reduce_scatter_output = reduce_scatter_input
764 else:
765 reduce_scatter_bucket.reduce_scatter_output = reduce_scatter_input.new_empty(
766 reduce_scatter_bucket.layout.total_numel
767 )
769 for hsdp_param in reduce_scatter_bucket.hsdp_params:
770 if hsdp_param.unsharded_accumulated_grad is not None:
771 hsdp_param.unsharded_accumulated_grad = None
772 else:
773 hsdp_param.unsharded_param.grad = None
774 reduce_scatter_bucket.unsharded_grads = []
775 if not reduce_scatter_bucket.uses_collective:
776 reduce_scatter_bucket.handle = None
777 continue
778 reduce_scatter_bucket.handle = dist.reduce_scatter_tensor(
779 output=reduce_scatter_bucket.reduce_scatter_output,
780 input=reduce_scatter_bucket.reduce_scatter_input,
781 group=reduce_scatter_bucket.shard_group,
782 op=reduce_scatter_bucket.reduce_op,
783 async_op=async_op,
784 )
786 @torch.no_grad()
787 def foreach_reducescatter(
788 self,
789 reduce_scatter_reduce_op: Optional[dist.ReduceOp] = dist.ReduceOp.AVG,
790 async_op: bool = True,
791 ) -> Optional[torch.Tensor]:
792 """Launch fused reduce-scatter buckets for this module's gradients."""
793 self.reduce_scatter_buckets = self._build_reduce_scatter_buckets(
794 reduce_scatter_reduce_op,
795 )
796 if not self.reduce_scatter_buckets:
797 return
798 self.all_reduce_buckets = self._build_all_reduce_buckets(self.reduce_scatter_buckets)
799 self._issue_reduce_scatter_buckets(async_op)
800 if async_op:
801 self.comm_ctx.pre_param_group = self
802 else:
803 self.wait_reduce_scatter_and_issue_all_reduce(async_op=False)
804 self.wait_all_reduce_and_save_grad()
805 return
807 def _wait_reduce_scatter_buckets(self) -> None:
808 """Wait prepared RS buckets and finish shard-dimension averaging."""
809 for reduce_scatter_bucket in self.reduce_scatter_buckets:
810 if reduce_scatter_bucket.handle is not None:
811 reduce_scatter_bucket.handle.wait()
812 reduce_scatter_bucket.handle = None
813 reduce_scatter_bucket.reduce_scatter_input = None
814 if reduce_scatter_bucket.reduce_scatter_output is None:
815 raise RuntimeError("Reduce-scatter bucket has not been prepared.")
816 if reduce_scatter_bucket.needs_avg_div and reduce_scatter_bucket.shard_world_size > 1:
817 reduce_scatter_bucket.reduce_scatter_output.div_(
818 reduce_scatter_bucket.shard_world_size
819 )
822 @staticmethod
823 def _issue_all_reduce_buckets(
824 all_reduce_buckets: list[AllReduceBucket],
825 async_op: bool,
826 ) -> None:
827 """Launch in-place AR for bucket outputs transferred from RS."""
828 for all_reduce_bucket in all_reduce_buckets:
829 if all_reduce_bucket.all_reduce_output is None:
830 raise RuntimeError("All-reduce bucket has not received its reduce-scatter output.")
831 if not all_reduce_bucket.uses_collective:
832 all_reduce_bucket.handle = None
833 continue
834 all_reduce_bucket.handle = dist.all_reduce(
835 all_reduce_bucket.all_reduce_output,
836 group=all_reduce_bucket.replicate_group,
837 op=all_reduce_bucket.reduce_op,
838 async_op=async_op,
839 )
841 def _sum_source_replica_gradients(self) -> None:
842 """Sum completed shard gradients over replicated source axes."""
843 views_by_group = {}
844 for bucket in self.reduce_scatter_buckets:
845 output = bucket.reduce_scatter_output
846 for param, offset, numel in zip(bucket.hsdp_params, bucket.param_offsets, bucket.layout.param_numels):
847 group = param.get_source_replicate_process_group()
848 if group is not None:
849 key = (group, output.dtype, output.device)
850 views_by_group.setdefault(key, []).append(output.narrow(0, offset, numel))
852 for (group, _, _), views in views_by_group.items():
853 if len(views) == 1:
854 dist.all_reduce(views[0], op=dist.ReduceOp.SUM, group=group, async_op=False)
855 else:
856 packed = torch.cat(views)
857 dist.all_reduce(packed, op=dist.ReduceOp.SUM, group=group, async_op=False)
858 for view, reduced in zip(views, packed.split([view.numel() for view in views])):
859 view.copy_(reduced)
861 def wait_reduce_scatter_and_issue_all_reduce(self, async_op: bool = True) -> None:
862 """Wait all RS buckets and launch the resulting HSDP all-reduces."""
863 self._wait_reduce_scatter_buckets()
864 self._sum_source_replica_gradients()
865 # Step1: get fianal reduce_scatter output
866 if not self.requires_all_reduce:
867 # if set_requires_all_reduce is False, accmu grad into reduce_partial_ouptut.
868 for reduce_scatter_bucket in self.reduce_scatter_buckets:
869 bucket_key = reduce_scatter_bucket.bucket_key
870 current_output = reduce_scatter_bucket.move_reducescatter_output()
871 reduce_partial_output = self.reduce_partial_outputs.get(bucket_key)
872 if reduce_partial_output is None:
873 self.reduce_partial_outputs[bucket_key] = current_output
874 else:
875 reduce_partial_output.add_(current_output)
876 self.reduce_scatter_buckets = []
877 self.all_reduce_buckets = []
878 return
880 for reduce_scatter_bucket in self.reduce_scatter_buckets:
881 reduce_partial_output = self.reduce_partial_outputs.pop(
882 reduce_scatter_bucket.bucket_key,
883 None,
884 )
885 if reduce_partial_output is not None:
886 # current reduce-scattered grad add accmulated grad
887 reduce_scatter_bucket.reduce_scatter_output.add_(reduce_partial_output)
888 # Step2: moving reducescatter bucket lifecycle
889 # Step2.1 build mapping from rs_bucket -> ar_bucket
890 all_reduce_by_source = {
891 id(all_reduce_bucket.source_reduce_scatter_bucket): all_reduce_bucket
892 for all_reduce_bucket in self.all_reduce_buckets
893 }
894 for reduce_scatter_bucket in self.reduce_scatter_buckets:
895 all_reduce_bucket = all_reduce_by_source.get(id(reduce_scatter_bucket))
896 if all_reduce_bucket is not None:
897 # Step2.2-A: need allreduce when HSDP
898 all_reduce_bucket.all_reduce_output = reduce_scatter_bucket.move_reducescatter_output()
899 continue
900 # Step2.2-B: FSDP only. Hand the completed output to the per-parameter gradient writeback.
901 self._apply_final_reduce_scatter_bucket(reduce_scatter_bucket)
902 self.reduce_scatter_buckets = []
903 # Step3: luanch async allreduce buckets
904 self._issue_all_reduce_buckets(self.all_reduce_buckets, async_op)
905 if self.all_reduce_buckets:
906 self.comm_ctx.all_reduce_param_group = self
908 @staticmethod
909 def _apply_final_reduce_scatter_bucket(bucket: ReduceScatterBucket) -> None:
910 """Apply final FSDP gradients and finish any copies to the host."""
911 # Take ownership of the output before releasing the bucket. Each gradient below is a view of it.
912 output = bucket.move_reducescatter_output()
913 need_synchronize = False
914 for param, offset, numel in zip(bucket.hsdp_params, bucket.param_offsets, bucket.layout.param_numels):
915 grad_view = output.narrow(0, offset, numel)
916 if param.source_shard_info is None:
917 need_synchronize = param.apply_reduced_grad(grad_view) or need_synchronize
918 else:
919 # Keep the view for the root to finish the source-layout reduction before writeback.
920 param.reduce_scatter_comm_ctx.reduce_scatter_output = grad_view
921 if need_synchronize:
922 # Finish first-bind nonblocking copies before a later backward can
923 # accumulate into the CPU gradient, including an FP32 main_grad.
924 torch.get_device_module(output.device).current_stream(output.device).synchronize()
926 def wait_all_reduce_and_save_grad(self) -> None:
927 """Wait HSDP all-reduces and expose their per-parameter output views."""
928 for all_reduce_bucket in self.all_reduce_buckets:
929 if all_reduce_bucket.handle is not None:
930 all_reduce_bucket.handle.wait()
931 all_reduce_bucket.handle = None
932 if all_reduce_bucket.all_reduce_output is None:
933 raise RuntimeError("All-reduce output has already been released.")
934 if all_reduce_bucket.needs_avg_div and all_reduce_bucket.replicate_world_size > 1:
935 all_reduce_bucket.all_reduce_output.div_(all_reduce_bucket.replicate_world_size)
936 for hsdp_param, param_numel, param_offset in zip(
937 all_reduce_bucket.hsdp_params,
938 all_reduce_bucket.param_numels,
939 all_reduce_bucket.param_offsets,
940 ):
941 hsdp_param.all_reduce_comm_ctx.all_reduce_output = all_reduce_bucket.all_reduce_output.narrow(
942 0,
943 param_offset,
944 param_numel,
945 )
946 all_reduce_bucket.all_reduce_output = None
947 self.all_reduce_buckets = []
948 if self.comm_ctx.all_reduce_param_group is self:
949 self.comm_ctx.all_reduce_param_group = None
951 def reset_iter_state(self) -> None:
952 """Drop communication references after a completed iteration."""
953 for all_gather_bucket in self.all_gather_buckets:
954 if all_gather_bucket.all_gather_result is not None:
955 all_gather_bucket.all_gather_result.all_gather_input = None
956 all_gather_bucket.all_gather_result.all_gather_output = None
957 all_gather_bucket.all_gather_result.handle = None
958 all_gather_bucket.all_gather_result = None
959 for reduce_scatter_bucket in self.reduce_scatter_buckets:
960 reduce_scatter_bucket.unsharded_grads = []
961 reduce_scatter_bucket.reduce_scatter_input = None
962 reduce_scatter_bucket.reduce_scatter_output = None
963 reduce_scatter_bucket.handle = None
964 for all_reduce_bucket in self.all_reduce_buckets:
965 all_reduce_bucket.all_reduce_output = None
966 all_reduce_bucket.handle = None
967 self.reduce_scatter_buckets = []
968 self.all_reduce_buckets = []
969 self.reduce_partial_outputs.clear()
970 if self.comm_ctx.pre_param_group is self:
971 self.comm_ctx.pre_param_group = None
972 if self.comm_ctx.all_reduce_param_group is self:
973 self.comm_ctx.all_reduce_param_group = None
976class AllReduceParamGroup:
977 """Group HSDP parameters by replicate group for one fused async all-reduce.
979 Used by the ``comm_fusion=False`` path only: there each parameter issues its
980 own reduce-scatter, and this class re-fuses the resulting shards so the
981 replicate-dimension all-reduce is still a single collective. The
982 ``comm_fusion=True`` path never builds this group -- it fuses at the bucket
983 level via ``AllReduceBucket``.
985 Zero-copy is achieved by pre-allocating one contiguous buffer with 512-byte
986 alignment, having each ``reduce_scatter_grad`` write straight into an aligned
987 view of it, all-reducing the whole buffer once, and slicing gradients back
988 out of those views.
990 Numerical-correctness constraints (each is load-bearing, do not "simplify"):
992 - The all-reduce uses SUM. For AVG, ``wait_and_split_grads`` divides the
993 fused buffer by ``replicate_world_size`` before exposing parameter views.
994 - The buffer is zero-initialized so the padding regions contribute nothing
995 to the SUM.
997 Attributes:
998 replicate_group: Process group for the replicate dimension.
999 hsdp_params: Parameters sharing that replicate group.
1000 reduce_dtype: Uniform element type of the fused buffer.
1001 reduce_op: Caller-requested op (AVG or SUM); decides the final scaling.
1002 replicate_world_size: Size of the replicate group.
1003 fused_buffer: Contiguous aligned buffer for all parameters; released
1004 once ``wait_and_split_grads`` has handed out its views.
1005 param_offsets: Element offset of each parameter inside the buffer.
1006 param_numels: Padded element count of each parameter.
1007 all_reduce_handle: In-flight async all-reduce work, or None.
1008 """
1010 ALIGNMENT_BYTES = 512
1012 def __init__(
1013 self,
1014 replicate_group: dist.ProcessGroup,
1015 hsdp_params: List[HSDPParamV2],
1016 reduce_op: dist.ReduceOp,
1017 ) -> None:
1018 self.replicate_group = replicate_group
1019 self.hsdp_params = hsdp_params
1020 self.reduce_dtype = hsdp_params[0].reduce_comm_dtype()
1021 self.reduce_op = reduce_op
1022 self.replicate_world_size = replicate_group.size() if replicate_group else 1
1023 self.fused_buffer: Optional[torch.Tensor] = None
1024 self.param_offsets: List[int] = []
1025 self.param_numels: List[int] = []
1026 self.all_reduce_handle: Optional[dist.Work] = None
1028 def compute_aligned_layout(self) -> int:
1029 """Compute packed parameter offsets and align the total buffer size."""
1030 self.param_offsets = []
1031 self.param_numels = []
1032 element_size = torch.tensor([], dtype=self.reduce_dtype).element_size()
1033 current_offset = 0
1034 for hsdp_param in self.hsdp_params:
1035 numel = hsdp_param.padded_sharded_param_size.numel()
1036 self.param_numels.append(numel)
1037 self.param_offsets.append(current_offset)
1038 current_offset += numel
1039 total_bytes = current_offset * element_size
1040 aligned_total_bytes = (
1041 (total_bytes + self.ALIGNMENT_BYTES - 1) // self.ALIGNMENT_BYTES
1042 ) * self.ALIGNMENT_BYTES
1043 return aligned_total_bytes // element_size
1045 def allocate_fused_buffer(self, device: torch.device) -> None:
1046 """Allocate and zero the fused all-reduce buffer."""
1047 self.fused_buffer = torch.zeros(
1048 self.compute_aligned_layout(),
1049 dtype=self.reduce_dtype,
1050 device=device,
1051 )
1053 def get_param_buffer_view(self, index: int) -> torch.Tensor:
1054 """Return one parameter's padded communication view."""
1055 if self.fused_buffer is None:
1056 raise RuntimeError("Fused buffer not allocated. Call allocate_fused_buffer first.")
1057 return self.fused_buffer.narrow(
1058 0,
1059 self.param_offsets[index],
1060 self.param_numels[index],
1061 )
1063 def get_param_grad_view(self, index: int, target_shape: torch.Size) -> torch.Tensor:
1064 """Return one parameter's actual-shard gradient view."""
1065 return self.get_param_buffer_view(index).narrow(0, 0, target_shape.numel()).view(target_shape)
1067 def accumulate_reduce_partial_outputs(self) -> None:
1068 """Merge no-all-reduce micro-step outputs into the current buffer."""
1069 if self.fused_buffer is None:
1070 return
1071 for index, hsdp_param in enumerate(self.hsdp_params):
1072 if hsdp_param.reduce_partial_output is None:
1073 continue
1074 partial_output = hsdp_param.reduce_partial_output
1075 if partial_output.dtype != self.reduce_dtype:
1076 partial_output = partial_output.to(self.reduce_dtype)
1077 self.get_param_buffer_view(index).add_(partial_output.view(-1))
1078 hsdp_param.reduce_partial_output = None
1080 def issue_async_allreduce(self) -> None:
1081 """Launch SUM all-reduce and leave AVG scaling to the wait path."""
1082 if self.fused_buffer is None:
1083 raise RuntimeError("Fused buffer not allocated.")
1084 self.all_reduce_handle = dist.all_reduce(
1085 self.fused_buffer,
1086 op=dist.ReduceOp.SUM,
1087 group=self.replicate_group,
1088 async_op=True,
1089 )
1091 def wait_and_split_grads(self) -> None:
1092 """Wait all-reduce, apply AVG scaling if needed, and expose parameter views."""
1093 if self.all_reduce_handle is not None:
1094 self.all_reduce_handle.wait()
1095 self.all_reduce_handle = None
1096 if self.fused_buffer is not None and self.reduce_op == dist.ReduceOp.AVG and self.replicate_world_size > 1:
1097 self.fused_buffer.div_(self.replicate_world_size)
1098 for index, hsdp_param in enumerate(self.hsdp_params):
1099 reduced_grad = self.get_param_grad_view(index, hsdp_param.sharded_size)
1100 context = hsdp_param.all_reduce_comm_ctx
1101 if context.all_reduce_output is None:
1102 context.all_reduce_output = reduced_grad
1103 else:
1104 # Deferred finalization can deliver several results for one parameter.
1105 context.all_reduce_output.add_(reduced_grad)
1106 self.fused_buffer = None