Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/core/fully_shard/hsdp_param.py 93.8% 1152
hyper_parallel/core/fully_shard/hsdp_scheduler.py 73.7% 257,259,269,272,276,280,401-402,557,575-585,591-592,706,713,721,747
hyper_parallel/core/fully_shard/hsdp_state.py 69.0% 336-342,434-435
hyper_parallel/core/fully_shard/param_group.py 91.3% 835,1079
hyper_parallel/core/pipeline_parallel/_stage.py 85.4% 84,107,140,168,297-302,304-306,380-381,384,471,489-491
hyper_parallel/core/pipeline_parallel/fsdp_comm_controller.py 93.6% 30,39,75-77,82,105,107,120,137,161
hyper_parallel/core/pipeline_parallel/mpipe/schedule.py 66.7% 200
hyper_parallel/core/pipeline_parallel/scheduler.py 75.0% 88,208,211,898,1017-1022
hyper_parallel/core/pipeline_parallel/stage.py 25.0% 137-139,141-149
hyper_parallel/core/fully_shard/hsdp_param.py
1148
1149
1150
1151
1152
1153
1154
1155
1156
        if (
            self.reduce_scatter_comm_ctx.reduce_scatter_handle is not None
            or self.reduce_scatter_comm_ctx.reduce_scatter_output is not None
        ):
            raise RuntimeError("Consume the previous ReduceScatter before reusing its communication slot")
        if self.unsharded_accumulated_grad is not None:
            self._grad = self.unsharded_accumulated_grad_data
            self.unsharded_accumulated_grad = None
        else:
hyper_parallel/core/fully_shard/hsdp_scheduler.py
253
254
255
256
257
258
259
260
261
262
263

    def lazy_init(self) -> None:
        """Register the module tree and initialize its sharded states once."""
        if self.scheduler_ctx.defer_grad_finalize and self.scheduler_ctx.reduce_interval != 1:
            raise ValueError("Deferred gradient finalization requires reduce_interval=1")
        if self.scheduler_ctx.lazy_init_done:
            return
        # HSDPModule imports the scheduler to implement its public API.
        from hyper_parallel.core.fully_shard.api import HSDPModule  # pylint: disable=import-outside-toplevel
        # Share the root context and register each unit's module name once.
        if self.scheduler_ctx.root_module is None:
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
            tree_ctx.root_module = self.cell
            registered_schedulers = set()
            for module_name, module in tree_ctx.root_module.named_modules():
                if not isinstance(module, HSDPModule):
                    continue
                submod_scheduler = module.hsdp_scheduler
                if submod_scheduler is None or submod_scheduler in registered_schedulers:
                    continue
                registered_schedulers.add(submod_scheduler)
                if submod_scheduler.scheduler_ctx is not tree_ctx:
                    if submod_scheduler.scheduler_ctx.root_module is not None:
                        raise ValueError("HSDP scheduler already belongs to another initialized module tree")
                    submod_scheduler.scheduler_ctx = tree_ctx
                    submod_scheduler.hsdp_state.scheduler_ctx = tree_ctx
                    if submod_scheduler.hsdp_state.param_group is not None:
                        submod_scheduler.hsdp_state.param_group.comm_ctx = tree_ctx.param_group_comm_ctx
                submod_scheduler._is_root = submod_scheduler is self  # pylint: disable=protected-access
                submod_scheduler.hsdp_state.module_name = module_name
                tree_ctx.all_hsdp_schedulers.append(submod_scheduler)
        # Initialize parameter names and reset sharded state.
397
398
399
400
401
402
403
404
405
406
        self.scheduler_state = FSDPSchedulerState.BACKWARD
        with profiler_record(f"post_backward:{self.hsdp_state.module_name}"):
            logger.debug("hook=backward_hook action=post_backward module=%s", self.hsdp_state)
            # An empty root would consume a child's tail without issuing its own work.
            if not self.scheduler_ctx.defer_grad_finalize or self.hsdp_state.hsdp_params:
                self.hsdp_state.post_backward()
        if self._fsdp_group_post_pending is not None:
            self._fsdp_group_post_pending.clear()

    # pylint: disable=W0613
553
554
555
556
557
558
559
560
561
        context = self.scheduler_ctx
        for hsdp_scheduler in context.all_hsdp_schedulers:
            # let modules which are not triggered backward_hook launch backward communication.
            if context.defer_grad_finalize:
                hsdp_scheduler._launch_remaining_backward_reductions()
            else:
                hsdp_scheduler._backward_hook()
            hsdp_scheduler._finalize_unused_prefetches()
            hsdp_scheduler.scheduler_state = None
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
        self.scheduler_ctx.post_backward_final_callback_queued = False

    def _launch_remaining_backward_reductions(self) -> None:
        """Launch reductions for units without an autograd post-backward hook."""
        if self.scheduler_state == FSDPSchedulerState.BACKWARD:
            return
        if self._fsdp_group_post_pending is not None:
            self._fsdp_group_post_pending.clear()
        state = self.hsdp_state
        if not state.hsdp_params:
            return
        state.accumulate_grads_in_reduce_dtype_and_reshard()
        if not state.reduce_grads:
            return
        if any(
            param.reduce_scatter_comm_ctx.reduce_scatter_output is not None
            and (param.unsharded_param.grad is not None or param.unsharded_accumulated_grad_data is not None)
            for param in state.hsdp_params
        ):
587
588
589
590
591
592
593
594
595
            and (param.unsharded_param.grad is not None or param.unsharded_accumulated_grad_data is not None)
            for param in state.hsdp_params
        ):
            # Keep the full gradient on the parameter until the previous RS releases its slot.
            return
        state.issue_reduce_scatter_for_current_module(append_to_tail=True)

    def _finalize_unused_prefetches(self) -> None:
        """Wait and release this scheduler's unused all-gathers after backward.
702
703
704
705
706
707
708
709
710
            param for param in chain(direct_params, replica_params)
            if param.unsharded_param.grad is not None or param.unsharded_accumulated_grad_data is not None
        }
        if not blocked_params:
            return
        pending = []
        for scheduler in context.all_hsdp_schedulers:
            state = scheduler.hsdp_state
            if state.reduce_grads and any(param in blocked_params for param in state.hsdp_params):
709
710
711
712
713
714
715
716
            state = scheduler.hsdp_state
            if state.reduce_grads and any(param in blocked_params for param in state.hsdp_params):
                pending.append(state)
        if not pending:
            return
        self.flush_reduce_scatter()
        for state in pending:
            state.issue_reduce_scatter_for_current_module(append_to_tail=True)
717
718
719
720
721
722
723
724

    def _finalize_gradients(self) -> None:
        """Finish all reductions and apply their completed results."""
        if self.scheduler_ctx.defer_grad_finalize:
            self.launch_pending_reduce_scatter()
        self._finalize_comm_fusion_reductions()
        self._finalize_per_param_reductions()
        self.apply_reduced_gradients()
743
744
745
746
747
748
749
750
751
                need_synchronize = hsdp_param.apply_reduced_grad(reduced_grad) or need_synchronize
                if all_reduce_output is not None:
                    hsdp_param.clear_all_reduce_output()
                else:
                    hsdp_param.clear_reduce_scatter_output()
            hsdp_state._sync_current_stream_if_needed(need_synchronize)

    @_dynamo_disable
    def _backward_hook(self):
hyper_parallel/core/fully_shard/hsdp_state.py
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
            self.post_backward_for_comm_fusion()

    def accumulate_grads_in_reduce_dtype_and_reshard(self) -> None:
        """Accumulate unsharded gradients in the reduction dtype and reshard if enabled."""
        for hsdp_param in self.hsdp_params:
            hsdp_param.accumulate_unsharded_grad_if_needed()
        if self.reshard_after_backward:
            self.shard()
        if not self.reduce_grads:
            for hsdp_param in self.hsdp_params:
                hsdp_param.to_accumulated_grad_if_needed()

    def wait_reduce_scatter(self) -> List[AllReduceParamGroup]:
        """Wait queued reductions and return the replica groups ready to launch."""
        groups = []
430
431
432
433
434
435
436
437
438
439

        context = self.scheduler_ctx
        if append_to_tail and context.pre_reduce_scatter_params:
            # One wait at the next post-backward must release every slot in the PP tail.
            context.pre_reduce_scatter_params[-1].extend(params_without_all_reduce)
            context.pre_all_reduce_groups[-1].extend(all_reduce_groups)
        else:
            # Empty slots preserve the interval measured in module units.
            context.pre_reduce_scatter_params.append(params_without_all_reduce)
            context.pre_all_reduce_groups.append(all_reduce_groups)
hyper_parallel/core/fully_shard/param_group.py
831
832
833
834
835
836
837
838
839
                    views_by_group.setdefault(key, []).append(output.narrow(0, offset, numel))

        for (group, _, _), views in views_by_group.items():
            if len(views) == 1:
                dist.all_reduce(views[0], op=dist.ReduceOp.SUM, group=group, async_op=False)
            else:
                packed = torch.cat(views)
                dist.all_reduce(packed, op=dist.ReduceOp.SUM, group=group, async_op=False)
                for view, reduced in zip(views, packed.split([view.numel() for view in views])):
1075
1076
1077
1078
1079
1080
            if context.all_reduce_output is None:
                context.all_reduce_output = reduced_grad
            else:
                # Deferred finalization can deliver several results for one parameter.
                context.all_reduce_output.add_(reduced_grad)
        self.fused_buffer = None
hyper_parallel/core/pipeline_parallel/_stage.py
80
81
82
83
84
85
86
87
                raise ValueError("HSDP pipeline stages require backward execution")
            scheduler = submodule.hsdp_scheduler
            root = scheduler.scheduler_ctx.root_module
            if scheduler.cell is not submodule or (root is not None and root is not submodule):
                raise ValueError("An HSDP parameter-management unit must belong to exactly one pipeline stage")
        self.fsdp_comm_controller = None
        self._after_forward_chunk = None
        self.retain_backward_graph = False
103
104
105
106
107
108
109
110
111
        """Configure a gradient-producing backward without consuming old communication."""
        if self.fsdp_comm_controller is None:
            return
        if micro_index not in range(self.fsdp_comm_controller.micro_batch_num):
            raise ValueError(f"Invalid backward microbatch {micro_index}")
        if micro_index in self.fsdp_comm_controller.completed_microbatches[self.stage_index]:
            raise RuntimeError(f"Stage {self.stage_index} already completed backward for microbatch {micro_index}")
        is_last_backward = (
            len(self.fsdp_comm_controller.completed_microbatches[self.stage_index])
136
137
138
139
140
141
142
143
144
        """Protect split-backward graphs and disable every gradient communication action."""
        if self.fsdp_comm_controller is None:
            return
        if micro_index not in range(self.fsdp_comm_controller.micro_batch_num):
            raise ValueError(f"Invalid input-backward microbatch {micro_index}")
        if (
            micro_index in self.fsdp_comm_controller.dx_microbatches[self.stage_index]
            or micro_index in self.fsdp_comm_controller.completed_microbatches[self.stage_index]
        ):
164
165
166
167
168
169
170
171
172

    def check_weight_backward_complete(self) -> None:
        """Require all split-backward graphs to be consumed at the end of a run."""
        if self._dw_cache:
            raise RuntimeError(f"Stage {self.stage_index} has unconsumed weight-backward graphs")

    def clear_cache(self) -> None:
        """clear cache."""
        for micro_index in tuple(self._reentrant_frames):
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
            )
            self._pending_autograd_params = [param for param in hsdp_params if param.sharded_param.requires_grad]

        if self._pending_autograd_params:
            pending = []
            full_parameters = []
            for param in self._pending_autograd_params:
                full_param = getattr(param, "unsharded_param", None)
                if full_param is None:
                    pending.append(param)
                else:
                    full_parameters.append(full_param)
            self._pp_autograd_params += tuple(full_parameters)
            self._pending_autograd_params = pending

    def _get_pp_autograd_params(self) -> tuple[torch.nn.Parameter, ...]:
        """Return the parameter leaves used by the stage's split backward."""
        if self._pp_autograd_params is None and not self.all_hsdp_schedulers:
376
377
378
379
380
381
382
383
384
385
386
387
388

        if not local_output:
            # Nothing to backprop through (e.g. all forward outputs detached).
            self._release_reentrant(micro_index)
            if not self.is_first_stage:
                self._populate_bwd_cache(micro_index)
            self._clear_recv_buffer(self.grad_recv_info, micro_index)
            self._clear_recv_buffer(self.args_recv_info, micro_index)
            self._finish_backward(micro_index)
            return

        grad_tensors = self._build_last_stage_sens() if self.is_last_stage else recv_args
        if micro_index in self._reentrant_frames:
467
468
469
470
471
472
473
474
        if self._dw_cache[micro_index] is None:
            self._dw_cache.pop(micro_index)
            self.backward_one_chunk(micro_index)
            if self.fsdp_comm_controller is not None:
                self.fsdp_comm_controller.dx_microbatches[self.stage_index].remove(micro_index)
            return

        self._configure_fsdp_backward(micro_index)
485
486
487
488
489
490
491
492
493
494
495
            return

        stage_backward_weight(iter(self._get_pp_autograd_params()), self._dw_cache[micro_index])
        if self.fsdp_comm_controller is not None:
            self.fsdp_comm_controller.reduce_dw_gradients(self.stage_index)
            self.fsdp_comm_controller.dx_microbatches[self.stage_index].remove(micro_index)
            self.fsdp_comm_controller.completed_microbatches[self.stage_index].add(micro_index)
        self._dw_cache.pop(micro_index)
        self._clear_recv_buffer(self.grad_recv_info, micro_index)
        self._clear_recv_buffer(self.args_recv_info, micro_index)
        if self.is_last_stage:
hyper_parallel/core/pipeline_parallel/fsdp_comm_controller.py
26
27
28
29
30
31
32
33
34

    def __init__(self, stages: Sequence[PipelineStageBase], micro_batch_num: int) -> None:
        """Record the stage-owned HSDP units and their settings."""
        if micro_batch_num <= 0:
            raise ValueError("micro_batch_num must be positive")
        self.micro_batch_num = micro_batch_num
        self.stage_schedulers = {}
        self.stage_contexts = {}
        self.user_settings = {}
35
36
37
38
39
40
41
42
43
        self.current_settings = {}
        self.context_settings = {}
        self.completed_microbatches = {stage.stage_index: set() for stage in stages}
        if len(self.completed_microbatches) != len(stages):
            raise ValueError("Local pipeline stages must have distinct stage indices")
        self.dx_microbatches = {stage.stage_index: set() for stage in stages}
        self.reduction_tail_stage = None
        self._handed_off_tail = None
        self.retained_backward_units = set()
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
                if scheduler in scheduler_owners:
                    raise ValueError("Pipeline stages must not share an HSDP scheduler")
                scheduler_owners.add(scheduler)
                for param in scheduler.hsdp_state.hsdp_params:
                    if param in wrapper_owners:
                        raise ValueError("Pipeline stages must not share HSDP parameter wrappers")
                    wrapper_owners.add(param)

            # Storage identity also catches distinct Parameters created as views.
            for param in stage.submodule.parameters():
                if param in parameter_owners and parameter_owners[param] != stage.stage_index:
                    raise ValueError("Pipeline stages must not share parameter objects")
                parameter_owners[param] = stage.stage_index
                local_param = param.to_local() if isinstance(param, DTensor) else param
                storage = local_param.untyped_storage()
                if storage in storage_owners and storage_owners[storage] != stage.stage_index:
101
102
103
104
105
106
107
108
109
110
            or self._handed_off_tail is not None
        ):
            raise RuntimeError("The previous pipeline run has unfinished HSDP work")
        if any(context.reduce_interval != 1 for context in self.stage_contexts.values()):
            raise ValueError("Deferred gradient finalization requires reduce_interval=1")
        if any(context.root_bp_state for context in self.stage_contexts.values()):
            raise RuntimeError("Set gradient finalization outside backward")
        for stage_index, context in self.stage_contexts.items():
            self.context_settings[stage_index] = context.defer_grad_finalize
            context.defer_grad_finalize = True
116
117
118
119
120
121
122
123
124
            return
        context = self.stage_contexts[stage_index]
        self.reduction_tail_stage = None
        if not (context.pre_reduce_scatter_params or context.pending_all_reduce_groups):
            return
        # This step cannot reuse the owner's parameter slots. Transfer only the queues.
        self._handed_off_tail = (
            stage_index, context.pre_reduce_scatter_params, context.pre_all_reduce_groups,
            context.pending_all_reduce_groups,
133
134
135
136
137
138
139
140
141
            return
        stage_index, params, groups, all_reduce = self._handed_off_tail
        context = self.stage_contexts[stage_index]
        if context.pre_reduce_scatter_params or context.pre_all_reduce_groups or context.pending_all_reduce_groups:
            raise RuntimeError("The stage submitted gradients while its previous tail was handed off")
        context.pre_reduce_scatter_params = params
        context.pre_all_reduce_groups = groups
        context.pending_all_reduce_groups = all_reduce
        self._handed_off_tail = None
157
158
159
160
161
162
163
164
165
        for param in hsdp_state.hsdp_params:
            param.accumulate_unsharded_grad_if_needed()
        if not hsdp_state.reduce_grads:
            for param in hsdp_state.hsdp_params:
                param.to_accumulated_grad_if_needed()

    def reduce_dw_gradients(self, stage_index: int) -> None:
        """Consume old work, then submit every ready unit without waiting on this batch."""
        schedulers = self.stage_schedulers.get(stage_index)
hyper_parallel/core/pipeline_parallel/mpipe/schedule.py
196
197
198
199
200
201
202
203
204
                f"overflow_mode must be 'full' or 'min', got {overflow_mode!r}"
            )
        stages = self._check_stages(stages)
        if any(stage.all_hsdp_schedulers for stage in stages):
            raise ValueError("MPipe does not support HSDP pipeline stages")
        self._overflow_mode = overflow_mode
        # ``preprocess_module`` is the resolved block to transpose (first T text
        # layers, the visual tower, or a param-free identity for dataload-only).
        self._preprocess_module = preprocess_module
hyper_parallel/core/pipeline_parallel/scheduler.py
84
85
86
87
88
89
90
91
92
def iter_leaf_meta_steps(step):
    """Yield leaf MetaSteps by recursively expanding composite containers."""
    if step is None:
        return
    if step.sub_steps:
        for sub_step in step.sub_steps:

            yield from iter_leaf_meta_steps(sub_step)
        return
204
205
206
207
208
209
210
211
212
213
214
215
        self._overlap_p2p = overlap_p2p
        self.exec_order = {}
        self.fsdp_comm_controller = FSDPCommController(self.stages, micro_batch_num)
        if swap and self.fsdp_comm_controller.stage_contexts:
            raise ValueError("HSDP pipeline stages do not support activation swap")
        for stage in self.stages:
            if stage.all_hsdp_schedulers:
                stage.fsdp_comm_controller = self.fsdp_comm_controller
        self._init_stages()
        self._build_stage_to_rank_index()
        self.fwd_handle_cache = {}
        self.bwd_handle_cache = {}
894
895
896
897
898
899
900
901
902
            backward = stage.backward_input_one_chunk
        elif step.type == MetaStepType.BWD_WEIGHT:
            backward = stage.backward_weight_one_chunk
        else:
            raise ValueError(f"Expected a backward leaf, got {step.type}")
        self.wait_bwd_recv(step.stage_index, step.micro_index)
        backward(step.micro_index)

    def _exec_pipeline_data_steps(self,
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
    def _handoff_fsdp_reduction_tail(self, step: MetaStep) -> None:
        """Choose who consumes the previous HSDP tail for the next compute step."""
        if self.fsdp_comm_controller.reduction_tail_stage is None:
            return
        backward_types = (MetaStepType.BWD, MetaStepType.BWD_WEIGHT)
        compute_types = (MetaStepType.FWD, MetaStepType.BWD_INPUT, *backward_types)
        leaves = step.sub_steps or (step,)
        if any(leaf.type in compute_types for leaf in leaves):
            backward_stages = {leaf.stage_index for leaf in leaves if leaf.type in backward_types}
            self.fsdp_comm_controller.handoff_reduction_tail(backward_stages)

    def run_microbatches(self, arg_mbs: list, kwarg_mbs: list, losses: list) -> None:
        """Execute the schedule step by step.
hyper_parallel/core/pipeline_parallel/stage.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        self._dyn_shape = dyn_shape
        self._shared_parameters = self._check_shared_parameters(shared_parameters)
        self._virtual_chunk_num = 1
        if self.all_hsdp_schedulers:
            if any(isinstance(module, OptimizedModule) for module in submodule.modules()):
                raise ValueError("HSDP pipeline stages do not support torch.compile")
            if any(isinstance(module, SwapWrapper) or "_swap_group_name" in module.__dict__
                   for module in submodule.modules()):
                raise ValueError("HSDP pipeline stages do not support activation swap")
            stage_modules = set(submodule.modules())
            for scheduler in self.all_hsdp_schedulers:
                if not set(scheduler.modules).issubset(stage_modules):
                    raise ValueError("An HSDP module group cannot span pipeline stages")
                if scheduler.comm_fusion_policy.enable_comm_fusion:
                    raise ValueError("HSDP pipeline stages do not support comm_fusion=True")
                if isinstance(scheduler.offload_policy, CPUOffloadPolicy):
                    raise ValueError("HSDP pipeline stages do not support parameter offload")

    @property
    def has_backward(self) -> bool:
        """Return whether this stage executes backward passes."""