Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / pipeline_parallel / mpipe / schedule.py: 98%
174 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"""The MPipe Transpose schedule (an Interleaved-1F1B variant).
17Layers the ``MPIPE_*`` transpose steps around the inherited Interleaved-1F1B
18body order and registers their handlers via the generic custom-function
19registry, so the core ``scheduler`` module carries no MPipe-specific code.
20"""
21import logging
22from typing import Callable, Optional, TYPE_CHECKING
24from torch.nn import Module
26from hyper_parallel.core.pipeline_parallel.mpipe.executor import MPipeTransposeExecutor
28from hyper_parallel.core.pipeline_parallel.scheduler import ScheduleInterleaved1F1B
29from hyper_parallel.core.pipeline_parallel.mpipe.sampler import mpipe_owned_micros
30from hyper_parallel.core.pipeline_parallel.mpipe.step_types import MpipeStepType
31from hyper_parallel.core.pipeline_parallel.utils import MetaStep, MetaStepType
33if TYPE_CHECKING:
34 from hyper_parallel.core.pipeline_parallel.utils import BatchDimSpec
36logger = logging.getLogger(__name__)
38# (data, features, graph input) step types of the transpose-prefix transfers.
39_PREFIX_SEND_TYPES = (MetaStepType.DATA_SEND, MpipeStepType.MPIPE_FWD_SEND, MpipeStepType.MPIPE_GRAPH_SEND)
40_PREFIX_RECV_TYPES = (MetaStepType.DATA_RECV, MpipeStepType.MPIPE_FWD_RECV, MpipeStepType.MPIPE_GRAPH_RECV)
43def _prefix_owned_micros(rank, num_transpose_micro_batches, micro_batch_num, overflow_mode):
44 """Micros ``rank`` transposes in its prefix (under ``"min"`` only ``rank``
45 itself; rank 0's overflow micros are loaded inline in its body order)."""
46 nt = num_transpose_micro_batches
47 if rank >= nt:
48 return []
49 if overflow_mode == "min":
50 return [rank]
51 return [m for m in range(micro_batch_num) if m % nt == rank]
54def _prefix_transfer_steps(micros, step_types, is_dataload_only, ship_graph):
55 """Type-major transfer block: all data, then all features, then all graph inputs.
57 The sending ranks and rank 0 both build their block here, so the send and
58 receive orders match; otherwise the meta recv drifts and decodes garbage
59 shapes. Dataload-only ships the data alone; ``ship_graph`` adds the input
60 ship-back for the centralized stage-0 backward.
61 """
62 data_type, fwd_type, graph_type = step_types
63 steps = [MetaStep(m, data_type, -1) for m in micros]
64 if not is_dataload_only:
65 steps += [MetaStep(m, fwd_type, -1) for m in micros]
66 if ship_graph:
67 steps += [MetaStep(m, graph_type, -1) for m in micros]
68 return steps
71class ScheduleMPipeTranspose(ScheduleInterleaved1F1B):
72 """The MPipe Transpose schedule.
74 A variant of Interleaved 1F1B that shrinks the warmup pipeline bubble by
75 **transposing** the forward of a model's first ``T`` layers (the
76 *preprocess* block, which logically belongs to stage 0's first chunk).
78 Instead of stage 0 computing the preprocess forward serially for every
79 micro-batch, the preprocess parameters are broadcast to all ``PP`` ranks
80 and, for the first ``NT = min(PP, micro_batch_num)`` micro-batches, each
81 rank ``i`` computes the preprocess forward of micro-batch ``i`` in parallel
82 during what would otherwise be its warmup idle time. Each rank ``i > 0``
83 then ships to stage 0:
85 * the preprocess **output** (``MPIPE_FWD_SEND`` / ``MPIPE_FWD_RECV``) so
86 stage 0 can run its body forward, and
87 * the preprocess **input** (``MPIPE_GRAPH_SEND`` / ``MPIPE_GRAPH_RECV``)
88 so the preprocess backward can run centrally on stage 0
89 (gradients accumulate on stage 0 only).
91 The remaining ``micro_batch_num - NT`` micro-batches run the preprocess
92 forward inline on stage 0 (graph-connected to the body, so their backward
93 is automatic), exactly as ordinary Interleaved 1F1B.
95 The body model (stage 0 = the layers after the preprocess block, all other
96 stages unchanged) is scheduled by the inherited Interleaved 1F1B logic; the
97 preprocess steps are layered around it: a transpose-phase prefix per rank,
98 plus inline preprocess forward / stage-0 backward steps.
100 Args:
101 stages (list[PipelineStage], PipelineStage): The body pipeline stages,
102 given **after** stage 0's first chunk has been partitioned into the
103 preprocess block and the body. Stage 0 here must wrap only the
104 layers that remain *after* the preprocess block; the transposed
105 preprocess layers are passed separately as ``preprocess_module`` and
106 must not appear in ``stages``.
107 micro_batch_num (int): The number of micro-batches.
108 preprocess_module (Optional[Module]): The preprocess block (first ``T``
109 layers of stage 0). Following Option A, it must exist on **every** rank: on rank 0
110 it holds the trained parameters; on other ranks it is a structural
111 copy whose parameters are overwritten each step by the broadcast.
112 num_transpose_layers (int): ``T`` — the number of preprocess layers,
113 must be smaller than the layer count of stage 0's first chunk.
114 ``0`` is allowed and means *only the data loading is transposed*:
115 each rank loads its micro-batch and ships the raw input to stage 0,
116 with no parameter broadcast, no preprocess compute, and no
117 stage-0 backward.
118 args_batch_dim (list, optional): See ``PipelineScheduleRuntime``.
119 kwargs_batch_dim (dict, optional): See ``PipelineScheduleRuntime``.
120 output_concat_dim (int, optional): See ``PipelineScheduleRuntime``.
121 overlap_p2p (bool, optional): See ``ScheduleInterleaved1F1B``.
122 Default ``False``.
123 swap (bool, optional): Reserved for API compatibility. MPipe activation
124 swap is not supported and ``True`` raises ``ValueError``.
126 Note:
127 This class builds the schedule ordering and registers the ``MPIPE_*``
128 execution handlers implemented by :class:`MPipeTransposeExecutor`.
129 HSDP decoder stages require a singleton sharding mesh and prefix backward on stage zero.
130 """
132 # Each rank runs one transposed preprocess forward, so every rank needs its
133 # own micro-batch input — drivers (the trainer) check this marker to feed all
134 # ranks rather than only the first stage.
135 requires_all_rank_input = True
137 def __init__(self,
138 stages: list,
139 micro_batch_num: int,
140 preprocess_module: "Optional[Module]",
141 num_transpose_layers: int,
142 num_visual_layers: Optional[int] = None,
143 args_batch_dim: "Optional[BatchDimSpec]" = None,
144 kwargs_batch_dim: "Optional[BatchDimSpec]" = None,
145 output_concat_dim: Optional[int] = None,
146 overlap_p2p: bool = False,
147 swap: bool = False,
148 output_consumer: Optional[Callable] = None,
149 owner_backward: bool = False,
150 less_memory: bool = False,
151 overflow_mode: str = "full") -> None:
152 """Build an interleaved-1F1B schedule that transposes the preprocess block.
154 Args:
155 stages (list): The local pipeline stages (as for :class:`ScheduleInterleaved1F1B`).
156 micro_batch_num (int): Number of micro-batches per optimizer step.
157 preprocess_module (Optional[Module]): The block transposed to every
158 rank — the first ``num_transpose_layers`` layers, a visual tower,
159 or a param-free identity for the dataload-only (``T = 0``) mode.
160 num_transpose_layers (int): ``T`` — the (informational) transposed-layer count.
161 num_visual_layers (int): total number of visual layers.
162 args_batch_dim (Optional[BatchDimSpec]): Positional-arg batch-dim spec (forwarded to the base).
163 kwargs_batch_dim (Optional[BatchDimSpec]): Keyword-arg batch-dim spec (forwarded to the base).
164 output_concat_dim (Optional[int]): Output concatenation dim (forwarded to the base).
165 overlap_p2p (bool): Whether to overlap P2P (forwarded to the base).
166 swap (bool): Reserved for API compatibility. Must be ``False``.
167 output_consumer: Optional ``(ctx, micro, out_tuple) -> None`` callback
168 routing a transposed micro-batch's preprocess output (``None`` =
169 default, the output becomes stage 0's body input).
170 less_memory (bool): Shallow-warmup interleaved body (forwarded to
171 the base) — see :class:`ScheduleInterleaved1F1B`. The transpose
172 prefix is unaffected.
173 owner_backward (bool): Opt-in owner-does-backward for a TRAINABLE
174 preprocess on torch. When effective, the owner rank retains the
175 forward graph, stage 0 ships the feature gradient back, and the
176 owner runs the tower backward in its cooldown (instead of the
177 centralized stage-0 backward); tower grads are SUM all-reduced
178 across the pp replicas. Ignored (stage-0 backward kept) for a frozen / param-free
179 preprocess.
180 overflow_mode (str): How to distribute the ``M > NT`` overflow micros.
181 ``"full"`` (default) — round-robin: each owner takes ``M/NT``
182 micros, ViT phase balanced. ``"min"`` — rank 0 absorbs the
183 overflow (saves inter-rank P2P at the cost of a longer rank-0
184 ViT phase).
185 """
186 if swap:
187 raise ValueError(
188 "MPipe Transpose with pipeline activation swap is not yet supported."
189 )
190 if not isinstance(num_transpose_layers, int) or num_transpose_layers < 0:
191 raise ValueError(
192 f"Argument 'num_transpose_layers' must be a non-negative int, "
193 f"but got {num_transpose_layers!r}."
194 )
195 if overflow_mode not in ("full", "min"):
196 raise ValueError(
197 f"overflow_mode must be 'full' or 'min', got {overflow_mode!r}"
198 )
199 stages = self._check_stages(stages)
200 for stage in stages:
201 for scheduler in stage.all_hsdp_schedulers:
202 if owner_backward or scheduler.mesh is None or scheduler.mesh.size() != 1:
203 raise ValueError("MPipe HSDP stages require singleton meshes and stage-zero prefix backward")
204 self._overflow_mode = overflow_mode
205 # ``preprocess_module`` is the resolved block to transpose (first T text
206 # layers, the visual tower, or a param-free identity for dataload-only).
207 self._preprocess_module = preprocess_module
208 self._num_transpose_layers = num_transpose_layers
209 self._num_visual_layers = num_visual_layers
210 # ``None`` = the preprocess output is stage 0's body input (arg_mbs);
211 # VL passes a consumer that routes it into an injection kwarg instead.
212 self._output_consumer = output_consumer
213 # Trainable preprocess -> broadcast + stage-0 backward; frozen or
214 # param-free -> ship the output only (no broadcast, no recompute).
215 self._has_trainable_preprocess = self._module_has_trainable_params(preprocess_module)
216 self._owner_backward = bool(owner_backward) and self._has_trainable_preprocess
217 super().__init__(stages,
218 micro_batch_num,
219 args_batch_dim=args_batch_dim,
220 kwargs_batch_dim=kwargs_batch_dim,
221 output_concat_dim=output_concat_dim,
222 overlap_p2p=overlap_p2p,
223 overlap_b_f=False,
224 swap=swap,
225 less_memory=less_memory)
226 self._executor = None
227 self._setup_mpipe_execution()
229 @staticmethod
230 def _module_has_trainable_params(module) -> bool:
231 """Whether ``module`` has any trainable (grad-requiring) parameter."""
232 if module is None:
233 return False
234 return any(p.requires_grad for p in module.parameters())
236 @property
237 def preprocess_module(self) -> "Optional[Module]":
238 """The preprocess block transposed to every rank (present on every rank)."""
239 return self._preprocess_module
241 @property
242 def output_consumer(self) -> Optional[Callable]:
243 """Optional ``(ctx, micro, out_tuple)`` placement callback (None = body input)."""
244 return self._output_consumer
246 @property
247 def has_trainable_preprocess(self) -> bool:
248 """Whether the preprocess has trainable params (drives broadcast / stage-0 backward)."""
249 return self._has_trainable_preprocess
251 @property
252 def owner_backward(self) -> bool:
253 """Whether owner-does-backward is effective (trainable preprocess + torch)."""
254 return self._owner_backward
256 @property
257 def num_transpose_layers(self) -> int:
258 """The informational transposed-layer count ``T`` (``0`` = dataload only)."""
259 return self._num_transpose_layers
261 @property
262 def num_transpose_micro_batches(self) -> int:
263 """``NT = min(PP, micro_batch_num)`` — count of owner ranks per cycle."""
264 return min(self.real_stage_num, self.micro_batch_num)
266 def owned_micros(self, pp_rank: int) -> frozenset:
267 """Owner set for ``pp_rank`` under :attr:`overflow_mode` (see ``mpipe_owned_micros``)."""
268 return mpipe_owned_micros(self.real_stage_num, self.micro_batch_num,
269 pp_rank, mode=self._overflow_mode)
271 def owner_of(self, micro: int) -> int:
272 """Rank that owns micro ``micro`` under :attr:`overflow_mode`."""
273 nt = self.num_transpose_micro_batches
274 if self._overflow_mode == "min":
275 return 0 if micro >= nt else micro
276 return micro % nt
278 def _setup_mpipe_execution(self) -> None:
279 """Build the Torch executor and register the MPIPE_* handlers."""
280 self._executor = MPipeTransposeExecutor(self)
281 self._apply_backward_retain_flag()
282 handlers = {
283 MpipeStepType.MPIPE_PARAM_BROADCAST: self._executor.broadcast_params,
284 MpipeStepType.MPIPE_TRANSPOSE_FWD: self._executor.transpose_forward,
285 MpipeStepType.MPIPE_FWD_SEND: self._executor.fwd_send,
286 MpipeStepType.MPIPE_FWD_RECV: self._executor.fwd_recv,
287 MpipeStepType.MPIPE_GRAPH_SEND: self._executor.fwd_bwd_graph_input_send,
288 MpipeStepType.MPIPE_GRAPH_RECV: self._executor.fwd_bwd_graph_input_recv,
289 MpipeStepType.MPIPE_TRANSPOSE_BWD: self._executor.transpose_backward,
290 MpipeStepType.MPIPE_GRAD_SEND: self._executor.grad_send,
291 MpipeStepType.MPIPE_GRAD_RECV_WITH_BACKWARD: self._executor.grad_recv_with_backward,
292 MpipeStepType.MPIPE_GRAD_REDUCE: self._executor.reduce_tower_grads,
293 }
294 for step_type, handler in handlers.items():
295 self.register_custom_function(step_type, handler)
297 def _apply_backward_retain_flag(self) -> None:
298 """Flag the stages to retain their body-backward graph for a TRAINABLE tower.
300 A trainable transposed tower + FSDP shares one all-gather node across the
301 micro graphs that back-propagate into it (the connected micro-0 body graph
302 plus the deferred owner/stage-0 tower backwards). The first backward to
303 traverse that shared node frees it, so a later one raises "backward through
304 the graph a second time" (surfaces at ``vpp >= 2``). Retaining the body
305 graph keeps the shared node alive. A frozen tower (no shared trainable
306 node) and plain PP (no flag) are unaffected.
307 """
308 if self._has_trainable_preprocess:
309 for stage in self.stages:
310 stage.retain_backward_graph = True
312 def run_microbatches(self, arg_mbs: list, kwarg_mbs: list, losses: list) -> None:
313 """Reset the executor's per-step caches, then run the schedule.
315 A step raising mid-run leaves its micro-batches in those caches, so the
316 error path drops them (:meth:`MPipeTransposeExecutor.abort`) -- the
317 counterpart of the scheduler's in-flight P2P drain, which covers only
318 the comm handles. The normal path leaves the caches empty, which the
319 next run's reset still verifies.
321 Args:
322 arg_mbs (list): Per-micro-batch positional args.
323 kwarg_mbs (list): Per-micro-batch keyword args.
324 losses (list): Mutable list collecting per-step losses.
325 """
326 if self._executor is not None:
327 self._executor.reset()
328 try:
329 super().run_microbatches(arg_mbs, kwarg_mbs, losses)
330 except BaseException:
331 if self._executor is not None:
332 self._executor.abort()
333 raise
335 def construct_exec_order(self) -> None:
336 """Build the body Interleaved 1F1B order, then layer the preprocess
337 transpose phase and the centralized preprocess backward on top.
339 The parameter broadcast, the stage-0-backward input transport, and the
340 stage-0 backward are emitted only for a **trainable** preprocess; a
341 frozen (visual tower) or param-free (``T == 0``) one only transposes
342 the forward and ships its output.
344 When owner-does-backward is effective (trainable + torch + opt-in) the
345 stage-0-backward input transport and stage-0 backward are replaced by a
346 feature-gradient ship-back (``MPIPE_GRAD_SEND`` on stage 0,
347 ``MPIPE_GRAD_RECV_WITH_BACKWARD`` cooldown suffix on the owners) and a final
348 ``MPIPE_GRAD_REDUCE`` collective on every rank.
349 """
350 super().construct_exec_order()
351 body_order = self.exec_order
352 nt = self.num_transpose_micro_batches
353 micro_batch_num = self.micro_batch_num
354 has_trainable = self._has_trainable_preprocess
355 owner_backward = self._owner_backward
356 mode = self._overflow_mode
357 # Body DATA_LOAD steps are rescheduled into the mpipe prefix (and, under
358 # "min", inline onto rank 0's body for the overflow micros).
359 for i, order in body_order.items():
360 body_order[i] = [step for step in order
361 if step is not None and step.type != MetaStepType.DATA_LOAD]
362 body_order[0] = self._insert_rank0_preprocess_steps(
363 body_order[0], nt, has_trainable, mode, owner_backward=owner_backward,
364 num_transpose_layers=self._num_transpose_layers)
365 exec_order = {}
366 for rank in range(self.real_stage_num):
367 order = (
368 self._build_transpose_prefix(
369 rank, nt, micro_batch_num, has_trainable, mode,
370 owner_backward=owner_backward,
371 num_transpose_layers=self._num_transpose_layers)
372 + body_order[rank]
373 )
374 if owner_backward:
375 # Cooldown suffix: stage 0 ships dL/dfeatures, owners run the
376 # tower backward, then all ranks SUM-all-reduce the tower grads.
377 order = (
378 order
379 + self._build_owner_backward_suffix(rank, nt, micro_batch_num, mode)
380 + [MetaStep(None, MpipeStepType.MPIPE_GRAD_REDUCE, 0)]
381 )
382 exec_order[rank] = order
383 self.exec_order = exec_order
384 # frozen + all visual layers transposed, so stage 0 needs no pixels
385 if (not self._has_trainable_preprocess and
386 self._num_visual_layers is not None and
387 self._num_transpose_layers >= self._num_visual_layers):
388 self._data_keys = ("input_ids",) + tuple(
389 k for k in self.kwargs_batch_dim if k != "pixel_values"
390 )
391 else:
392 self._data_keys = ("input_ids",) + tuple(self.kwargs_batch_dim)
394 # Length-M so overflow micros and VPP chunks index in bounds; the
395 # prefix key -1 ships owner to rank 0, body stages chain via stages[0].
396 self._data_dst = {-1: [0 for _ in range(self.micro_batch_num)]}
397 self._data_src = {-1: [self.owner_of(m) for m in range(self.micro_batch_num)]}
398 for i in range(self._stage_num):
399 self._data_dst[i] = [self.stages[0].dst_stage for _ in range(self.micro_batch_num)]
400 self._data_src[i] = [self.stages[0].src_stage for _ in range(self.micro_batch_num)]
402 @staticmethod
403 def _build_transpose_prefix(rank, num_transpose_micro_batches, micro_batch_num,
404 has_trainable, overflow_mode,
405 owner_backward=False, num_transpose_layers=None):
406 """Build the transpose-phase prefix prepended to ``rank``'s body order.
408 Under ``overflow_mode="full"`` (round-robin) rank ``rank`` (``< NT``)
409 owns ``{m : m % NT == rank}`` — emits DATA_LOAD → MPIPE_TRANSPOSE_FWD
410 per owned micro, and (when not rank 0) ships each to rank 0. Rank 0
411 receives every non-owned micro. For a **trainable** preprocess every
412 rank also broadcasts its (trainable) parameters and ranks ``> 0``
413 additionally ship the input for the centralized stage-0 backward; for
414 a frozen (visual tower) preprocess only the transpose forward and its
415 output send/recv remain.
417 Under ``"min"`` each owner (including rank 0) emits exactly one
418 transposed micro (``{rank}``). Rank 0 receives only ``1..NT-1``; the
419 overflow micros ``NT..M-1`` are loaded inline on rank 0 by
420 :meth:`_insert_rank0_preprocess_steps`.
422 Dataload-only mode (``num_transpose_layers == 0``): every emission
423 of MPIPE_PARAM_BROADCAST, MPIPE_TRANSPOSE_FWD, MPIPE_FWD_SEND/RECV,
424 MPIPE_GRAPH_SEND/RECV is suppressed. Only DATA_LOAD + DATA_SEND/RECV
425 remain; stage 0 runs the visual tower itself during body forward.
426 Ownership (round-robin vs single-owner) still follows
427 ``overflow_mode`` so the dataload I/O sharding stays balanced.
429 Under owner-does-backward the input ship-back (``MPIPE_GRAPH_SEND`` /
430 ``MPIPE_GRAPH_RECV``) is dropped -- the owner keeps its forward graph and
431 receives only the feature gradient later (``MPIPE_GRAD_RECV_WITH_BACKWARD``).
432 """
433 nt = num_transpose_micro_batches
434 owned = _prefix_owned_micros(rank, nt, micro_batch_num, overflow_mode)
435 is_dataload_only = num_transpose_layers == 0
436 prefix = []
437 if has_trainable and not is_dataload_only:
438 prefix.append(MetaStep(rank, MpipeStepType.MPIPE_PARAM_BROADCAST, -1))
439 # DATA_LOAD + MPIPE_TRANSPOSE_FWD are local (no comm) — emit per-micro.
440 for m in owned:
441 prefix.append(MetaStep(m, MetaStepType.DATA_LOAD, -1))
442 if not is_dataload_only:
443 prefix.append(MetaStep(m, MpipeStepType.MPIPE_TRANSPOSE_FWD, -1))
444 ship_graph = has_trainable and not owner_backward
445 if rank != 0:
446 return prefix + _prefix_transfer_steps(owned, _PREFIX_SEND_TYPES, is_dataload_only, ship_graph)
447 # Non-owned = micros rank 0 didn't transpose locally ("min":
448 # overflow micros load inline, so they are not received).
449 if overflow_mode == "min":
450 non_owned = list(range(1, nt))
451 else:
452 non_owned = [m for m in range(micro_batch_num) if m not in owned]
453 return prefix + _prefix_transfer_steps(non_owned, _PREFIX_RECV_TYPES, is_dataload_only, ship_graph)
455 @staticmethod
456 def _build_owner_backward_suffix(rank, num_transpose_micro_batches, micro_batch_num, overflow_mode):
457 """Cooldown suffix (owner-backward), appended AFTER all body steps so the
458 feature-grad transport never interleaves with the body's P2P.
460 Stage 0 ships ``dL/dfeatures`` for every micro it does not own itself
461 (``MPIPE_GRAD_SEND``, one per micro whose owner != 0). Each owner rank
462 receives a gradient for **every** micro it owns (``MPIPE_GRAD_RECV_WITH_BACKWARD``,
463 one step per owned micro) and backprops its retained tower graph for each.
464 Ranks ``>= NT`` own no transposed micro-batch.
466 Under ``"min"`` an owner rank owns exactly one micro (``{rank}``), so this
467 degenerates to the original one-gradient-per-rank exchange. Under ``"full"``
468 (round-robin) with ``M > NT`` an owner rank can own several micros
469 (``{m : m % NT == rank}``); each gets its own SEND/RECV pair. Both sides
470 iterate ``range(micro_batch_num)`` in ascending order, so for any fixed
471 (rank 0, owner) pair the send order matches the receive order -- required
472 since HCCL serializes P2P per rank-pair on a single channel.
473 """
474 nt = num_transpose_micro_batches
476 def owner_of(micro: int) -> int:
477 """Rank that owns ``micro`` under the active overflow mode."""
478 if overflow_mode == "min":
479 return 0 if micro >= nt else micro
480 return micro % nt
482 if rank == 0:
483 return [MetaStep(micro, MpipeStepType.MPIPE_GRAD_SEND, 0)
484 for micro in range(micro_batch_num) if owner_of(micro) != 0]
485 if rank < nt:
486 return [MetaStep(micro, MpipeStepType.MPIPE_GRAD_RECV_WITH_BACKWARD, 0)
487 for micro in range(micro_batch_num) if owner_of(micro) == rank]
488 return []
490 @staticmethod
491 def _insert_rank0_preprocess_steps(order, num_transpose_micro_batches,
492 has_trainable, overflow_mode, owner_backward=False,
493 num_transpose_layers=None):
494 """Patch stage 0's body order for the overflow / recompute paths.
496 Under ``"full"``: every micro is transposed (somewhere). No inline
497 preprocess on rank 0; under trainable, MPIPE_TRANSPOSE_BWD fires after
498 every stage-0 BWD (the preprocess output is detached either way).
500 Under ``"min"``: rank 0 absorbs the overflow micros ``NT..M-1``. Before
501 each stage-0 FWD on an overflow micro we insert DATA_LOAD and (under
502 trainable or frozen) MPIPE_TRANSPOSE_FWD — running the preprocess
503 locally with a detached graph. For frozen this is just "rank 0
504 runs the ViT here so the body forward has the encoded features /
505 visual-injection kwarg"; for trainable the body BWD also needs an
506 MPIPE_TRANSPOSE_BWD stage-0 backward for the preprocess gradient. (The
507 previous design used a graph-connected forward to avoid the
508 stage-0 backward on overflow micros; that optimization isn't restored
509 here — `"min"` saves comm for slightly more rank-0 compute on the
510 trainable path.)
512 Under owner-does-backward (``owner_backward``) the centralized stage-0
513 backward is replaced: the body backward deposits ``dL/dfeatures`` on the
514 placed feature tensors, and a stage-0 cooldown SUFFIX
515 (:meth:`_build_owner_backward_suffix`) ships it back to the owners -- NOT
516 inline here, since the blocking grad meta-exchange would deadlock against
517 the body's P2P. So no per-BWD step is inserted for any micro; every
518 owned/inline forward on stage 0 already runs graph-connected
519 (``transpose_forward``'s owner-backward branch), so the body backward
520 flows into the tower automatically.
522 Dataload-only (``num_transpose_layers == 0``) suppresses the inline
523 MPIPE_TRANSPOSE_FWD, matching the contract documented on
524 :meth:`_build_transpose_prefix`: with an identity preprocess there is
525 nothing to run ahead of the body, and stage 0 consumes the raw loaded
526 data directly.
527 """
528 if not has_trainable and overflow_mode == "full":
529 return order
530 nt = num_transpose_micro_batches
531 is_dataload_only = num_transpose_layers == 0
532 patched = []
533 for step in order:
534 is_stage0_fwd = (
535 step is not None
536 and step.type == MetaStepType.FWD
537 and step.stage_index == 0
538 )
539 if (overflow_mode == "min" and is_stage0_fwd
540 and step.micro_index >= nt):
541 patched.append(MetaStep(step.micro_index, MetaStepType.DATA_LOAD, -1))
542 if not is_dataload_only:
543 # Populates the visual-injection kwarg via output_consumer;
544 # without it rank 0's body forward crashes.
545 patched.append(MetaStep(step.micro_index, MpipeStepType.MPIPE_TRANSPOSE_FWD, -1))
546 patched.append(step)
547 is_stage0_bwd = (
548 step is not None
549 and step.type == MetaStepType.BWD
550 and step.stage_index == 0
551 )
552 if is_stage0_bwd and has_trainable and not owner_backward:
553 patched.append(MetaStep(step.micro_index, MpipeStepType.MPIPE_TRANSPOSE_BWD, -1))
554 return patched