Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / pipeline_parallel / utils.py: 87%
101 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 2025-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"""pipeline parallel utils"""
16from enum import Enum, auto
19class MetaStepType(Enum):
20 """Specify the enumeration type for MetaStep."""
21 DATA_LOAD = auto()
22 DATA_SEND = auto()
23 DATA_RECV = auto()
24 FWD = auto()
25 BWD = auto()
26 BWD_INPUT = auto()
27 BWD_WEIGHT = auto()
28 FWD_RECV = auto()
29 FWD_SEND = auto()
30 BWD_RECV = auto()
31 BWD_SEND = auto()
32 # Composite P2P: a contiguous run of FWD_SEND/FWD_RECV/BWD_SEND/BWD_RECV
33 # coalesced by ``coalesce_p2p`` into one step whose ``sub_steps`` the runtime
34 # groups by peer and issues as ``batch_isend_irecv`` (same-peer send+recv ->
35 # duplex). Produced under ``p2p_transport="batch"`` or ``"multi_stream"``.
36 BATCH_SEND_RECV = auto()
37 OVERLAP_F_B = auto()
38 OVERLAP_B_F = auto()
39 SWAP_LAUNCH_OFFLOAD = auto()
40 SWAP_WAIT_OFFLOAD = auto()
41 SWAP_LAUNCH_LOAD = auto()
42 SWAP_WAIT_LOAD = auto()
45class MetaStep:
46 """
47 Meta step of PipelineSchedule.
48 An execution list composed of MetaStep can be constructed
49 and fed into the PipelineSchedule for execution.
51 Args:
52 micro_index (int | None): The index of micro-batch. ``None`` for
53 composite types (``OVERLAP_F_B`` / ``OVERLAP_B_F``) whose real
54 micro index lives in each ``sub_steps`` entry.
55 type (MetaStepType): Specify the type of current step.
56 stage_index (int | None): Stage index of current step. ``None``
57 for composite types; use ``sub_steps`` to get each direction's
58 stage.
59 sub_steps (tuple[MetaStep, MetaStep] | None): For composite types
60 only: ``(fwd, bwd)`` for ``OVERLAP_F_B``, ``(bwd, fwd)`` for
61 ``OVERLAP_B_F``.
62 boundary_p2p (tuple[MetaStep, ...] | None): For ``OVERLAP_B_F`` under
63 the ``"boundary"`` P2P transport only: P2P steps to issue at the
64 fwd/bwd boundary inside the overlap (the forward's ``FWD_SEND``
65 plus the next slot's recvs), hoisted out of the following gap by
66 ``attach_fwd_boundary_p2p``. Issued via
67 :meth:`PipelineScheduleRuntime.exec_boundary_p2p`.
68 """
69 def __init__(self, micro_index, meta_type, stage_index, sub_steps=None,
70 boundary_p2p=None):
71 self._type = meta_type
72 self._micro_index = micro_index
73 self._stage_index = stage_index
74 self._sub_steps = sub_steps
75 self._boundary_p2p = boundary_p2p
77 @property
78 def micro_index(self):
79 """Return the micro-batch index of this step."""
80 return self._micro_index
82 @property
83 def stage_index(self):
84 """Return the stage index of this step."""
85 return self._stage_index
87 @property
88 def type(self):
89 """Return the MetaStepType of this step."""
90 return self._type
92 @property
93 def sub_steps(self):
94 """Return this step's sub-steps.
96 ``(fwd, bwd)`` for OVERLAP_F_B, ``(bwd, fwd)`` for OVERLAP_B_F, or
97 ``None`` for every other type.
98 """
99 return self._sub_steps
101 @property
102 def boundary_p2p(self):
103 """P2P steps to issue at the overlap's fwd/bwd boundary, or ``None``."""
104 return self._boundary_p2p
106 def __eq__(self, value):
107 if not isinstance(value, MetaStep):
108 return NotImplemented
109 return (self.type == value.type
110 and self.micro_index == value.micro_index
111 and self.stage_index == value.stage_index
112 and self.sub_steps == value.sub_steps)
114 def __ne__(self, value):
115 if not isinstance(value, MetaStep):
116 return NotImplemented
117 return not self.__eq__(value)
119 def __hash__(self):
120 return hash((self.type, self.micro_index, self.stage_index))
122 def __str__(self):
123 if self.sub_steps:
124 sub = ", ".join(str(s) for s in self.sub_steps)
125 return (f"MetaStep(type={self.type}, micro_index={self.micro_index}, "
126 f"stage_index={self.stage_index}, sub_steps=[{sub}])")
127 return f"MetaStep(type={self.type}, micro_index={self.micro_index}, stage_index={self.stage_index})"
129 def __repr__(self):
130 return self.__str__()
132 @staticmethod
133 def from_str(step_str):
134 """Parse a MetaStep from its string representation."""
137class BatchDimSpec:
138 """
139 Specify the batch dimension of a Tensor.
141 Args:
142 batch_dim (int): batch dimension.
143 """
144 __slots__ = ("batch_dim",)
146 def __init__(self, batch_dim):
147 if not isinstance(batch_dim, int):
148 raise TypeError(f"batch_dim must be int, but got type {type(batch_dim)}.")
149 self.batch_dim = batch_dim
151 def __repr__(self):
152 return f"BatchDimSpec({self.batch_dim})"
154 def __str__(self):
155 return f"BatchDim(dim={self.batch_dim})"
157 @staticmethod
158 def from_tuple(batch_dims):
159 """Create a tuple of BatchDimSpec from a tuple of batch dimensions."""
160 if not isinstance(batch_dims, tuple):
161 raise TypeError(f"batch_dims must be tuple, but got type {type(batch_dims)}.")
162 return tuple(BatchDimSpec(dim) for dim in batch_dims)
164 @staticmethod
165 def from_dict(batch_dims):
166 """Create a dict of BatchDimSpec from a dict mapping keys to batch dimensions."""
167 if not isinstance(batch_dims, dict):
168 raise TypeError(f"batch_dims must be dict, but got type {type(batch_dims)}.")
169 return {k: BatchDimSpec(v) for k, v in batch_dims.items()}
172class _RecvInfo:
173 """
174 Used for construct forward Receive operation and backward Send operation.
176 ``requires_grad`` mirrors the forward tensor's ``requires_grad`` so
177 pipeline code can skip backward send/recv for tensors that have no
178 gradient, keeping the bwd-send count consistent with the peer's
179 bwd-recv count.
180 """
182 def __init__(self, global_rank, buffer=None, requires_grad: bool = True):
183 self._global_rank = global_rank
184 self._buffer = buffer
185 self._requires_grad = bool(requires_grad)
187 @property
188 def global_rank(self):
189 """Return the global rank of the peer process."""
190 return self._global_rank
192 @property
193 def buffer(self):
194 """Return the receive/send buffer tensor."""
195 return self._buffer
197 @buffer.setter
198 def buffer(self, val):
199 """Set the receive/send buffer tensor."""
200 self._buffer = val
202 @property
203 def requires_grad(self) -> bool:
204 """Whether the corresponding forward tensor requires a gradient."""
205 return self._requires_grad
207 @requires_grad.setter
208 def requires_grad(self, val: bool) -> None:
209 """Set whether the corresponding forward tensor requires a gradient."""
210 self._requires_grad = bool(val)