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 93.9% 272,276,280,578,713,747
hyper_parallel/core/fully_shard/hsdp_state.py 100%  
hyper_parallel/core/fully_shard/param_group.py 91.3% 835,1079
hyper_parallel/core/pipeline_parallel/_stage.py 94.9% 84,107,140,168,380-381,384
hyper_parallel/core/pipeline_parallel/fsdp_comm_controller.py 94.8% 30,39,76,82,105,107,120,137,161
hyper_parallel/core/pipeline_parallel/mpipe/schedule.py 66.7% 200
hyper_parallel/core/pipeline_parallel/scheduler.py 92.5% 88,208,898
hyper_parallel/core/pipeline_parallel/stage.py 81.2% 138,141,145
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
                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.
574
575
576
577
578
579
580
581
582
        """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()
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)
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/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):
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:
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()
72
73
74
75
76
77
78
79
80
                    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():
78
79
80
81
82
83
84
85
86

            # 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
        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()
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,
hyper_parallel/core/pipeline_parallel/stage.py
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
        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")