Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / fully_shard / hsdp_scheduler.py: 91%
497 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 scheduler"""
16import functools
17import inspect
18from collections import deque
19from itertools import chain
20from typing import Any, Callable, List, Mapping, Optional, ParamSpec, Tuple, TypeVar, Union
22import torch
23from torch import nn
24from torch.autograd import Variable
25from torch.utils._pytree import tree_flatten, tree_unflatten
27from hyper_parallel.core.dtensor.device_mesh import DeviceMesh
28from hyper_parallel.core.fully_shard.hook_function import PostBackwardFunction
29from hyper_parallel.core.fully_shard.hsdp_utils import (
30 FSDPSchedulerState,
31 get_managed_modules_parameters,
32)
33from hyper_parallel.core.fully_shard.utils import (
34 CommFusionPolicy,
35 SourceShardMetaInfo,
36 apply_to_tensors,
37 cast_fp_tensor,
38 parameters_dict,
39 profiler_record,
40)
41from hyper_parallel.tools.logging import get_logger
43logger = get_logger("FSDP")
45nn.Module = nn.Module
47_P = ParamSpec("_P")
48_R = TypeVar("_R")
51def _dynamo_disable(func: Callable[_P, _R]) -> Callable[_P, _R]:
52 """Disable Dynamo tracing while an FSDP runtime hook executes."""
54 @functools.wraps(func)
55 def wrapper(*args: _P.args, **kwargs: _P.kwargs) -> _R:
56 return torch._dynamo.disable(
57 func,
58 recursive=True,
59 )(*args, **kwargs)
61 return wrapper
64class ParamGroupCommCtx:
65 """Track the in-flight parameter-group communication for one module tree."""
67 def __init__(self) -> None:
68 self.pre_param_group = None
69 self.all_reduce_param_group = None
70 self.comm_handle = None
73class HSDPSchedulerContext:
74 """Share scheduler and backward-pipeline state within one HSDP module tree."""
76 def __init__(self) -> None:
77 """Initialize bookkeeping and communication queues for a module tree."""
78 self.is_last_backward: bool = True
79 self.root_module = None
80 # Compile tracing may enter the root more than once; initialize shared
81 # parameter state only on the first real forward.
82 self.lazy_init_done: bool = False
83 self.root_bp_state = False
84 self.post_backward_final_callback_queued = False
85 self.defer_grad_finalize = False
86 # all_hsdp_schedulers (for one module tree structure), deduplicated at
87 # registration time because ``fully_shard`` may be given a module list
88 # whose modules share one scheduler.
89 self.all_hsdp_schedulers = []
90 # Parameter FQNs are initialized once after all schedulers share this context.
91 self._param_fqn_initialized = False
92 # Each queue entry normally belongs to one non-fused unit, including empty units.
93 # Configuration and queues are shared by the entire module tree.
94 self.reduce_interval: int = 1
95 self.pre_reduce_scatter_params = deque()
96 self.pre_all_reduce_params = []
97 self.pre_direct_all_reduce_grads = []
98 self.pre_all_reduce_groups = deque()
99 self.pending_all_reduce_groups = []
100 self.param_group_comm_ctx = ParamGroupCommCtx()
102 def merge_reduce_scatter_tail(self) -> None:
103 """Keep the last two entries in one batch for the next PP backward."""
104 if len(self.pre_reduce_scatter_params) < 2:
105 return
106 params = self.pre_reduce_scatter_params.pop()
107 groups = self.pre_all_reduce_groups.pop()
108 self.pre_reduce_scatter_params[-1].extend(params)
109 self.pre_all_reduce_groups[-1].extend(groups)
112class HSDPSchedulerV2:
113 """HSDPScheduler is used to scheduler hsdp"""
115 def __init__(
116 self,
117 cell: Union[nn.Module, Tuple[nn.Module, ...]],
118 mesh,
119 reshard_after_forward,
120 shard_placement_fn,
121 mp_policy,
122 offload_policy,
123 ignored_params,
124 replicate_params,
125 device,
126 comm_fusion,
127 comm_fusion_zero_copy=False,
128 source_shard_infos: Optional[Mapping[nn.Parameter, SourceShardMetaInfo]] = None,
129 ):
130 """init hsdp scheduler.
132 Args:
133 cell: A single module or tuple of modules to manage as one FSDP unit.
134 mesh: Explicit data-parallel device mesh.
135 reshard_after_forward: Whether to reshard parameters after forward.
136 shard_placement_fn: Optional function selecting the parameter shard dimension.
137 mp_policy: Mixed-precision policy.
138 offload_policy: Parameter offload policy.
139 ignored_params: Parameters excluded from fully_shard management.
140 replicate_params: Managed parameters that remain replicated.
141 device: Target device for parameters.
142 comm_fusion: Communication fusion configuration.
143 comm_fusion_zero_copy: Whether fused communication writes into views.
144 source_shard_infos: Optional per-parameter TP/EP source metadata.
145 """
146 self.modules = (cell,) if isinstance(cell, nn.Module) else tuple(cell)
147 self.cell = self.modules[0]
148 self.mesh: DeviceMesh = mesh
149 self.shard_placement_fn = shard_placement_fn
150 self.mp_policy = mp_policy
151 self.offload_policy = offload_policy
152 self.comm_fusion_policy = CommFusionPolicy(comm_fusion, comm_fusion_zero_copy)
153 self.ignored_params = ignored_params
154 self.replicate_params = replicate_params
155 self.device = device
156 self.reshard_after_forward = reshard_after_forward
157 self.source_shard_infos = source_shard_infos
158 self.scheduler_state = None
159 self.forward_prefetch_cells = []
160 self.backward_prefetch_cells = []
161 self._backup_forward_fetch = None
162 # Flag to identify root module.
163 self._is_root = True
164 # module and its all sub-modules share one same 'HSDPSchedulerContext'
165 self.scheduler_ctx = HSDPSchedulerContext()
166 # When ``fully_shard`` is given multiple root modules, forward pre/post hooks coordinate
167 # so unshard / PostBackward / reshard run once per forward (aligned with PyTorch FSDP2).
168 self._fsdp_group_post_pending: Optional[set] = set() if len(self.modules) > 1 else None
169 self._new_cell_state()
170 self._register_hooks()
172 def _new_cell_state(self):
173 """Create the HSDP state that owns this scheduler's managed parameters."""
174 # Imported lazily: ``state`` pulls in ``param_group``, which imports this
175 # module for ``ParamGroupCommCtx``.
176 from hyper_parallel.core.fully_shard.hsdp_state import ( # pylint: disable=C0415
177 HSDPStateV2,
178 )
180 self.hsdp_state = HSDPStateV2(
181 self.modules,
182 self.mesh,
183 self.shard_placement_fn,
184 self.comm_fusion_policy,
185 self.mp_policy,
186 self.offload_policy,
187 self.ignored_params,
188 self.replicate_params,
189 self.scheduler_ctx,
190 self.device,
191 source_shard_infos=self.source_shard_infos,
192 )
194 def _register_hooks(self):
195 """Register the forward and backward hooks driving shard/unshard."""
196 self._register_forward_backward_hooks()
198 def _get_managed_params(self):
199 """Return deduplicated parameters from all managed modules."""
200 return get_managed_modules_parameters(self.modules, self.ignored_params)
202 def set_reshard_after_forward(self, reshard_after_forward: bool) -> None:
203 """Set reshard_after_forward flag.
205 Args:
206 reshard_after_forward: Whether to reshard parameters after forward.
207 """
208 if not isinstance(reshard_after_forward, bool):
209 raise ValueError(f"reshard_after_forward should be a bool, got {type(reshard_after_forward)}")
210 self.reshard_after_forward = reshard_after_forward
212 def set_reshard_after_backward(self, reshard_after_backward: bool) -> None:
213 """Set reshard_after_backward flag.
215 Args:
216 reshard_after_backward: Whether to reshard after backward completes.
217 """
218 if not isinstance(reshard_after_backward, bool):
219 raise ValueError(f"reshard_after_backward should be a bool, got {type(reshard_after_backward)}")
220 if self.hsdp_state is not None:
221 self.hsdp_state.reshard_after_backward = reshard_after_backward
223 def set_requires_all_reduce(self, requires_all_reduce: bool) -> None:
224 """Set requires_all_reduce flag.
226 Args:
227 requires_all_reduce: Whether this unit participates in all-reduce.
228 """
229 if not isinstance(requires_all_reduce, bool):
230 raise ValueError(f"requires_all_reduce should be a bool, got {type(requires_all_reduce)}")
231 if self.hsdp_state is not None:
232 self.hsdp_state.set_requires_all_reduce(requires_all_reduce)
234 @_dynamo_disable
235 def reset_iter_state(self) -> None:
236 """Reset scheduler bookkeeping after a completed iteration."""
237 self.scheduler_ctx.root_bp_state = False
238 self.scheduler_ctx.post_backward_final_callback_queued = False
239 self.scheduler_ctx.pre_direct_all_reduce_grads.clear()
240 self.scheduler_ctx.param_group_comm_ctx.pre_param_group = None
241 self.scheduler_ctx.param_group_comm_ctx.all_reduce_param_group = None
242 self.scheduler_ctx.param_group_comm_ctx.comm_handle = None
243 self.scheduler_state = None
244 if self._fsdp_group_post_pending is not None:
245 self._fsdp_group_post_pending.clear()
246 self._restore_forward_prefetch_after_recompute()
247 self.hsdp_state.reset_iter_state()
249 def abort_iter_state(self) -> None:
250 """Discard an interrupted iteration after the device has been stopped.
252 The recovery coordinator must first abort outstanding device work
253 and park the training thread. Unlike ordinary finalization this
254 path never waits on a failed collective, reads an unsharded buffer,
255 or replaces a persistent sharded parameter.
256 """
257 state = self.hsdp_state
258 self.reset_iter_state()
259 for param in state.hsdp_params:
260 param.sharded_param.grad = None
261 if hasattr(param.sharded_param, "main_grad"):
262 param.sharded_param.main_grad = None
263 param._setattr_on_modules(param.sharded_param)
264 # Avoid to_sharded(): a failure before the first all-gather may
265 # leave unsharded_param_buffers empty.
266 if param.unsharded_param_buffers and param.unsharded_param_buffers[0] is not param._sharded_param_data:
267 param.free_unsharded_param()
268 param.sharded_state = type(param.sharded_state).SHARDED
269 state.is_shard = True
271 def set_requires_grad_sync(self, requires_grad_sync: bool) -> None:
272 """Set flag controlling whether gradients are synchronized.
274 Args:
275 requires_grad_sync: When True, enable grad sync for this scheduler.
276 """
277 if not isinstance(requires_grad_sync, bool):
278 raise ValueError(f"requires_grad_sync should be a bool, got {type(requires_grad_sync)}")
279 self.hsdp_state.set_requires_grad_sync(requires_grad_sync)
281 def lazy_init(self) -> None:
282 """Register the module tree and initialize its sharded states once."""
283 if self.scheduler_ctx.defer_grad_finalize and self.scheduler_ctx.reduce_interval != 1:
284 raise ValueError("Deferred gradient finalization requires reduce_interval=1")
285 if self.scheduler_ctx.lazy_init_done:
286 return
287 # HSDPModule imports the scheduler to implement its public API.
288 from hyper_parallel.core.fully_shard.api import HSDPModule # pylint: disable=import-outside-toplevel
289 # Share the root context and register each unit's module name once.
290 if self.scheduler_ctx.root_module is None:
291 tree_ctx = self.scheduler_ctx
292 tree_ctx.root_module = self.cell
293 registered_schedulers = set()
294 for module_name, module in tree_ctx.root_module.named_modules():
295 if not isinstance(module, HSDPModule):
296 continue
297 submod_scheduler = module.hsdp_scheduler
298 if submod_scheduler is None or submod_scheduler in registered_schedulers:
299 continue
300 registered_schedulers.add(submod_scheduler)
301 if submod_scheduler.scheduler_ctx is not tree_ctx:
302 if submod_scheduler.scheduler_ctx.root_module is not None:
303 raise ValueError("HSDP scheduler already belongs to another initialized module tree")
304 submod_scheduler.scheduler_ctx = tree_ctx
305 submod_scheduler.hsdp_state.scheduler_ctx = tree_ctx
306 if submod_scheduler.hsdp_state.param_group is not None:
307 submod_scheduler.hsdp_state.param_group.comm_ctx = tree_ctx.param_group_comm_ctx
308 submod_scheduler._is_root = submod_scheduler is self # pylint: disable=protected-access
309 submod_scheduler.hsdp_state.module_name = module_name
310 tree_ctx.all_hsdp_schedulers.append(submod_scheduler)
311 # Initialize parameter names and reset sharded state.
312 self._init_params_fqn()
313 self._lazy_init_all_states()
314 self.scheduler_ctx.lazy_init_done = True
316 def _hsdp_forward_pre_hook(self, unused_cell, args, kwargs):
317 """Forward pre hook to unsharded parameter for forward process."""
318 logger.debug("hook=forward_pre enter module=%s", self.hsdp_state)
319 if self.scheduler_state == FSDPSchedulerState.PRE_BACKWARD:
320 logger.debug("hook=forward_pre skip module=%s reason=pre_backward", self.hsdp_state)
321 return args, kwargs
322 if self.scheduler_ctx.root_bp_state:
323 self._disable_forward_prefetch_for_recompute()
324 self.lazy_init()
325 self.scheduler_state = FSDPSchedulerState.PRE_FORWARD
326 if self.mp_policy.cast_forward_inputs and self.mp_policy.param_dtype:
327 cast_fn = functools.partial(cast_fp_tensor, self.mp_policy.param_dtype)
328 args = apply_to_tensors(cast_fn, args)
329 kwargs = apply_to_tensors(cast_fn, kwargs)
330 with profiler_record(f"pre_forward unshard:{self.hsdp_state.module_name}"):
331 logger.debug("hook=forward_pre action=unshard module=%s", self.hsdp_state)
332 self.hsdp_state.unshard()
333 for prefetch_cell in self.forward_prefetch_cells:
334 prefetch_state = prefetch_cell.hsdp_scheduler.hsdp_state
335 with profiler_record(f"pre_forward prefetch:"
336 f"{prefetch_state.module_name}"):
337 logger.debug(
338 "hook=forward_pre action=prefetch module=%s target=%s",
339 self.hsdp_state,
340 prefetch_state,
341 )
342 prefetch_state.prefetch()
343 return args, kwargs
345 def _lazy_init_all_states(self):
346 if self._is_root and self.scheduler_ctx.root_module is not None:
347 for submod_scheduler in self.scheduler_ctx.all_hsdp_schedulers:
348 hsdp_state = submod_scheduler.hsdp_state
349 if hsdp_state:
350 hsdp_state.lazy_init()
352 def _init_params_fqn(self): # pylint: disable=W0212
353 if not self._is_root or self.scheduler_ctx.root_module is None:
354 return
355 if self.scheduler_ctx._param_fqn_initialized: # pylint: disable=protected-access
356 return
357 # Build a map from original (sharded) parameter tensor to its HSDPParam wrapper.
358 param_to_hsdp_param = {}
359 for submod_scheduler in self.scheduler_ctx.all_hsdp_schedulers:
360 hsdp_state = submod_scheduler.hsdp_state
361 if hsdp_state is None:
362 continue
363 for hsdp_param in hsdp_state.hsdp_params:
364 orig_param = hsdp_param.sharded_param
365 # Shared parameters: keep only the first mapping to preserve the
366 # first-seen FQN (consistent with the deduplication in _init_hsdp_params).
367 if orig_param not in param_to_hsdp_param:
368 param_to_hsdp_param[orig_param] = hsdp_param
370 # Walk the full parameter tree and assign FQNs; skip params already seen
371 # (shared-parameter deduplication: first name wins).
372 visited_params = set()
373 for param_name, parameter in parameters_dict(self.scheduler_ctx.root_module):
374 if parameter in visited_params:
375 continue
376 visited_params.add(parameter)
377 hsdp_param = param_to_hsdp_param.get(parameter)
378 if hsdp_param is not None:
379 hsdp_param._param_fqn = param_name # pylint: disable=W0212
380 self.scheduler_ctx._param_fqn_initialized = True # pylint: disable=protected-access
382 # pylint: disable=W0613, R1710
383 def _hsdp_forward_hook(self, cell, inputs, outputs):
384 """Forward hook to shard parameter for saving memory."""
385 logger.debug("hook=forward enter module=%s", self.hsdp_state)
386 if self.scheduler_state == FSDPSchedulerState.PRE_BACKWARD:
387 logger.debug("hook=forward skip module=%s reason=pre_backward", self.hsdp_state)
388 return
389 self.scheduler_state = FSDPSchedulerState.FORWARD
390 if self.reshard_after_forward:
391 with profiler_record(f"forward reshard:{self.hsdp_state.module_name}"):
392 logger.debug("hook=forward action=reshard module=%s", self.hsdp_state)
393 self.hsdp_state.shard()
394 if self.mp_policy.output_dtype is not None:
395 outputs = apply_to_tensors(
396 functools.partial(cast_fp_tensor, self.mp_policy.output_dtype),
397 outputs,
398 )
399 return outputs
401 # pylint: disable=W0613
402 def _hsdp_backward_pre_hook(self, cell, grad_outputs):
403 """Backward pre hook to unsharded parameter for backward process."""
404 logger.debug("hook=backward_pre enter module=%s", self.hsdp_state)
405 self.scheduler_state = FSDPSchedulerState.PRE_BACKWARD
406 with profiler_record(f"pre_backward unshard:{self.hsdp_state.module_name}"):
407 logger.debug("hook=backward_pre action=unshard module=%s", self.hsdp_state)
408 self.hsdp_state.unshard()
409 for prefetch_cell in self.backward_prefetch_cells:
410 prefetch_state = prefetch_cell.hsdp_scheduler.hsdp_state
411 with profiler_record(f"pre_backward prefetch:"
412 f"{prefetch_state.module_name}"):
413 logger.debug(
414 "hook=backward_pre action=prefetch module=%s target=%s",
415 self.hsdp_state,
416 prefetch_state,
417 )
418 prefetch_state.prefetch()
420 # pylint: disable=W0613
421 def _hsdp_backward_hook(self, cell, grad_inputs, grad_outputs):
422 """Backward hook to shard parameter for optimizer process or saving memory."""
423 logger.debug("hook=backward_hook enter module=%s", self.hsdp_state)
424 self.scheduler_state = FSDPSchedulerState.BACKWARD
425 with profiler_record(f"post_backward:{self.hsdp_state.module_name}"):
426 logger.debug("hook=backward_hook action=post_backward module=%s", self.hsdp_state)
427 # An empty root would consume a child's tail without issuing its own work.
428 if not self.scheduler_ctx.defer_grad_finalize or self.hsdp_state.hsdp_params:
429 self.hsdp_state.post_backward()
430 if self._fsdp_group_post_pending is not None:
431 self._fsdp_group_post_pending.clear()
433 # pylint: disable=W0613
434 @staticmethod
435 def _grouped_forward_pre_hook_skip(cell, args, kwargs) -> None:
436 """Return value when grouped pre-forward should not run (first module already did).
438 ``nn.Module`` pre-hooks use ``None`` for a no-op.
439 """
440 return None
442 @staticmethod
443 def _grouped_forward_post_hook_skip(outputs) -> None:
444 """Return value when grouped post-forward is deferred to a later module.
446 ``nn.Module`` forward hooks use ``None`` for a no-op.
447 """
448 return None
450 @_dynamo_disable
451 def _grouped_forward_pre_hook(self, cell, args, kwargs):
452 """Run FSDP pre-forward only for the first module in the group (PyTorch FSDP2-aligned)."""
453 pending = self._fsdp_group_post_pending
454 if pending is None:
455 return self._forward_pre_hook(cell, args, kwargs)
456 if len(pending) == 0:
457 pending.update(self.modules)
458 return self._forward_pre_hook(cell, args, kwargs)
459 return self._grouped_forward_pre_hook_skip(cell, args, kwargs)
461 def _make_grouped_forward_post_hook(self, mod):
462 """Build post-forward hook: last module in the group runs reshard + output backward hooks."""
464 def grouped_post_hook(cell, inputs, outputs):
465 pending = self._fsdp_group_post_pending
466 if pending is None:
467 return self._forward_hook(cell, inputs, outputs)
468 pending.discard(mod)
469 if len(pending) == 0:
470 return self._forward_hook(cell, inputs, outputs)
471 return self._grouped_forward_post_hook_skip(outputs)
473 return grouped_post_hook
475 def set_forward_prefetch_cells(self, hsdp_cell_list: List[Any]) -> None:
476 """Set cells prefetched during forward.
478 Args:
479 hsdp_cell_list: HSDP cells to prefetch ahead of forward.
480 """
481 self.forward_prefetch_cells = hsdp_cell_list
483 def set_backward_prefetch_cells(self, hsdp_cell_list: List[Any]) -> None:
484 """Set cells prefetched during backward.
486 Args:
487 hsdp_cell_list: HSDP cells to prefetch ahead of backward.
488 """
489 self.backward_prefetch_cells = hsdp_cell_list
491 def _disable_forward_prefetch_for_recompute(self) -> None:
492 """Temporarily disable forward prefetch during activation recompute."""
493 self._backup_forward_fetch = self.forward_prefetch_cells
494 self.forward_prefetch_cells = []
496 def _restore_forward_prefetch_after_recompute(self) -> None:
497 """Restore the saved forward prefetch list after activation recompute."""
498 if self._backup_forward_fetch is None:
499 return
500 self.forward_prefetch_cells = self._backup_forward_fetch
501 self._backup_forward_fetch = None
503 def _register_post_backward_hook(self, args, kwargs):
504 """Wrap forward args/kwargs through PostBackwardFunction to register backward hook."""
505 if not torch.is_grad_enabled():
506 return args, kwargs
507 args_list, args_spec = tree_flatten(args)
508 kwargs_list, kwargs_spec = tree_flatten(kwargs)
509 args_kwargs_list = list(args_list) + list(kwargs_list)
510 inp_tensor_indices: List[int] = []
511 inp_tensors: List[torch.Tensor] = []
512 for i, obj in enumerate(args_kwargs_list):
513 if torch.is_tensor(obj) and obj.requires_grad:
514 inp_tensor_indices.append(i)
515 inp_tensors.append(obj)
516 if len(inp_tensors) == 0:
517 return args, kwargs # no tensors that require gradients
518 processed_tensors = PostBackwardFunction.apply(self, *inp_tensors)
519 for inp_tensor_idx, processed_tensor in zip(inp_tensor_indices, processed_tensors):
520 args_kwargs_list[inp_tensor_idx] = processed_tensor
521 args_list = args_kwargs_list[: len(args_list)]
522 kwargs_list = args_kwargs_list[len(args_list) :]
523 args = tree_unflatten(args_list, args_spec)
524 kwargs = tree_unflatten(kwargs_list, kwargs_spec)
525 return args, kwargs
527 @_dynamo_disable
528 def _forward_pre_hook(self, cell, args, kwargs):
529 """Execute forward pre hook and set up backward hook."""
530 args, kwargs = self._hsdp_forward_pre_hook(cell, args, kwargs)
531 return self._register_post_backward_hook(args, kwargs)
533 def _register_backward_pre_hook(self, outputs) -> None:
534 """Register gradient hooks on all requires-grad outputs to trigger backward pre hook."""
535 flat_outputs, _ = tree_flatten(outputs)
536 for output in flat_outputs:
537 if isinstance(output, torch.Tensor) and output.requires_grad:
538 handle_ref = [None]
539 # pylint: disable=C0103, W0102
541 def wrapper_for_backward_pre_hook(grad, _handle_ref=handle_ref):
542 """Remove this hook after it fires to prevent accmulation"""
543 handle = _handle_ref[0]
544 if handle is not None:
545 handle.remove()
546 return self._backward_pre_hook(grad)
547 # pylint: enable=C0103, W0102
548 handle = output.register_hook(wrapper_for_backward_pre_hook)
549 handle_ref[0] = handle
551 @_dynamo_disable
552 def _forward_hook(self, cell, inputs, outputs): # pylint: disable=R1710
553 """Execute forward hook."""
554 if self.scheduler_state == FSDPSchedulerState.PRE_BACKWARD:
555 return
556 self._register_backward_pre_hook(outputs)
557 if self.scheduler_ctx.root_bp_state:
558 self._restore_forward_prefetch_after_recompute()
559 return
560 return self._hsdp_forward_hook(cell, inputs, outputs)
562 # pylint: disable=W0212
563 @_dynamo_disable
564 def _backward_pre_hook(self, grad):
565 """Execute backward pre hook."""
566 if self.scheduler_state == FSDPSchedulerState.PRE_BACKWARD:
567 return grad
568 if not self.scheduler_ctx.post_backward_final_callback_queued:
569 self.scheduler_ctx.post_backward_final_callback_queued = True
570 root_scheduler = self.scheduler_ctx.root_module.hsdp_scheduler
571 Variable._execution_engine.queue_callback(root_scheduler._root_backward_hook)
572 self.scheduler_ctx.root_bp_state = True
573 self._hsdp_backward_pre_hook(self.cell, None)
574 return grad
576 @_dynamo_disable
577 def _root_backward_hook(self):
578 """Finish backward for all states and let PP finalize deferred gradients."""
579 logger.debug("hook=root_backward_hook enter module=%s", self.hsdp_state)
580 context = self.scheduler_ctx
581 for hsdp_scheduler in context.all_hsdp_schedulers:
582 # let modules which are not triggered backward_hook launch backward communication.
583 if context.defer_grad_finalize:
584 hsdp_scheduler._launch_remaining_backward_reductions()
585 else:
586 hsdp_scheduler._backward_hook()
587 hsdp_scheduler._finalize_unused_prefetches()
588 hsdp_scheduler.scheduler_state = None
589 hsdp_scheduler._restore_forward_prefetch_after_recompute()
590 self.scheduler_ctx.root_bp_state = False
591 if not context.defer_grad_finalize:
592 with torch.profiler.record_function(f"root_backward reduce:{self.hsdp_state.module_name}"):
593 logger.debug(
594 "hook=root_backward_hook action=final_reduce module=%s",
595 self.hsdp_state,
596 )
597 self._finalize_gradients()
598 self.scheduler_ctx.post_backward_final_callback_queued = False
600 def _launch_remaining_backward_reductions(self) -> None:
601 """Launch reductions for units without an autograd post-backward hook."""
602 if self.scheduler_state == FSDPSchedulerState.BACKWARD:
603 return
604 if self._fsdp_group_post_pending is not None:
605 self._fsdp_group_post_pending.clear()
606 state = self.hsdp_state
607 if not state.hsdp_params:
608 return
609 state.accumulate_grads_in_reduce_dtype_and_reshard()
610 if not state.reduce_grads:
611 return
612 if any(
613 param.reduce_scatter_comm_ctx.reduce_scatter_output is not None
614 and (param.unsharded_param.grad is not None or param.unsharded_accumulated_grad_data is not None)
615 for param in state.hsdp_params
616 ):
617 # Keep the full gradient on the parameter until the previous RS releases its slot.
618 return
619 state.issue_reduce_scatter_for_current_module()
620 self.scheduler_ctx.merge_reduce_scatter_tail()
622 def _finalize_unused_prefetches(self) -> None:
623 """Wait and release this scheduler's unused all-gathers after backward.
625 A module used in forward need not participate in this backward. Its
626 speculative prefetch may therefore have no pre-backward consumer.
627 """
628 state = self.hsdp_state
629 if state is None:
630 return
631 for param in state.hsdp_params:
632 context = param.allgather_comm_ctx
633 if context.allgather_handle is None and context.allgather_output is None:
634 continue
635 with profiler_record(f"finalize_unused_prefetch param:{param}"):
636 if context.allgather_handle is not None:
637 context.allgather_handle.wait()
638 context.allgather_handle = None
639 context.allgather_output = None
640 if state.is_shard and param.shard_world_size > 1:
641 param.free_unsharded_param()
642 if state.param_group is not None:
643 for bucket in state.param_group.all_gather_buckets:
644 result = bucket.all_gather_result
645 if result is None:
646 continue
647 param_fqns = ", ".join(str(param) for param in bucket.hsdp_params)
648 with profiler_record(f"finalize_unused_prefetch bucket:{state.module_name}:{param_fqns}"):
649 if result.handle is not None:
650 result.handle.wait()
651 result.handle = None
652 result.all_gather_input = None
653 result.all_gather_output = None
654 bucket.all_gather_result = None
656 def check_state_prefetch_handles_consumed(self) -> None:
657 """Check that all parameters in the module tree consumed their prefetch work.
659 Raises:
660 RuntimeError: If a parameter or fused bucket retains an all-gather
661 handle because the configured prefetch order is incorrect.
662 """
663 unconsumed_param_fqns = []
664 for hsdp_scheduler in self.scheduler_ctx.all_hsdp_schedulers:
665 hsdp_state = hsdp_scheduler.hsdp_state
666 if hsdp_state is None:
667 continue
668 unconsumed_param_fqns.extend(
669 str(param) for param in hsdp_state.hsdp_params
670 if param.allgather_comm_ctx.allgather_handle is not None
671 )
672 if hsdp_state.param_group is not None:
673 for bucket in hsdp_state.param_group.all_gather_buckets:
674 result = bucket.all_gather_result
675 if result is not None and result.handle is not None:
676 unconsumed_param_fqns.extend(str(param) for param in bucket.hsdp_params)
677 if unconsumed_param_fqns:
678 param_fqns = ", ".join(dict.fromkeys(unconsumed_param_fqns))
679 raise RuntimeError(
680 f"Unconsumed prefetch handles for parameters: {param_fqns}. "
681 "The prefetch order is incorrect. Set forward/backward prefetch order "
682 "according to the model's actual execution order."
683 )
685 def _finalize_comm_fusion_reductions(self) -> None:
686 """Drain the comm_fusion=True RS/AR pipeline."""
687 comm_ctx = self.scheduler_ctx.param_group_comm_ctx
688 if comm_ctx.all_reduce_param_group is not None:
689 logger.debug(
690 "hook=root_backward_hook wait=comm_fusion_all_reduce module=%s",
691 self.hsdp_state,
692 )
693 comm_ctx.all_reduce_param_group.wait_all_reduce_and_save_grad()
694 comm_ctx.all_reduce_param_group = None
695 if comm_ctx.pre_param_group is not None:
696 logger.debug(
697 "hook=root_backward_hook wait=comm_fusion_reduce_scatter module=%s",
698 self.hsdp_state,
699 )
700 comm_ctx.pre_param_group.wait_reduce_scatter_and_issue_all_reduce()
701 comm_ctx.pre_param_group = None
702 if comm_ctx.all_reduce_param_group is not None:
703 comm_ctx.all_reduce_param_group.wait_all_reduce_and_save_grad()
704 comm_ctx.all_reduce_param_group = None
706 def _finalize_per_param_reductions(self) -> None:
707 """Drain the module-tree-local comm_fusion=False RS/AR queues."""
708 # A fused root may own non-fused children, so always drain the tree queues.
709 self.flush_reduce_scatter()
710 self.wait_all_reduce()
712 def flush_reduce_scatter(self) -> None:
713 """Consume this tree's old shards and submit their replica reductions."""
714 while self.scheduler_ctx.pre_reduce_scatter_params:
715 last_all_reduce_groups = self.hsdp_state._wait_prev_reduce_scatter()
716 self.hsdp_state._wait_prev_reduce_scatter_without_all_reduce()
717 self.hsdp_state.issue_prev_fused_all_reduce(last_all_reduce_groups)
719 def wait_all_reduce(self) -> None:
720 """Wait for replica reductions already submitted in this tree."""
721 self.hsdp_state.wait_and_split_all_reduce_work_groups()
723 def launch_pending_reduce_scatter(self) -> None:
724 """Release occupied slots and submit full gradients left by the root hook."""
725 context = self.scheduler_ctx
726 direct_params = chain.from_iterable(context.pre_reduce_scatter_params)
727 replica_groups = chain.from_iterable(context.pre_all_reduce_groups)
728 replica_params = chain.from_iterable(group.hsdp_params for group in replica_groups)
729 blocked_params = {
730 param for param in chain(direct_params, replica_params)
731 if param.unsharded_param.grad is not None or param.unsharded_accumulated_grad_data is not None
732 }
733 if not blocked_params:
734 return
735 pending = []
736 for scheduler in context.all_hsdp_schedulers:
737 state = scheduler.hsdp_state
738 if state.reduce_grads and any(param in blocked_params for param in state.hsdp_params):
739 pending.append(state)
740 if not pending:
741 return
742 self.flush_reduce_scatter()
743 for state in pending:
744 state.issue_reduce_scatter_for_current_module()
745 context.merge_reduce_scatter_tail()
747 def _finalize_gradients(self) -> None:
748 """Finish all reductions and apply their completed results."""
749 if self.scheduler_ctx.defer_grad_finalize:
750 self.launch_pending_reduce_scatter()
751 self._finalize_comm_fusion_reductions()
752 self._finalize_per_param_reductions()
753 self.apply_reduced_gradients()
755 def apply_reduced_gradients(self) -> None:
756 """Apply pending reduced gradients after communication completes."""
757 for hsdp_scheduler in self.scheduler_ctx.all_hsdp_schedulers:
758 hsdp_state = hsdp_scheduler.hsdp_state
759 if hsdp_state is None:
760 continue
761 fused = hsdp_state.comm_fusion_policy.enable_comm_fusion
762 need_synchronize = False
763 for hsdp_param in hsdp_state.hsdp_params:
764 all_reduce_output = hsdp_param.all_reduce_comm_ctx.all_reduce_output
765 reduced_grad = all_reduce_output
766 if reduced_grad is None and fused:
767 # The fused wait publishes its ready shard here. The per-parameter
768 # wait already consumes its shard directly or submits replica AR.
769 reduced_grad = hsdp_param.reduce_scatter_comm_ctx.reduce_scatter_output
770 if reduced_grad is None:
771 continue
772 need_synchronize = hsdp_param.apply_reduced_grad(reduced_grad) or need_synchronize
773 if all_reduce_output is not None:
774 hsdp_param.clear_all_reduce_output()
775 else:
776 hsdp_param.clear_reduce_scatter_output()
777 hsdp_state._sync_current_stream_if_needed(need_synchronize)
779 @_dynamo_disable
780 def _backward_hook(self):
781 """Execute backward hook."""
782 if self.scheduler_state == FSDPSchedulerState.BACKWARD:
783 return
784 self._hsdp_backward_hook(self.cell, None, None)
786 @staticmethod
787 def _register_forward_module_hook(mod, hook) -> None:
788 """Register forward hook; use ``always_call=True`` when supported (matches PyTorch FSDP)."""
789 sig = inspect.signature(mod.register_forward_hook)
790 if "always_call" in sig.parameters:
791 mod.register_forward_hook(hook, prepend=False, always_call=True)
792 else:
793 mod.register_forward_hook(hook, prepend=False)
795 def _register_forward_backward_hooks(self):
796 """Register module forward and backward hook on all managed modules."""
797 if self._fsdp_group_post_pending is None:
798 for mod in self.modules:
799 mod.register_forward_pre_hook(self._forward_pre_hook, with_kwargs=True)
800 mod.register_forward_hook(self._forward_hook)
801 return
802 for mod in self.modules:
803 mod.register_forward_pre_hook(self._grouped_forward_pre_hook, with_kwargs=True)
804 grouped_forward_hook = _dynamo_disable(self._make_grouped_forward_post_hook(mod))
805 self._register_forward_module_hook(mod, grouped_forward_hook)