Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / fully_shard / hsdp_state.py: 94%
311 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"""HSDP cell state"""
16# pylint: disable=protected-access
18from collections import defaultdict
19from typing import List, Mapping, Optional
21import torch
22from torch import nn
24from hyper_parallel.tools.logging import get_logger
25from hyper_parallel.core.dtensor.dtensor import DTensor
26from hyper_parallel.core.fully_shard.hsdp_utils import (
27 _get_param_module_infos,
28)
29from hyper_parallel.core.fully_shard.utils import (
30 CPUOffloadPolicy,
31 DDPMeshInfo,
32 FSDPMeshInfo,
33 HSDPMeshInfo,
34 SourceShardMetaInfo,
35)
36from hyper_parallel.core.fully_shard.hsdp_param import HSDPParamV2
37from hyper_parallel.core.fully_shard.param_group import HSDPParamGroup, AllReduceParamGroup
38from hyper_parallel.tools.dryrun.simulation import is_device_runtime_simulated
40logger = get_logger("FSDP")
42nn.Module = nn.Module
45def _to_dtype_if_needed(
46 tensor: torch.Tensor, dtype: Optional[torch.dtype]
47) -> torch.Tensor:
48 """Cast tensor to the given dtype if it differs from current dtype.
50 Args:
51 tensor: The input tensor to potentially cast.
52 dtype: Target dtype. If None or same as tensor dtype, no-op.
53 """
54 if dtype is not None and tensor.dtype != dtype:
55 return tensor.to(dtype)
56 return tensor
59class HSDPStateV2:
60 """HSDP state for cell"""
62 def __init__(
63 self,
64 cell,
65 mesh,
66 shard_placement_fn,
67 comm_fusion_policy,
68 mp_policy,
69 offload_policy,
70 raw_ignored_params,
71 raw_replicate_params,
72 scheduler_ctx,
73 device,
74 source_shard_infos: Optional[Mapping[torch.nn.Parameter, SourceShardMetaInfo]] = None,
75 ):
76 """
77 Initialize HSDPStateV2.
79 Args:
80 cell (nn.Module): The module whose parameters are managed by this state.
81 mesh: Mesh topology for shard/replicate dimensions.
82 shard_placement_fn: Optional function selecting the parameter shard dimension.
83 comm_fusion_policy: Communication fusion configuration.
84 mp_policy: Mixed-precision policy.
85 offload_policy: Parameter offload policy.
86 raw_ignored_params: Parameters excluded from fully_shard management.
87 raw_replicate_params: Managed parameters that remain replicated.
88 scheduler_ctx: Scheduler context shared by this module tree.
89 device (torch.device): Target device.
90 source_shard_infos: Optional per-parameter TP/EP source metadata.
91 """
92 self.source_shard_infos = source_shard_infos
93 self.modules = (cell,) if isinstance(cell, nn.Module) else tuple(cell)
94 self.cell = self.modules[0]
95 self.mesh = mesh
96 self.shard_placement_fn = shard_placement_fn
97 self.mp_policy = mp_policy
98 self.offload_policy = offload_policy
99 self.comm_fusion_policy = comm_fusion_policy
100 self.raw_ignored_params = set(raw_ignored_params or ())
101 self.raw_replicate_params = set(raw_replicate_params or ())
102 self.scheduler_ctx = scheduler_ctx
103 self.device = device
104 self.hsdp_params: List[HSDPParamV2] = []
105 self.param_group = None
106 self._move_states_to_device()
107 self._init_hsdp_params()
108 self.is_shard = True
109 self.module_name = None
110 # requires_gradient_sync
111 self.reduce_grads = True
112 # Reshard parameter after backward
113 self.reshard_after_backward = True
114 # Requires AllReduce for grad When HSDP
115 self.requires_all_reduce = True
116 self.set_reduce_op_type("avg")
117 self._reset_sharded_params = False
118 self._init_param_group()
120 def __repr__(self) -> str:
121 """Stable debug name used in log lines.
123 ``module_name`` is only assigned by the root forward pre-hook, so fall
124 back to the managed module class and object id before names are set.
125 Logging's ``%s`` calls this lazily -- only when a record is emitted.
126 """
127 if self.module_name:
128 return str(self.module_name)
129 return f"{self.cell.__class__.__name__}@{id(self.cell):x}"
131 def _init_param_group(self):
132 """Initialize fused parameter group for communication fusion.
134 All managed parameters enter one ``HSDPParamGroup``. Parameters without
135 an FSDP shard dimension use the group's local all-gather and
136 reduce-scatter paths before entering replicate all-reduce buckets.
137 """
138 self.param_group = None
139 if not self.comm_fusion_policy.enable_comm_fusion:
140 return
141 if self.hsdp_params:
142 # pylint: disable=E1128
143 self.param_group = HSDPParamGroup(
144 self.hsdp_params,
145 self.device,
146 self.comm_fusion_policy.comm_fusion_zero_copy,
147 comm_ctx=self.scheduler_ctx.param_group_comm_ctx,
148 )
150 def _move_states_to_device(self):
151 """move states to device"""
152 for mod in self.modules:
153 for param in mod.parameters():
154 if hasattr(param, "_hsdp_param_initialized") and param._hsdp_param_initialized:
155 continue
156 if param.device == self.device or param.device.type == "meta":
157 continue
158 param.data = param.to(self.device)
159 for buffer in mod.buffers():
160 if buffer.device == self.device or buffer.device.type == "meta":
161 continue
162 buffer.data = buffer.to(self.device)
164 def _build_param_source_shard_info(
165 self, param: torch.nn.Parameter
166 ) -> Optional[SourceShardMetaInfo]:
167 """Build normalized source-layout metadata for one managed parameter."""
168 if isinstance(param, DTensor):
169 if self.source_shard_infos is not None:
170 raise ValueError(
171 "source_shard_infos cannot be provided when fully_shard manages a native DTensor parameter"
172 )
173 return SourceShardMetaInfo(
174 mesh=param.device_mesh,
175 placements=tuple(param.placements),
176 origin_is_dtensor=True,
177 )
178 if self.source_shard_infos is None:
179 return None
180 return self.source_shard_infos.get(param)
182 def _init_hsdp_params(self):
183 """Initialize all fully_shard-managed parameters for the module."""
184 # all parameters in the module tree(s), deduplicated
185 visited_params = set()
186 filtered_params = []
187 for mod in self.modules:
188 for _, param in mod.named_parameters():
189 if param in self.raw_ignored_params:
190 continue
191 if hasattr(param, "_hsdp_param_initialized") and param._hsdp_param_initialized:
192 continue
193 if param in visited_params:
194 continue
195 visited_params.add(param)
196 filtered_params.append(param)
198 module_infos = _get_param_module_infos(filtered_params, tuple(self.modules))
199 for param, module_info in zip(filtered_params, module_infos):
200 self.hsdp_params.append(
201 HSDPParamV2(
202 param,
203 module_info,
204 self._build_param_mesh_info(param),
205 shard_placement_fn=self.shard_placement_fn,
206 mp_policy=self.mp_policy,
207 offload_policy=self.offload_policy,
208 device=self.device,
209 source_shard_info=self._build_param_source_shard_info(param),
210 )
211 )
213 def _build_param_mesh_info(self, parameter):
214 if self.mesh.ndim not in (1, 2):
215 raise ValueError(
216 "fully_shard only supports explicit 1D DP/FSDP meshes or 2D HSDP meshes. "
217 f"Got mesh.ndim={self.mesh.ndim}."
218 )
219 if parameter in self.raw_replicate_params:
220 return DDPMeshInfo(
221 mesh=self.mesh if self.mesh.ndim == 1 else self.mesh.flatten(),
222 replicate_mesh_dim=0,
223 )
224 if self.mesh.ndim == 1:
225 return FSDPMeshInfo(mesh=self.mesh, shard_mesh_dim=0)
226 return HSDPMeshInfo(
227 mesh=self.mesh,
228 shard_mesh_dim=1,
229 replicate_mesh_dim=0,
230 )
232 def _init_mp_dtypes(self):
233 """Initialize dtype attributes for each parameter from the mixed-precision policy."""
234 for hsdp_param in self.hsdp_params:
235 hsdp_param.init_dtype_attrs(self.mp_policy)
237 def _validate_cpu_offload_params(self):
238 """Validate that all parameters are on CPU when CPU offload policy is enabled."""
239 if not isinstance(self.offload_policy, CPUOffloadPolicy):
240 return
241 hsdp_params_not_on_cpu = [
242 hsdp_param
243 for hsdp_param in self.hsdp_params
244 if hsdp_param.sharded_param.device.type != "cpu"
245 ]
246 if hsdp_params_not_on_cpu:
247 raise RuntimeError(
248 "HSDP parameters should be materialized on CPU when enabling CPU offloading. "
249 'For example, load a CPU state dict or call module.to_empty(device="cpu"). '
250 "Found following parameters on non-CPU device: "
251 f"{[(p._param_fqn, p.sharded_param.device) for p in hsdp_params_not_on_cpu]}\n"
252 )
254 def lazy_init(self):
255 """Deferred initialization: reset sharded params, validate devices, and set mixed-precision dtypes."""
256 if self.is_shard and not self._reset_sharded_params:
257 for hsdp_param in self.hsdp_params:
258 hsdp_param.reset_sharded_param()
259 self._reset_sharded_params = True
260 self._validate_no_meta_params()
261 self._validate_cpu_offload_params()
262 self._init_mp_dtypes()
264 def _validate_no_meta_params(self):
265 param_names_on_meta = [
266 hsdp_param._param_fqn
267 for hsdp_param in self.hsdp_params
268 if hsdp_param.sharded_param.device.type == "meta"
269 ]
270 if param_names_on_meta:
271 raise RuntimeError(
272 "HSDP parameters should be materialized from meta device before training, "
273 f"but the following were still on meta device: {param_names_on_meta}\n"
274 "For example, call module.to_empty(device) to materialize to device and "
275 "call module.reset_parameters() on each module to initialize values."
276 )
278 def post_backward_for_comm_fusion(self):
279 """post_backward_for_comm_fusion."""
280 logger.debug("post_backward module=%s mode=comm_fusion enter", self)
281 # Fused gradient reduction path: first apply any pending async reduction
282 # from the previous module's backward (pipelined overlap), then issue
283 # this module's fused reduce-scatter (+ all-reduce for HSDP).
284 comm_ctx = self.scheduler_ctx.param_group_comm_ctx
285 # Phase 2: save gradients for the param group whose all-reduce is done.
286 if comm_ctx.all_reduce_param_group is not None:
287 logger.debug("post_backward module=%s wait=comm_fusion_all_reduce", self)
288 comm_ctx.all_reduce_param_group.wait_all_reduce_and_save_grad()
289 comm_ctx.all_reduce_param_group = None
290 # Phase 1: wait reduce_scatter, issue async all_reduce for previous layer
291 if comm_ctx.pre_param_group is not None:
292 logger.debug("post_backward module=%s wait=comm_fusion_reduce_scatter", self)
293 comm_ctx.pre_param_group.wait_reduce_scatter_and_issue_all_reduce()
294 comm_ctx.pre_param_group = None
295 if self.param_group is not None:
296 logger.debug("post_backward module=%s launch=comm_fusion_reduce_scatter", self)
297 self.param_group.foreach_reducescatter(
298 reduce_scatter_reduce_op=self.reduce_op_type,
299 )
301 def post_backward(self, *unused): # pylint: disable=unused-argument
302 """Reduce gradients and reshard parameters after backward."""
303 logger.debug(
304 "post_backward module=%s enter reduce_grads=%s comm_fusion=%s reshard_after_backward=%s",
305 self,
306 self.reduce_grads,
307 self.comm_fusion_policy.enable_comm_fusion,
308 self.reshard_after_backward,
309 )
310 for hsdp_param in self.hsdp_params:
311 hsdp_param.accumulate_unsharded_grad_if_needed()
312 if not self.reduce_grads:
313 if self.reshard_after_backward:
314 self.shard()
315 for hsdp_param in self.hsdp_params:
316 hsdp_param.to_accumulated_grad_if_needed()
317 return
318 if self.reshard_after_backward:
319 # Reshard before gradient communication to reduce backward memory peak.
320 self.shard()
321 if not self.comm_fusion_policy.enable_comm_fusion:
322 prev_group = []
323 if len(self.scheduler_ctx.pre_reduce_scatter_params) >= self.scheduler_ctx.reduce_interval:
324 prev_group = self._wait_prev_reduce_scatter()
325 self._wait_prev_reduce_scatter_without_all_reduce()
327 # Step 3: issue current reduce_scatter
328 self.issue_reduce_scatter_for_current_module()
330 # Step 4: issue previous fused all-reduce asynchronously
331 self.issue_prev_fused_all_reduce(prev_group)
332 else:
333 self.post_backward_for_comm_fusion()
335 def accumulate_grads_in_reduce_dtype_and_reshard(self) -> None:
336 """Accumulate unsharded gradients in the reduction dtype and reshard if enabled."""
337 for hsdp_param in self.hsdp_params:
338 hsdp_param.accumulate_unsharded_grad_if_needed()
339 if self.reshard_after_backward:
340 self.shard()
341 if not self.reduce_grads:
342 for hsdp_param in self.hsdp_params:
343 hsdp_param.to_accumulated_grad_if_needed()
345 def wait_reduce_scatter(self) -> List[AllReduceParamGroup]:
346 """Wait queued reductions and return the replica groups ready to launch."""
347 groups = []
348 while self.scheduler_ctx.pre_reduce_scatter_params:
349 groups.extend(self._wait_prev_reduce_scatter())
350 self._wait_prev_reduce_scatter_without_all_reduce()
351 return groups
353 def issue_reduce_scatter_for_current_module(self) -> None:
354 """Issue and queue ReduceScatter for the current module's parameters.
356 This method groups parameters by their replicate_process_group and:
357 1. For params without all_reduce needs: issue reduce_scatter directly
358 2. For params with all_reduce needs: allocate fused buffer and issue reduce_scatter
359 into aligned views, enabling zero-copy fused all_reduce later.
360 """
361 # Collect parameters that need gradient reduction
362 params_to_reduce = []
363 for hsdp_param in self.hsdp_params:
364 skip_param = (
365 not hasattr(hsdp_param, "_unsharded_param")
366 or not hsdp_param.unsharded_param_buffers
367 or not hsdp_param.sharded_param.requires_grad
368 or (
369 hsdp_param.unsharded_param.grad is None
370 and hsdp_param.unsharded_accumulated_grad_data is None
371 )
372 )
373 if skip_param:
374 continue
375 params_to_reduce.append(hsdp_param)
376 params_without_all_reduce = []
377 all_reduce_groups = []
379 # Group by replicate process group and reduction dtype so every fused
380 # all-reduce buffer has one communication group and one element type.
381 groups_by_comm = defaultdict(list)
382 for hsdp_param in params_to_reduce:
383 if self.requires_all_reduce and hsdp_param.replicate_world_size > 1:
384 replicate_process_group = hsdp_param.mesh_info.replicate_process_group
385 group_key = (id(replicate_process_group), hsdp_param.reduce_comm_dtype())
386 groups_by_comm[group_key].append(hsdp_param)
387 else:
388 groups_by_comm[None].append(hsdp_param)
390 # Handle params that don't need all_reduce (FSDP or single replica)
391 if None in groups_by_comm:
392 for hsdp_param in groups_by_comm[None]:
393 logger.debug(
394 "post_backward module=%s launch=reduce_scatter param=%s all_reduce=False",
395 self,
396 hsdp_param,
397 )
398 hsdp_param.reduce_scatter_grad(
399 reduce_op=self.reduce_op_type,
400 )
401 params_without_all_reduce.append(hsdp_param)
403 # Handle params that need all_reduce (HSDP with multiple replicas)
404 for group_key, hsdp_params in groups_by_comm.items():
405 if group_key is None:
406 continue
407 # Create AllReduceParamGroup for fused all-reduce
408 group = AllReduceParamGroup(
409 replicate_group=hsdp_params[0].mesh_info.replicate_process_group,
410 hsdp_params=hsdp_params,
411 reduce_op=self.reduce_op_type,
412 )
414 # Allocate fused buffer with 512-byte alignment
415 group.allocate_fused_buffer(self.device)
417 # Issue reduce_scatter with output directly into fused buffer views
418 logger.debug(
419 "post_backward module=%s launch=fused_reduce_scatter group_params=%s",
420 self,
421 hsdp_params,
422 )
423 for idx, hsdp_param in enumerate(hsdp_params):
424 buffer_view = group.get_param_buffer_view(idx)
425 hsdp_param.reduce_scatter_grad(
426 reduce_op=self.reduce_op_type,
427 output_buffer=buffer_view,
428 )
430 all_reduce_groups.append(group)
432 # Empty entries preserve the interval measured in module units.
433 self.scheduler_ctx.pre_reduce_scatter_params.append(params_without_all_reduce)
434 self.scheduler_ctx.pre_all_reduce_groups.append(all_reduce_groups)
436 def _wait_prev_reduce_scatter(self) -> List[AllReduceParamGroup]:
437 """Wait the oldest unit's reduce-scatter before replica all-reduce.
439 The shared interval determines how many subsequent units overlap it.
441 Returns:
442 List of previous AllReduceParamGroups (one per communication group).
443 """
444 if self.scheduler_ctx.pre_all_reduce_groups:
445 prev_groups = self.scheduler_ctx.pre_all_reduce_groups.popleft()
446 for prev_group in prev_groups:
447 logger.debug(
448 "post_backward module=%s wait=fused_reduce_scatter group_params=%s",
449 self,
450 prev_group.hsdp_params,
451 )
452 for hsdp_param in prev_group.hsdp_params:
453 reduced_grad = hsdp_param.reduce_scatter_output()
454 hsdp_param.all_reduce_source_replicate_grad_inplace(reduced_grad, torch.distributed.ReduceOp.SUM)
455 hsdp_param.clear_reduce_scatter_output()
456 return prev_groups
457 return []
459 def issue_prev_fused_all_reduce(self, prev_groups: List[AllReduceParamGroup]) -> None:
460 """Step 4: issue the previous module's fused all-reduce asynchronously.
462 The all-reduce work is collected in ``pending_all_reduce_groups``
463 and is waited in the root backward hook.
465 Args:
466 prev_groups: Previous parameter groups whose all-reduce should be issued.
467 """
468 for prev_group in prev_groups:
469 prev_group.accumulate_reduce_partial_outputs()
470 logger.debug(
471 "post_backward module=%s launch=fused_all_reduce group_params=%s",
472 self,
473 prev_group.hsdp_params,
474 )
475 prev_group.issue_async_allreduce()
476 self.scheduler_ctx.pending_all_reduce_groups.append(prev_group)
478 def _wait_prev_reduce_scatter_without_all_reduce(self) -> None:
479 """Wait RS outputs, accumulate partial results, and clear communication slots.
481 Single-replica partials are applied immediately. Multi-replica partials
482 remain for the existing AllReduceParamGroup to consume before all-reduce.
483 """
484 need_synchronize = False
485 params = (
486 self.scheduler_ctx.pre_reduce_scatter_params.popleft()
487 if self.scheduler_ctx.pre_reduce_scatter_params else ()
488 )
489 for pre_hsdp_param in params:
490 logger.debug(
491 "post_backward module=%s wait=reduce_scatter param=%s",
492 self,
493 pre_hsdp_param,
494 )
495 reduced_grad = pre_hsdp_param.reduce_scatter_output()
496 pre_hsdp_param.all_reduce_source_replicate_grad_inplace(reduced_grad, torch.distributed.ReduceOp.SUM)
497 if pre_hsdp_param.reduce_partial_output is None:
498 pre_hsdp_param.reduce_partial_output = reduced_grad
499 else:
500 pre_hsdp_param.reduce_partial_output.add_(reduced_grad)
501 pre_hsdp_param.clear_reduce_scatter_output()
503 if pre_hsdp_param.replicate_world_size <= 1:
504 # No replica all-reduce follows, so accumulate into the parameter
505 # gradient immediately and clear the consumed partial.
506 need_synchronize = (
507 pre_hsdp_param.apply_reduced_grad(pre_hsdp_param.reduce_partial_output) or need_synchronize
508 )
509 pre_hsdp_param.reduce_partial_output = None
511 self._sync_current_stream_if_needed(need_synchronize)
513 def wait_and_split_all_reduce_work_groups(self) -> None:
514 """Wait fused all-reduce work and expose each parameter result."""
515 for group in self.scheduler_ctx.pending_all_reduce_groups:
516 logger.debug(
517 "post_backward module=%s wait=fused_all_reduce group_params=%s",
518 self,
519 group.hsdp_params,
520 )
521 group.wait_and_split_grads()
522 self.scheduler_ctx.pending_all_reduce_groups.clear()
524 def reset_iter_state(self) -> None:
525 """Clear Torch communication bookkeeping without clearing optimizer gradients."""
526 self.scheduler_ctx.pre_reduce_scatter_params.clear()
527 self.scheduler_ctx.pre_all_reduce_params.clear()
528 self.scheduler_ctx.pre_all_reduce_groups.clear()
529 self.scheduler_ctx.pending_all_reduce_groups.clear()
530 if self.param_group is not None:
531 self.param_group.reset_iter_state()
532 for hsdp_param in self.hsdp_params:
533 hsdp_param.allgather_comm_ctx.allgather_handle = None
534 hsdp_param.allgather_comm_ctx.allgather_output = None
535 hsdp_param.reduce_scatter_comm_ctx.reduce_scatter_handle = None
536 hsdp_param.reduce_scatter_comm_ctx.reduce_scatter_output = None
537 hsdp_param.all_reduce_comm_ctx.all_reduce_handle = None
538 hsdp_param.all_reduce_comm_ctx.all_reduce_output = None
539 hsdp_param.reduce_partial_output = None
540 hsdp_param.unsharded_accumulated_grad = None
541 hsdp_param._grad = None
542 if hasattr(hsdp_param, "_unsharded_param"):
543 hsdp_param.unsharded_param.grad = None
545 def set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
546 """set requires grad sync flag to control gradient sync."""
547 self.reduce_grads = requires_grad_sync
549 def set_reduce_op_type(self, reduce_op_type: str) -> None:
550 """set reduce op type for gradient reduction."""
551 fsdp_support_reduce_op = {
552 "sum": torch.distributed.ReduceOp.SUM,
553 "avg": torch.distributed.ReduceOp.AVG,
554 }
555 reduce_op = reduce_op_type.lower().strip() if isinstance(reduce_op_type, str) else reduce_op_type
556 reduce_op_value = fsdp_support_reduce_op.get(reduce_op)
557 if reduce_op_value is None:
558 raise ValueError(
559 f"Unsupported reduce op type {reduce_op_type}, "
560 f"supported types are {list(fsdp_support_reduce_op.keys())}"
561 )
562 self.reduce_op_type = reduce_op_value
564 def shard(self) -> None:
565 """change parameters to sharded state"""
566 logger.debug(
567 "action=reshard module=%s params=%s",
568 self,
569 self.hsdp_params,
570 )
571 if self.is_shard:
572 return
573 for param in self.hsdp_params:
574 param.to_sharded()
575 self.is_shard = True
577 def unshard(self, async_op: bool = False) -> None:
578 """change parameters to unsharded state"""
579 logger.debug(
580 "action=unshard module=%s async_op=%s params=%s",
581 self,
582 async_op,
583 self.hsdp_params,
584 )
585 if not self.is_shard:
586 return
588 if self.comm_fusion_policy.enable_comm_fusion and self.param_group is not None:
589 self.param_group.unshard(async_op)
590 else:
591 for param in self.hsdp_params:
592 param.unshard(async_op)
593 if not async_op:
594 self.wait_for_unshard()
596 def prefetch(self) -> None:
597 """prefetch unsharded parameters"""
598 logger.debug(
599 "action=prefetch module=%s params=%s",
600 self,
601 self.hsdp_params,
602 )
603 self.unshard(async_op=True)
605 def wait_for_unshard(self) -> None:
606 """wait for all unshard parameters"""
607 logger.debug(
608 "action=wait_unshard module=%s params=%s",
609 self,
610 self.hsdp_params,
611 )
612 if not self.is_shard:
613 return
615 if self.comm_fusion_policy.enable_comm_fusion and self.param_group is not None:
616 self.param_group.wait_for_unshard()
617 else:
618 for param in self.hsdp_params:
619 param.wait_for_unshard()
620 self.is_shard = False
622 def set_gradient_scaling_factor(self, factor):
623 """Propagate the gradient scaling factor to the layer that applies it.
625 The factor is consumed on the reduce input: ``param_group.foreach_reduce``
626 for the fused (comm_fusion) path, or per-parameter ``reduce_scatter_grad``
627 / ``all_reduce_grad`` otherwise. The state does not hold a copy.
628 """
629 if self.param_group is not None:
630 self.param_group.gradient_scaling_factor = factor
631 else:
632 for hsdp_param in self.hsdp_params:
633 hsdp_param.gradient_scaling_factor = factor
635 def set_requires_all_reduce(self, requires_all_reduce: bool) -> None:
636 """Propagate the HSDP all-reduce switch to the active communication path."""
637 self.requires_all_reduce = requires_all_reduce
638 if self.param_group is not None:
639 self.param_group.requires_all_reduce = requires_all_reduce
641 def _sync_current_stream_if_needed(self, need_synchronize):
642 if need_synchronize:
643 if is_device_runtime_simulated():
644 # Logical simulation: the D2H grad copy completed in program
645 # order; there is no device stream to drain.
646 return
647 if self.device.type == "npu":
648 torch.npu.current_stream().synchronize()
649 elif self.device.type == "cuda":
650 torch.cuda.current_stream().synchronize()
651 else:
652 raise NotImplementedError(
653 f"Unsupported device type {self.device.type} for synchronization after CPU offload."
654 )