Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / pipeline_parallel / fsdp_comm_controller.py: 93%
191 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"""Own pipeline synchronization boundaries for deferred HSDP work."""
16from collections import defaultdict, deque
17from collections.abc import Sequence
19from hyper_parallel.core.dtensor.dtensor import DTensor
20from hyper_parallel.core.fully_shard.hsdp_state import HSDPStateV2
21from hyper_parallel.core.fully_shard.param_group import AllReduceParamGroup
22from hyper_parallel.core.pipeline_parallel._stage import PipelineStageBase
25class FSDPCommController:
26 """Coordinate stage-local HSDP gradients on the caller's current device stream."""
28 def __init__(self, stages: Sequence[PipelineStageBase], micro_batch_num: int) -> None:
29 """Record the stage-owned HSDP units and their settings."""
30 if micro_batch_num <= 0:
31 raise ValueError("micro_batch_num must be positive")
32 self.micro_batch_num = micro_batch_num
33 self.stage_schedulers = {}
34 self.stage_contexts = {}
35 self.user_settings = {}
36 self.current_settings = {}
37 self.context_settings = {}
38 self.completed_microbatches = {stage.stage_index: set() for stage in stages}
39 if len(self.completed_microbatches) != len(stages):
40 raise ValueError("Local pipeline stages must have distinct stage indices")
41 self.dx_microbatches = {stage.stage_index: set() for stage in stages}
42 self.reduction_tail_stage = None
43 self._handed_off_tail = None
44 self.retained_backward_units = set()
45 self._validate_stage_ownership(stages)
46 for stage in stages:
47 schedulers = stage.all_hsdp_schedulers
48 if not schedulers:
49 continue
50 context = schedulers[0].scheduler_ctx
51 self.stage_schedulers[stage.stage_index] = schedulers
52 self.stage_contexts[stage.stage_index] = context
53 for scheduler in schedulers:
54 settings = {
55 "reshard_after_forward": scheduler.reshard_after_forward,
56 "reshard_after_backward": scheduler.hsdp_state.reshard_after_backward,
57 "requires_gradient_sync": scheduler.hsdp_state.reduce_grads,
58 "requires_all_reduce": scheduler.hsdp_state.requires_all_reduce,
59 }
60 self.user_settings[scheduler] = settings
61 self.current_settings[scheduler] = settings.copy()
63 @staticmethod
64 def _validate_stage_ownership(stages: Sequence[PipelineStageBase]) -> None:
65 """Ensure a scheduler or mutable parameter is owned by one stage."""
66 scheduler_owners = set()
67 wrapper_owners = set()
68 parameter_owners = {}
69 storage_owners = {}
70 for stage in stages:
71 for scheduler in stage.all_hsdp_schedulers:
72 if scheduler in scheduler_owners:
73 raise ValueError("Pipeline stages must not share an HSDP scheduler")
74 scheduler_owners.add(scheduler)
75 for param in scheduler.hsdp_state.hsdp_params:
76 if param in wrapper_owners:
77 raise ValueError("Pipeline stages must not share HSDP parameter wrappers")
78 wrapper_owners.add(param)
80 # Storage identity also catches distinct Parameters created as views.
81 for param in stage.submodule.parameters():
82 if param in parameter_owners and parameter_owners[param] != stage.stage_index:
83 raise ValueError("Pipeline stages must not share parameter objects")
84 parameter_owners[param] = stage.stage_index
85 local_param = param.to_local() if isinstance(param, DTensor) else param
86 storage = local_param.untyped_storage()
87 if storage in storage_owners and storage_owners[storage] != stage.stage_index:
88 raise ValueError("Pipeline stages must not share mutable parameter storage")
89 storage_owners[storage] = stage.stage_index
91 def begin(self) -> None:
92 """Take ownership of root gradient finalization until the run completes.
94 An interrupted run keeps its saved settings and communication state;
95 starting another run must not overwrite that outstanding work.
96 """
97 has_recorded_microbatches = any(self.completed_microbatches.values()) or any(self.dx_microbatches.values())
98 has_reduction_tail = self.reduction_tail_stage is not None or self._handed_off_tail is not None
99 if self.context_settings or has_recorded_microbatches or has_reduction_tail:
100 raise RuntimeError("The previous pipeline run has unfinished HSDP work")
101 if any(context.reduce_interval != 1 for context in self.stage_contexts.values()):
102 raise ValueError("Deferred gradient finalization requires reduce_interval=1")
103 if any(context.root_bp_state for context in self.stage_contexts.values()):
104 raise RuntimeError("Set gradient finalization outside backward")
105 for stage_index, context in self.stage_contexts.items():
106 self.context_settings[stage_index] = context.defer_grad_finalize
107 context.defer_grad_finalize = True
109 def handoff_reduction_tail(self, backward_stages: set[int]) -> None:
110 """Take the previous tail unless this step reduces gradients for its owner."""
111 stage_index = self.reduction_tail_stage
112 if stage_index is None or stage_index in backward_stages:
113 return
114 context = self.stage_contexts[stage_index]
115 self.reduction_tail_stage = None
116 if not (context.pre_reduce_scatter_params or context.pending_all_reduce_groups):
117 return
118 # This step cannot reuse the owner's parameter slots. Transfer only the queues.
119 self._handed_off_tail = (
120 stage_index, context.pre_reduce_scatter_params, context.pre_all_reduce_groups,
121 context.pending_all_reduce_groups,
122 )
123 context.pre_reduce_scatter_params = deque()
124 context.pre_all_reduce_groups = deque()
125 context.pending_all_reduce_groups = []
127 def finish_handed_off_tail(self) -> None:
128 """Wait and apply the previous tail after the overlapping step returns."""
129 if self._handed_off_tail is None:
130 return
131 stage_index, params, groups, all_reduce = self._handed_off_tail
132 context = self.stage_contexts[stage_index]
133 if context.pre_reduce_scatter_params or context.pre_all_reduce_groups or context.pending_all_reduce_groups:
134 raise RuntimeError("The stage submitted gradients while its previous tail was handed off")
135 context.pre_reduce_scatter_params = params
136 context.pre_all_reduce_groups = groups
137 context.pending_all_reduce_groups = all_reduce
138 self._handed_off_tail = None
139 self.flush_reduce_scatter(stage_index)
140 self.wait_all_reduce(stage_index)
141 self.stage_schedulers[stage_index][0].apply_reduced_gradients()
143 def finish_backward(self, stage_index: int, micro_index: int) -> None:
144 """Launch any blocked root gradients after the chunk's backward returns."""
145 if self.reduction_tail_stage is not None and self.reduction_tail_stage != stage_index:
146 self.flush_reduce_scatter(self.reduction_tail_stage)
147 self.stage_schedulers[stage_index][0].launch_pending_reduce_scatter()
148 self.reduction_tail_stage = stage_index
149 self.completed_microbatches[stage_index].add(micro_index)
151 @staticmethod
152 def accumulate_grad_for_all_params_if_needed(hsdp_state: HSDPStateV2) -> None:
153 """Accumulate full gradients and retain them locally during no-sync steps."""
154 for param in hsdp_state.hsdp_params:
155 param.accumulate_unsharded_grad_if_needed()
156 if not hsdp_state.reduce_grads:
157 for param in hsdp_state.hsdp_params:
158 param.to_accumulated_grad_if_needed()
160 def reduce_dw_gradients(self, stage_index: int) -> None:
161 """Consume old work, then submit every ready unit without waiting on this batch."""
162 schedulers = self.stage_schedulers.get(stage_index)
163 if not schedulers:
164 return
166 old_groups = []
167 for old_stage_index in dict.fromkeys((self.reduction_tail_stage, stage_index)):
168 old_schedulers = self.stage_schedulers.get(old_stage_index)
169 if old_schedulers:
170 state = old_schedulers[0].hsdp_state
171 old_groups.append((state, state.wait_reduce_scatter()))
172 for scheduler in schedulers:
173 state = scheduler.hsdp_state
174 self.accumulate_grad_for_all_params_if_needed(state)
175 if state.reshard_after_backward:
176 state.shard()
177 context = self.stage_contexts[stage_index]
178 for scheduler in schedulers:
179 state = scheduler.hsdp_state
180 if state.reduce_grads and state.hsdp_params:
181 state.issue_reduce_scatter_for_current_module()
182 context.merge_reduce_scatter_tail()
183 for state, groups in old_groups:
184 state.issue_prev_fused_all_reduce(groups)
185 self.reduction_tail_stage = stage_index
187 def flush_reduce_scatter(self, stage_index: int) -> None:
188 """Consume only this stage's original queue and submit its ready AllReduce work."""
189 schedulers = self.stage_schedulers.get(stage_index)
190 if schedulers:
191 schedulers[0].flush_reduce_scatter()
193 def wait_all_reduce(self, stage_index: int) -> None:
194 """Wait already-submitted AllReduce work without launching ReduceScatter."""
195 schedulers = self.stage_schedulers.get(stage_index)
196 if schedulers:
197 schedulers[0].wait_all_reduce()
199 def _reduce_remaining_replica_grads(self, stage_index: int) -> None:
200 """Submit early microbatch shards left after the last ReduceScatter drain.
202 A parameter skipped in the last backward has no new full gradient to
203 trigger replica reduction. The regular AllReduce group consumes its
204 accumulated shard and publishes the result at the stage's usual wait.
205 """
206 for scheduler in self.stage_schedulers[stage_index]:
207 state = scheduler.hsdp_state
208 params_by_group_dtype = defaultdict(list)
209 for param in state.hsdp_params:
210 if param.reduce_partial_output is not None:
211 group_key = (param.mesh_info.replicate_process_group, param.reduce_comm_dtype())
212 params_by_group_dtype[group_key].append(param)
213 for (replica_group, _), params in params_by_group_dtype.items():
214 group = AllReduceParamGroup(replica_group, params, state.reduce_op_type)
215 group.allocate_fused_buffer(state.device)
216 state.issue_prev_fused_all_reduce([group])
218 def finalize(self) -> None:
219 """Finish a successful run, restore user settings, and preserve optimizer gradients.
221 Failures leave outstanding state visible and propagate to the caller.
222 Callbacks must have joined their compute threads.
223 """
224 if self.retained_backward_units:
225 raise RuntimeError("Overlap callbacks must release retained units")
226 for stage_index in self.stage_schedulers:
227 if self.dx_microbatches[stage_index]:
228 raise RuntimeError(f"Stage {stage_index} has unfinished weight backwards")
229 if self.completed_microbatches[stage_index] != set(range(self.micro_batch_num)):
230 raise RuntimeError(f"Stage {stage_index} did not complete every backward microbatch")
232 self.finish_handed_off_tail()
233 # Release outstanding slots before submitting any remaining full gradients.
234 for stage_index in self.stage_contexts:
235 self.flush_reduce_scatter(stage_index)
236 for schedulers in self.stage_schedulers.values():
237 for scheduler in schedulers:
238 state = scheduler.hsdp_state
239 self.accumulate_grad_for_all_params_if_needed(state)
240 state.issue_reduce_scatter_for_current_module()
241 for stage_index in self.stage_contexts:
242 self.flush_reduce_scatter(stage_index)
243 self._reduce_remaining_replica_grads(stage_index)
244 for stage_index in self.stage_contexts:
245 self.wait_all_reduce(stage_index)
246 for stage_index, schedulers in self.stage_schedulers.items():
247 schedulers[0].apply_reduced_gradients()
248 for scheduler in schedulers:
249 scheduler.hsdp_state.shard()
250 scheduler.reset_iter_state()
251 settings = self.user_settings[scheduler]
252 scheduler.set_reshard_after_forward(settings["reshard_after_forward"])
253 scheduler.set_reshard_after_backward(settings["reshard_after_backward"])
254 scheduler.set_requires_grad_sync(settings["requires_gradient_sync"])
255 scheduler.set_requires_all_reduce(settings["requires_all_reduce"])
256 self.current_settings[scheduler] = settings.copy()
257 self.stage_contexts[stage_index].defer_grad_finalize = self.context_settings[stage_index]
258 for completed in self.completed_microbatches.values():
259 completed.clear()
260 self.reduction_tail_stage = None
261 self.context_settings.clear()