Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / pipeline_parallel / scheduler.py: 76%

1193 statements  

« 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"""pipeline schedule""" 

16from abc import ABC, abstractmethod 

17from contextlib import nullcontext 

18from collections import defaultdict 

19import itertools 

20import bisect 

21import logging 

22import re 

23from typing import Any, Iterator 

24 

25import torch 

26import torch.distributed as dist 

27 

28import hyper_parallel 

29from hyper_parallel.core.pipeline_parallel.fsdp_comm_controller import FSDPCommController 

30from hyper_parallel.core.pipeline_parallel.pipeline_swap import ( 

31 PipelineSwapSession, 

32 inject_pipeline_swap_steps, 

33 swap_launch_load, 

34 swap_launch_offload, 

35 swap_wait_load, 

36 swap_wait_offload, 

37 unregister_layer_swap_hooks, 

38) 

39from hyper_parallel.core.pipeline_parallel.utils import BatchDimSpec, MetaStep, MetaStepType 

40from hyper_parallel.core.pipeline_parallel._microbatch import _MicroBatch 

41from hyper_parallel.core.pipeline_parallel._p2p import ( 

42 create_p2p_multi_stream_groups, 

43 prepare_batch_p2p_group, 

44) 

45 

46logger = logging.getLogger(__name__) 

47 

48 

49def generate_stage_to_rank_mapping(real_stage_num, stage_num, style='loop'): 

50 """Generate stage to rank mapping for loop or V schedules.""" 

51 if style == 'loop': 

52 return {stage_index: stage_index % real_stage_num for stage_index in range(stage_num)} 

53 if style == 'v': 

54 if stage_num % real_stage_num != 0: 

55 raise ValueError( 

56 f"stage_num {stage_num} must be evenly divisible by real_stage_num {real_stage_num} for V schedules." 

57 ) 

58 mapping = {} 

59 rank_index = 0 

60 for stage_index in range(stage_num): 

61 mapping[stage_index] = rank_index 

62 if (stage_index + 1) % real_stage_num == 0: 

63 continue 

64 if (stage_index // real_stage_num) % 2 == 0: 

65 rank_index += 1 

66 else: 

67 rank_index -= 1 

68 return mapping 

69 raise ValueError(f"Unsupported stage rank mapping style: {style}") 

70 

71 

72def generate_rank_to_stage_mapping(real_stage_num, stage_num, style='loop'): 

73 """Invert the stage to rank mapping.""" 

74 stage_to_rank = generate_stage_to_rank_mapping(real_stage_num, stage_num, style) 

75 rank_to_stages = defaultdict(list) 

76 for stage_index, rank in stage_to_rank.items(): 

77 rank_to_stages[rank].append(stage_index) 

78 

79 for stages in rank_to_stages.values(): 

80 stages.sort() 

81 return dict(rank_to_stages) 

82 

83 

84def iter_leaf_meta_steps(step): 

85 """Yield leaf MetaSteps by recursively expanding composite containers.""" 

86 if step is None: 

87 return 

88 if step.sub_steps: 

89 for sub_step in step.sub_steps: 

90 

91 yield from iter_leaf_meta_steps(sub_step) 

92 return 

93 yield step 

94 

95 

96class PipelineContext: 

97 """Per-run state handed to a custom execution function (see 

98 :meth:`PipelineScheduleRuntime.register_custom_function`). 

99 

100 A plain data carrier for one :meth:`PipelineScheduleRuntime.run_microbatches` 

101 call. The P2P helpers (``wait_fwd_recv`` / ``wait_bwd_recv`` / ``send_fwd`` 

102 / ``send_bwd``) and the ``enable_dxdw_split`` flag live on the schedule, so a 

103 callback reaches them through :attr:`schedule`, e.g. 

104 ``ctx.schedule.send_bwd(stage, micro_index)``. 

105 

106 Attributes: 

107 schedule: The owning :class:`PipelineScheduleRuntime`. 

108 arg_mbs: Per-micro-batch positional args. 

109 kwarg_mbs: Per-micro-batch keyword args. 

110 losses: Mutable list collecting per-step losses. 

111 """ 

112 

113 def __init__(self, schedule: "PipelineScheduleRuntime", arg_mbs: list, 

114 kwarg_mbs: list, losses: list) -> None: 

115 """Bundle the active schedule with one run's micro-batch inputs and losses.""" 

116 self.schedule = schedule 

117 self.arg_mbs = arg_mbs 

118 self.kwarg_mbs = kwarg_mbs 

119 self.losses = losses 

120 self.fsdp_comm_controller = schedule.fsdp_comm_controller 

121 

122 

123class PipelineScheduleRuntime(ABC): 

124 """ 

125 Base class for pipeline schedule. 

126 Implements the `split_microbatches` and `run_microbatches` method. 

127 Derived classes should implement `run_microbatches` method and `run` method. 

128 

129 Supports registering **custom execution functions** for any 

130 :class:`MetaStepType` via :meth:`register_custom_function`. When 

131 ``run_microbatches`` encounters a step whose type has a registered 

132 handler, it creates a :class:`PipelineContext` and delegates execution 

133 to the handler instead of using the built-in logic. 

134 

135 Args: 

136 stages (list[PipelineStage], PipelineStage): PipelineStage used to run_microbatches. 

137 micro_batch_num (int): The number of micro-batch. 

138 args_batch_dim (int | BatchDimSpec | list | tuple, optional): Per 

139 positional-arg batch dim, indexed by arg position. Entries may be 

140 plain ``int`` (or ``None`` to keep the default); a single-input 

141 model may pass a bare ``int``/``BatchDimSpec`` instead of a 

142 one-element list (wrapped automatically). Default ``None``. 

143 kwargs_batch_dim (dict, optional): Per keyword-arg batch dim, mapping 

144 arg name to a plain ``int`` or ``BatchDimSpec``. Default ``None``. 

145 swap (bool, optional): Whether to inject pipeline activation swap 

146 control steps. Supported by ``ScheduleGPipe``, ``Schedule1F1B``, 

147 and ``ScheduleInterleaved1F1B``. Default ``False``. 

148 p2p_transport (str, optional): How pipeline send/recv are issued. 

149 ``"auto"`` (default) — gap-time duplex batching on overlap_b_f 

150 schedules (``coalesce_p2p``: same-peer send+recv as one 

151 ``batch_isend_irecv``, TX||RX; hardware-validated and measured a 

152 net win on real workloads), plain per-op ``isend``/``irecv`` 

153 everywhere else. ``"plain"`` — force per-op ``isend``/``irecv`` 

154 (escape hatch for transports or topologies where batching 

155 misbehaves). ``"batch"`` — duplex batching explicitly (what 

156 ``"auto"`` picks under overlap_b_f). ``"boundary"`` — 

157 EXPERIMENTAL fwd-boundary batching: each overlap's ``F_SEND`` + 

158 the next slot's recvs go out mid-overlap, right after the forward, 

159 as per-op solo batches; only ``B_SEND`` waits for the backward. 

160 Avoids the duplex handle's send-coupling (a2a-friendly) and posts 

161 the activation send ~half a slot early, but is not yet 

162 hardware-validated — opt in deliberately. Must be set identically 

163 on every rank — HCCL cannot match a batched op against a plain one 

164 (EI0005). On backends that require full-group participation before 

165 the first batched P2P call, batch-backed modes prepare the PP group 

166 once at their first run boundary. 

167 ``"multi_stream"`` — EXPERIMENTAL: the same gap-time duplex 

168 batching as ``"batch"``, but each adjacent PP peer pair uses its 

169 own two-rank communication group so the previous and next PP edges 

170 can progress on separate communication streams. 

171 """ 

172 

173 _P2P_TRANSPORTS = ("auto", "plain", "batch", "boundary", "multi_stream") 

174 

175 def __init__(self, 

176 stages, 

177 micro_batch_num, 

178 args_batch_dim=None, 

179 kwargs_batch_dim=None, 

180 output_concat_dim=None, 

181 overlap_p2p=False, 

182 swap=False, 

183 p2p_transport="auto"): 

184 if p2p_transport not in self._P2P_TRANSPORTS: 

185 raise ValueError( 

186 f"p2p_transport must be one of {self._P2P_TRANSPORTS}, got " 

187 f"{p2p_transport!r}" 

188 ) 

189 self.stages = self._check_stages(stages) 

190 self.micro_batch_num = micro_batch_num 

191 self._args_batch_dim = self._normalize_args_batch_dim(args_batch_dim) 

192 self._kwargs_batch_dim = self._normalize_kwargs_batch_dim(kwargs_batch_dim) 

193 # Every key on the wire is one DATA_LOAD actually populated. MPipe 

194 # overrides this in ``construct_exec_order``. 

195 self._data_keys = tuple(self._kwargs_batch_dim or ()) 

196 self._output_concat_dim = output_concat_dim 

197 self.split_micro_batch = _MicroBatch( 

198 self.micro_batch_num, self._args_batch_dim, self._kwargs_batch_dim) 

199 self.n_local_stages = len(self.stages) 

200 self._stage_dict = self.convert_stages_dict() 

201 self.real_stage_num = self.stages[0].stage_num // self.n_local_stages 

202 self._stage_num = self.stages[0].stage_num 

203 self._stage_to_rank_index = None 

204 self._overlap_p2p = overlap_p2p 

205 self.exec_order = {} 

206 self.fsdp_comm_controller = FSDPCommController(self.stages, micro_batch_num) 

207 if self.fsdp_comm_controller.stage_contexts: 

208 has_wrapped_stage = any(stage.all_hsdp_schedulers and stage.has_activation_swap for stage in self.stages) 

209 supported_schedule = type(self) in (ScheduleGPipe, Schedule1F1B, ScheduleInterleaved1F1B) 

210 if (swap or has_wrapped_stage) and not (supported_schedule and swap): 

211 raise ValueError( 

212 "HSDP pipeline stages require swap=True with ScheduleGPipe, " 

213 "Schedule1F1B, or ScheduleInterleaved1F1B for activation swap" 

214 ) 

215 for stage in self.stages: 

216 if stage.all_hsdp_schedulers: 

217 stage.fsdp_comm_controller = self.fsdp_comm_controller 

218 self._init_stages() 

219 self._build_stage_to_rank_index() 

220 self.fwd_handle_cache = {} 

221 self.bwd_handle_cache = {} 

222 self._custom_fn_map = {} 

223 self._pp_swap_enabled = swap 

224 self._swap_keys = frozenset() 

225 self._swap_session = None 

226 self.data_iterator = None 

227 self._pp_fsdp_composed = False 

228 self._dp_group_info = None 

229 self.last_local_tokens = 0 

230 # Outstanding async send handle groups for the in-flight 

231 # ``run_microbatches`` call; reset per run and drained at its end. 

232 self._send_handles = [] 

233 # ``p2p_transport`` resolves in ``build_exec_order`` (it needs the 

234 # subclass's ``_overlap_b_f``) to one of: 

235 # 

236 # * ``"batch"`` (the ``"auto"`` default on overlap_b_f schedules) — 

237 # gap-time duplex via ``coalesce_p2p``: same-peer send+recv as one 

238 # ``batch_isend_irecv`` (TX||RX on the full-duplex link). 

239 # Waiting the whole batch before consuming its recv also waits for 

240 # the riding send, which can reduce EP all-to-all overlap. 

241 # * ``"plain"`` (the ``"auto"`` default elsewhere) — per-op 

242 # ``isend``/``irecv``, the upstream-original path. 

243 # * ``"boundary"`` (EXPERIMENTAL, explicit opt-in only) — fwd-boundary 

244 # batching. ``attach_fwd_boundary_p2p`` hangs each steady gap's 

245 # ``F_SEND`` (its data is ready when the overlap's forward finishes 

246 # — the backward, ~2x FLOPs, is the long pole) plus the next slot's 

247 # recvs on the OVERLAP_B_F step; the stage's after-forward hook 

248 # fires ``exec_boundary_p2p`` at the fwd/bwd boundary, while the 

249 # backward is still running. The send leaves roughly half a slot 

250 # early — the only mode that moves the SENDER's post time — and the 

251 # recv handles carry no send (a2a-friendly). Every op is a per-op 

252 # solo batch and ``coalesce_p2p`` is NOT run: a hoisted recv cannot 

253 # stay duplexed with a send that is only ready later, and 

254 # asymmetric shapes (one end duplex, other end split) hang — 

255 # all-solo keeps per-pair batch sequences complementary 

256 # ([S,R] vs [R,S]), safe under both candidate HCCL pairing 

257 # semantics. Promote to the auto default only after it earns both 

258 # a hardware accuracy pass and a perf win over "batch". 

259 # * ``"multi_stream"`` (EXPERIMENTAL, explicit opt-in only) — keeps the 

260 # ``"batch"`` schedule and same-peer duplex fusion, but routes each 

261 # physical PP edge through a fixed two-rank group so neighboring 

262 # edges can use separate communication streams. Group count is 

263 # bounded by physical PP degree (at most two per rank), not by the 

264 # number of micro-batches. 

265 # 

266 # Two transport invariants for any future rewrite: plain per-pair 

267 # streams need the gap's recv-first/send-first complementarity (a 

268 # send-crossing hoist made both ends recv-first -> rendezvous deadlock, 

269 # 2026-06), and batch pairing needs per-pair shape mirroring (a 

270 # one-sided split made 2 solos face 1 duplex -> hang, 2026-06). 

271 self._p2p_transport = p2p_transport 

272 # Effective mode + per-op batch gating; set by ``build_exec_order``. 

273 self._p2p_mode = None 

274 self._batch_p2p = False 

275 self._batch_p2p_group = None 

276 self._batch_p2p_group_initialized = False 

277 # ``peer_global_rank -> two-rank process group``. Populated only for 

278 # the experimental ``p2p_transport="multi_stream"`` mode. 

279 self._p2p_multi_stream_groups = {} 

280 self._p2p_multi_stream_groups_initialized = False 

281 # OVERLAP steps whose boundary_p2p was already issued this run (the 

282 # stage after-forward hook and the post-step safety net are both 

283 # allowed to call exec_boundary_p2p; reset per run_microbatches call). 

284 self._boundary_issued = set() 

285 # (fwd stage_index, micro_index) -> armed OVERLAP step, consumed by the 

286 # stage after-forward hook to fire the boundary issue mid-overlap. 

287 self._pending_boundary = {} 

288 

289 @property 

290 def kwargs_batch_dim(self) -> dict: 

291 """Per-kwarg batch-dim split spec declared by the model's pipeline setup. 

292 

293 Read by the trainer's PP step to forward exactly the batch keys the 

294 schedule knows how to split into per-micro kwargs (text: attention_mask / 

295 position_ids; VL also pixel_values / image_grid_thw / mm_token_type_ids). 

296 """ 

297 return self._kwargs_batch_dim or {} 

298 

299 def register_custom_function(self, step_type: MetaStepType, fn) -> None: 

300 """Register a custom execution function for the given step type. 

301 

302 When :meth:`run_microbatches` encounters a :class:`MetaStep` whose 

303 ``type`` matches ``step_type``, it calls ``fn(step, ctx)`` instead 

304 of the built-in logic. 

305 

306 Args: 

307 step_type: The :class:`MetaStepType` to intercept. 

308 fn: A callable with signature ``(step: MetaStep, ctx: PipelineContext) -> None``. 

309 

310 When pipeline activation swap is enabled, callbacks that 

311 execute FWD leaves must call ``ctx.schedule.execute_fwd_leaf`` 

312 so swap collection runs in the matching chunk context. 

313 

314 Example: 

315 >>> def my_overlap_callback(step, ctx): 

316 ... fwd_step, bwd_step = step.sub_steps 

317 ... # custom parallel execution logic 

318 >>> schedule.register_custom_function(MetaStepType.OVERLAP_F_B, my_overlap_callback) 

319 """ 

320 self._custom_fn_map[step_type] = fn 

321 

322 

323 def _inject_local_pp_swap_actions(self): 

324 """Annotate the local rank schedule with pipeline activation-swap actions.""" 

325 self._swap_keys = frozenset() 

326 if not self._pp_swap_enabled: 

327 return 

328 current_rank = self._stage_to_rank_index[self.stages[0].stage_index] 

329 unregister_layer_swap_hooks(self.stages) 

330 self.exec_order[current_rank] = inject_pipeline_swap_steps(self.exec_order[current_rank]) 

331 self._swap_keys = frozenset( 

332 (step.stage_index, step.micro_index) 

333 for step in self.exec_order[current_rank] 

334 if step is not None and step.type == MetaStepType.SWAP_LAUNCH_OFFLOAD 

335 ) 

336 

337 @abstractmethod 

338 def _build_stage_to_rank_index(self) -> None: 

339 """ 

340 Build attribute of _stage_to_rank_index. 

341 Each subclass constructs it according to its own schedule style. 

342 """ 

343 

344 @abstractmethod 

345 def construct_exec_order(self) -> None: 

346 """Build exec order, PP cmopute and PP comms(Send/Recv)""" 

347 

348 def build_exec_order(self) -> None: 

349 """Build compute/P2P steps, form transport containers, then inject activation swap. 

350 

351 Parameter communication follows actual module hooks rather than schedule 

352 steps. Swap actions stay outside P2P containers and wait before backward 

353 reads activations; split weight backward needs no repeated activation load. 

354 """ 

355 mode = self._p2p_transport 

356 if mode == "auto": 

357 mode = "batch" if getattr(self, "_overlap_b_f", False) else "plain" 

358 self._p2p_mode = mode 

359 self._batch_p2p = mode != "plain" 

360 # Multi-stream tensor P2P uses edge groups, but dynamic-shape metadata still uses the full PP group. 

361 self._batch_p2p_group = ( 

362 self._resolve_batch_p2p_group() if self._batch_p2p else None 

363 ) 

364 if mode == "multi_stream": 

365 self._init_p2p_multi_stream_groups() 

366 self.construct_exec_order() 

367 if mode == "boundary": 

368 # fwd-boundary mode: hang the forward's F_SEND + next slot's recvs 

369 # on the OVERLAP step (issued mid-overlap, right after the 

370 # forward). Everything stays per-op solo batches — deliberately 

371 # NO coalesce_p2p (see __init__). 

372 self.exec_order = attach_fwd_boundary_p2p(self.exec_order) 

373 elif mode in ("batch", "multi_stream"): 

374 # Coalesce contiguous P2P runs into BATCH_SEND_RECV so the runtime 

375 # issues same-peer send+recv as one duplex batch. NOTE: couples 

376 # the riding send into the compute-gating recv wait — see 

377 # __init__. 

378 self.exec_order = coalesce_p2p(self.exec_order) 

379 self._inject_local_pp_swap_actions() 

380 

381 def _init_p2p_multi_stream_groups(self) -> None: 

382 """Create adjacent two-rank groups for multi-stream P2P transport.""" 

383 first_stage = self.stages[0] 

384 mesh = getattr(first_stage, "mesh", None) 

385 pp_rank_list = ( 

386 list(mesh.rank_list) 

387 if mesh is not None 

388 else dist.get_process_group_ranks(first_stage.pp_group) 

389 ) 

390 self._p2p_multi_stream_groups = create_p2p_multi_stream_groups( 

391 pp_rank_list, 

392 include_wrap=self.n_local_stages > 1, 

393 ) 

394 

395 def _p2p_op(self, op_type, tensor, peer): 

396 """Build a P2P descriptor, selecting the multi-stream group when enabled.""" 

397 group = self._batch_p2p_group 

398 if self._p2p_mode == "multi_stream": 

399 group = self._p2p_multi_stream_groups.get(peer) 

400 if group is None: 

401 raise RuntimeError( 

402 f"No P2P multi-stream group was created for peer global rank {peer}. " 

403 f"Available peers are {sorted(self._p2p_multi_stream_groups)}." 

404 ) 

405 if op_type not in ("isend", "irecv"): 

406 raise ValueError(f"Unsupported pipeline P2P operation: {op_type!r}.") 

407 op = dist.isend if op_type == "isend" else dist.irecv 

408 return dist.P2POp(op, tensor, peer, group=group) 

409 

410 def convert_stages_dict(self): 

411 """convert stages to dict.""" 

412 stage_dict = {} 

413 for stage in self.stages: 

414 stage_dict[stage.stage_index] = stage 

415 return stage_dict 

416 

417 def split_microbatches(self, args, kwargs): 

418 """split_microbatches.""" 

419 if args or kwargs: 

420 args_split, kwargs_split = self.split_micro_batch(args, kwargs) 

421 return args_split, kwargs_split 

422 return [[] for _ in range(self.micro_batch_num)], [{} for _ in range(self.micro_batch_num)] 

423 

424 @staticmethod 

425 def _to_spec(elem): 

426 """Normalize one batch-dim entry: ``int`` -> ``BatchDimSpec``. 

427 

428 ``None`` and ``BatchDimSpec`` pass through unchanged. ``bool`` is 

429 rejected even though it is an ``int`` subclass, so ``True``/``False`` 

430 are not silently read as dims 1/0. 

431 """ 

432 if elem is None or isinstance(elem, BatchDimSpec): 

433 return elem 

434 if isinstance(elem, int) and not isinstance(elem, bool): 

435 return BatchDimSpec(elem) 

436 raise TypeError( 

437 f"batch-dim entry must be int, BatchDimSpec or None, but got {type(elem)}.") 

438 

439 @staticmethod 

440 def _normalize_args_batch_dim(args_batch_dim): 

441 """Accept a plain ``int``/``BatchDimSpec`` or a ``list``/``tuple`` of them. 

442 

443 ``args_batch_dim`` is a per-arg spec indexed by positional-arg position 

444 (see ``_MicroBatch``). A single-input model can pass a bare ``int`` / 

445 ``BatchDimSpec`` instead of the awkward one-element 

446 ``BatchDimSpec.from_tuple((0,))``; elements may be plain ``int`` (or 

447 ``None`` to keep the default). Always returns ``None`` or a 

448 ``tuple[BatchDimSpec | None]`` so downstream per-arg indexing is 

449 unchanged. 

450 """ 

451 if args_batch_dim is None: 

452 return None 

453 if isinstance(args_batch_dim, BatchDimSpec) or \ 

454 (isinstance(args_batch_dim, int) and not isinstance(args_batch_dim, bool)): 

455 args_batch_dim = (args_batch_dim,) 

456 if isinstance(args_batch_dim, (list, tuple)): 

457 return tuple(PipelineScheduleRuntime._to_spec(e) for e in args_batch_dim) 

458 raise TypeError( 

459 f"args_batch_dim must be int, BatchDimSpec or a list/tuple of them, " 

460 f"but got {type(args_batch_dim)}.") 

461 

462 @staticmethod 

463 def _normalize_kwargs_batch_dim(kwargs_batch_dim): 

464 """Accept plain ``int`` dict values: ``{\"x\": 0}`` -> ``{\"x\": BatchDimSpec(0)}``. 

465 

466 ``kwargs_batch_dim`` maps each keyword-arg name to its batch dim. 

467 Returns ``None`` or a ``dict[str, BatchDimSpec | None]`` so downstream 

468 per-key indexing is unchanged. 

469 """ 

470 if kwargs_batch_dim is None: 

471 return None 

472 if not isinstance(kwargs_batch_dim, dict): 

473 raise TypeError( 

474 f"kwargs_batch_dim must be a dict[str, int | BatchDimSpec], " 

475 f"but got {type(kwargs_batch_dim)}.") 

476 return {k: PipelineScheduleRuntime._to_spec(v) for k, v in kwargs_batch_dim.items()} 

477 

478 def _check_stages(self, stages): 

479 """check stages type.""" 

480 if isinstance(stages, hyper_parallel.PipelineStage): 

481 return [stages] 

482 if isinstance(stages, (list, tuple)): 

483 for stage in stages: 

484 if not isinstance(stage, hyper_parallel.PipelineStage): 

485 raise TypeError(f"Argument 'stages' must be type of PipelineStage, \ 

486 list or tuple of PipelineStage, but got list or tuple of {type(stage)}.") 

487 return stages 

488 raise TypeError(f"Argument 'stages' must be type of PipelineStage, \ 

489 list or tuple of PipelineStage, but got type of {type(stages)}.") 

490 

491 def _init_stages(self): 

492 """init stages.""" 

493 pp_group = None 

494 for stage in self.stages: 

495 # Virtual chunks on one rank must share the automatically created 

496 # communicator; native new_group does not cache equivalent groups. 

497 if stage.pp_group is None and stage.mesh is None: 

498 stage.pp_group = pp_group 

499 stage.init(self.n_local_stages) 

500 pp_group = stage.pp_group 

501 # After-forward hook: lets the schedule issue fwd-boundary P2P the 

502 # moment a forward chunk completes (no-op unless an OVERLAP step 

503 # with boundary_p2p was armed for that (stage, micro)). 

504 stage._after_forward_chunk = self._on_forward_chunk_done # pylint: disable=W0212 

505 

506 def _on_forward_chunk_done(self, stage_index, micro_index): 

507 """Stage after-forward hook: fire the armed boundary P2P, if any. 

508 

509 Runs on the thread executing the forward (the overlap callback's 

510 ``fwd_fn`` / the main thread), at the fwd/bwd boundary — the paired 

511 backward is still running, so the boundary ops overlap it. Keyed by 

512 the overlap's forward ``(stage_index, micro_index)``; unrelated 

513 forwards (warm-up steps, recompute re-runs of past micros) miss the 

514 key and no-op. 

515 """ 

516 step = self._pending_boundary.pop((stage_index, micro_index), None) 

517 if step is not None: 

518 self.exec_boundary_p2p(step) 

519 

520 def run(self, *args: Any, **kwargs: Any) -> list: 

521 """schedule run.""" 

522 losses = [] 

523 try: 

524 if self._pp_swap_enabled: 

525 self._swap_session = PipelineSwapSession(self._swap_keys) 

526 split_args, split_kwargs = self.split_microbatches(args, kwargs) 

527 self.run_microbatches(split_args, split_kwargs, losses) 

528 finally: 

529 self._drain_inflight_p2p() 

530 if self._swap_session is not None: 

531 self._swap_session.close() 

532 self._swap_session = None 

533 return losses 

534 

535 def run_with_dataiterator(self, data_iterator: Iterator, pp_fsdp_composed: bool, 

536 dp_group_info: object = None, **kwargs: object) -> list: 

537 """Run the schedule, pulling each micro-batch from ``data_iterator``. 

538 

539 Args: 

540 data_iterator (Iterator): Yields one micro-batch per DATA_LOAD. 

541 pp_fsdp_composed (bool): Whether PP composes with (F/H)SDP. 

542 dp_group_info (object): DP group used to all-reduce the token count. 

543 **kwargs: Accepted for signature parity with :meth:`run`; unused. 

544 

545 Returns: 

546 list: The last stage's per-micro-batch losses (empty elsewhere). 

547 """ 

548 del kwargs 

549 self.data_iterator = data_iterator 

550 self._pp_fsdp_composed = pp_fsdp_composed 

551 # DATA_LOAD all-reduces n_valid over this group under PP+FSDP; the 

552 # trainer owns the handle, so it has to be threaded in. 

553 self._dp_group_info = dp_group_info 

554 self.last_local_tokens = 0 

555 rargs = [[] for _ in range(self.micro_batch_num)] 

556 rkwargs = [{} for _ in range(self.micro_batch_num)] 

557 losses = [] 

558 try: 

559 if self._pp_swap_enabled: 

560 self._swap_session = PipelineSwapSession(self._swap_keys) 

561 self.run_microbatches(rargs, rkwargs, losses) 

562 finally: 

563 # An exception unwinds past the end-of-iteration drain, leaving 

564 # handles un-waited; wait them so the contract holds on that path too. 

565 self._drain_inflight_p2p() 

566 if self._swap_session is not None: 

567 self._swap_session.close() 

568 self._swap_session = None 

569 return losses 

570 

571 def sync_shared_parameters_grad(self): 

572 """sync_shared_parameters_grad.""" 

573 for stage in self.stages: 

574 stage.sync_shared_parameters_grad() 

575 

576 def update_losses(self, stage, loss, losses): 

577 """update_losses.""" 

578 if stage.is_last_stage: 

579 losses.append(loss) 

580 

581 @property 

582 def enable_dxdw_split(self) -> bool: 

583 """Whether this schedule splits ``OVERLAP_B_F`` backward into dx/dw.""" 

584 return getattr(self, "_enable_dxdw_split", False) 

585 

586 def _wait_p2p(self, handles): 

587 for handle in handles: 

588 if handle is not None: 

589 handle.wait() 

590 

591 def _resolve_batch_p2p_group(self): 

592 """Return the common PP group required by every local stage.""" 

593 first_stage = self.stages[0] 

594 group = first_stage.pp_group 

595 for stage in self.stages[1:]: 

596 if stage.pp_group is group or stage.pp_group == group: 

597 continue 

598 raise ValueError( 

599 "Batch P2P requires all local stages to use the same PP process group, " 

600 f"but stages {first_stage.stage_index} and {stage.stage_index} use different groups." 

601 ) 

602 return group 

603 

604 def _ensure_batch_p2p_group_initialized(self) -> None: 

605 """Run backend-specific PP-group preparation once before batched P2P.""" 

606 if (not self._batch_p2p or self._batch_p2p_group_initialized 

607 or self.real_stage_num <= 1): 

608 return 

609 prepare_batch_p2p_group(self._batch_p2p_group) 

610 self._batch_p2p_group_initialized = True 

611 

612 def _ensure_p2p_multi_stream_groups_initialized(self) -> None: 

613 """Prepare multi-stream edge groups in their stable creation order.""" 

614 if (getattr(self, "_p2p_mode", None) != "multi_stream" 

615 or getattr(self, "_p2p_multi_stream_groups_initialized", False)): 

616 return 

617 for group in self._p2p_multi_stream_groups.values(): 

618 prepare_batch_p2p_group(group) 

619 self._p2p_multi_stream_groups_initialized = True 

620 

621 def _drain_inflight_p2p(self): 

622 """Wait every P2P handle still in flight — error-path cleanup. 

623 

624 run_microbatches waits its deferred sends only in the end-of-iteration 

625 drain; an exception mid-iteration unwinds past that drain, leaving issued 

626 isend/irecv handles un-waited in ``_send_handles`` and the recv caches 

627 (the ``CommHandle destroyed without calling wait()`` warning). run()'s 

628 finally calls this so every handle is still ``wait()``-ed — honoring the 

629 comm contract — on the error path too, and pops them so a later run() 

630 does not re-wait stale handles (the recv caches are never reset per run). 

631 No-op on the normal path: the drain already emptied ``_send_handles`` and 

632 every cached recv was consumed. 

633 """ 

634 while self._send_handles: 

635 self._wait_p2p(self._send_handles.pop()) 

636 while self.fwd_handle_cache: 

637 self._wait_p2p(self.fwd_handle_cache.popitem()[1]) 

638 while self.bwd_handle_cache: 

639 self._wait_p2p(self.bwd_handle_cache.popitem()[1]) 

640 

641 def _batched_issue(self, specs): 

642 """Launch same-peer P2P ``specs`` as one ``batch_isend_irecv`` group. 

643 

644 ``specs`` are ``(op_type, tensor, peer_global_rank)`` from the stage's 

645 ``*_specs`` builders (which carry the meta/bookkeeping side effects). 

646 Returns the native list of work handles or ``[]`` — shaped like 

647 the per-op ``exec_*_ops`` return so the cache / drain paths are 

648 unchanged. Only the launch is coalesced; matching stays per-peer FIFO. 

649 """ 

650 if not specs: 

651 return [] 

652 ops = [self._p2p_op(op_type, tensor, peer) for op_type, tensor, peer in specs] 

653 return dist.batch_isend_irecv(ops) 

654 

655 # --- P2P step primitives ------------------------------------------------ 

656 # One method per cross-rank comm action, used both by the runtime loop 

657 # (``_exec_step``) and by OVERLAP callbacks (via ``ctx.schedule``). With 

658 # ``overlap_p2p=True`` comm is decoupled from its compute: a recv caches its 

659 # handles for the consuming step to ``wait_*`` later, and a send defers its 

660 # handles to the end-of-iteration drain. With ``overlap_p2p=False`` every 

661 # op waits inline. 

662 

663 def recv_fwd(self, stage: "hyper_parallel.PipelineStage", micro_index: int) -> None: 

664 """Post the FWD recv for ``micro_index``; cache it (overlap_p2p) or wait now.""" 

665 handles = (self._batched_issue(stage.fwd_recv_specs(micro_index)) 

666 if self._batch_p2p else stage.exec_fwd_recv_ops(micro_index)) 

667 if self._overlap_p2p: 

668 self.fwd_handle_cache[(stage.stage_index, micro_index)] = handles 

669 else: 

670 self._wait_p2p(handles) 

671 

672 def recv_bwd(self, stage: "hyper_parallel.PipelineStage", micro_index: int) -> None: 

673 """Post the BWD recv for ``micro_index``; cache it (overlap_p2p) or wait now.""" 

674 handles = (self._batched_issue(stage.bwd_recv_specs(micro_index)) 

675 if self._batch_p2p else stage.exec_bwd_recv_ops(micro_index)) 

676 if self._overlap_p2p: 

677 self.bwd_handle_cache[(stage.stage_index, micro_index)] = handles 

678 else: 

679 self._wait_p2p(handles) 

680 

681 def wait_fwd_recv(self, stage_index: int, micro_index: int) -> None: 

682 """Wait the FWD recv cached by :meth:`recv_fwd`; no-op if nothing is cached.""" 

683 handles = self.fwd_handle_cache.pop((stage_index, micro_index), None) 

684 if handles: 

685 self._wait_p2p(handles) 

686 

687 def wait_bwd_recv(self, stage_index: int, micro_index: int) -> None: 

688 """Wait the BWD recv cached by :meth:`recv_bwd`; no-op if nothing is cached.""" 

689 handles = self.bwd_handle_cache.pop((stage_index, micro_index), None) 

690 if handles: 

691 self._wait_p2p(handles) 

692 

693 def send_fwd(self, stage: "hyper_parallel.PipelineStage", micro_index: int) -> None: 

694 """Send this stage's forward output for ``micro_index`` to the next stage.""" 

695 handles = (self._batched_issue(stage.fwd_send_specs(micro_index)) 

696 if self._batch_p2p else stage.exec_fwd_send_ops(micro_index)) or [] 

697 if self._overlap_p2p: 

698 # Append the whole handle group: run_microbatches drains _send_handles 

699 # group by group, so a bare handle would be wrongly iterated as a list. 

700 self._send_handles.append(handles) 

701 else: 

702 self._wait_p2p(handles) 

703 

704 def send_bwd(self, stage: "hyper_parallel.PipelineStage", micro_index: int) -> None: 

705 """Send this stage's input-gradient for ``micro_index`` to the previous stage. 

706 

707 Driven by the scheduler's ``BWD_SEND`` step. It pops the input grad that 

708 the backward (unified ``backward_one_chunk`` or, under 

709 ``enable_dxdw_split=True``, ``backward_input_one_chunk``) wrote to the 

710 stage's ``bwd_cache``. Calling it manually in addition to the scheduled 

711 ``BWD_SEND`` would double-send the gradient. 

712 """ 

713 handles = (self._batched_issue(stage.bwd_send_specs(micro_index)) 

714 if self._batch_p2p else stage.exec_bwd_send_ops(micro_index)) or [] 

715 if self._overlap_p2p: 

716 self._send_handles.append(handles) 

717 else: 

718 self._wait_p2p(handles) 

719 

720 def _arm_boundary(self, step): 

721 """Register ``step`` for the stage after-forward hook; return its key. 

722 

723 No-op (returns ``None``) unless ``step`` carries ``boundary_p2p``. The 

724 key is the overlap's forward ``(stage_index, micro_index)`` — exactly 

725 what the hook receives when that forward chunk completes. 

726 """ 

727 if not getattr(step, "boundary_p2p", None) or not step.sub_steps: 

728 return None 

729 fwd_sub = next((s for s in step.sub_steps 

730 if s.type == MetaStepType.FWD), None) 

731 if fwd_sub is None: 

732 return None 

733 key = (fwd_sub.stage_index, fwd_sub.micro_index) 

734 self._pending_boundary[key] = step 

735 return key 

736 

737 def _finish_boundary(self, step, armed_key) -> None: 

738 """Post-step safety net: issue any boundary P2P the hook missed.""" 

739 self.exec_boundary_p2p(step) 

740 if armed_key is not None: 

741 self._pending_boundary.pop(armed_key, None) 

742 

743 def exec_boundary_p2p(self, step) -> None: 

744 """Issue ``step.boundary_p2p`` (fwd-boundary P2P) once per run. 

745 

746 Fired by the stage after-forward hook (``_on_forward_chunk_done``) the 

747 moment the overlap's forward chunk completes — the backward is still 

748 running on its own thread, so the F_SEND leaves ~half a slot early and 

749 the next slot's recvs are already posted when the peers' sends arrive. 

750 Idempotent per ``run_microbatches`` call: the post-step safety net 

751 (``_finish_boundary``) also invokes it, so an overlap whose forward 

752 never went through ``forward_one_chunk`` degrades to gap-time issue 

753 order instead of dropping the ops. 

754 

755 Dispatches through the existing per-op helpers (``send_fwd`` / 

756 ``recv_fwd`` / ``recv_bwd``), so batching, handle caching for 

757 ``wait_*_recv`` and deferred-send bookkeeping behave exactly like the 

758 scheduled steps they replace. No-op for steps without 

759 ``boundary_p2p``. 

760 """ 

761 ops = getattr(step, "boundary_p2p", None) 

762 if not ops or id(step) in self._boundary_issued: 

763 return 

764 self._boundary_issued.add(id(step)) 

765 for sub in ops: 

766 stage = self._stage_dict[sub.stage_index] 

767 if sub.type == MetaStepType.FWD_SEND: 

768 self.send_fwd(stage, sub.micro_index) 

769 elif sub.type == MetaStepType.FWD_RECV: 

770 self.recv_fwd(stage, sub.micro_index) 

771 elif sub.type == MetaStepType.BWD_RECV: 

772 self.recv_bwd(stage, sub.micro_index) 

773 elif sub.type == MetaStepType.BWD_SEND: 

774 # attach_fwd_boundary_p2p never hoists BWD_SEND (its grad is 

775 # produced by the backward still in flight); defensive only. 

776 self.send_bwd(stage, sub.micro_index) 

777 

778 # ``op_type -> (specs builder name, route kind)`` for a coalesced sub-step. 

779 # ``route`` is the recv-cache kind (so wait_*_recv finds the handle), or 

780 # ``None`` for a send (no local consumer). 

781 _BATCH_SUB_DISPATCH = { 

782 MetaStepType.FWD_RECV: ("fwd_recv_specs", "fwd"), 

783 MetaStepType.BWD_RECV: ("bwd_recv_specs", "bwd"), 

784 MetaStepType.FWD_SEND: ("fwd_send_specs", None), 

785 MetaStepType.BWD_SEND: ("bwd_send_specs", None), 

786 } 

787 

788 def _exec_batch_send_recv(self, step) -> None: 

789 """Execute a coalesced P2P run: one ``batch_isend_irecv`` per peer. 

790 

791 Builds each sub-step's specs (same meta/bookkeeping side effects as the 

792 per-step ``recv_fwd`` / ``send_fwd`` / ...), groups every op by peer 

793 global rank, and issues one batch per peer so a same-peer send+recv runs 

794 duplex. Handle routing mirrors the per-step path: under 

795 ``overlap_p2p`` a batch carrying a recv is cached for ``wait_*_recv`` 

796 (its send rides along), a send-only batch defers to ``_send_handles``; 

797 without ``overlap_p2p`` every batch waits inline. 

798 """ 

799 # (op_type, tensor, peer, route) per op; route = (kind, stage, micro) 

800 # for a recv, else None. 

801 tagged = [] 

802 for sub in step.sub_steps: 

803 builder_name, kind = self._BATCH_SUB_DISPATCH[sub.type] 

804 stage = self._stage_dict[sub.stage_index] 

805 specs = getattr(stage, builder_name)(sub.micro_index) 

806 route = (kind, sub.stage_index, sub.micro_index) if kind is not None else None 

807 for op_type, tensor, peer in specs: 

808 tagged.append((op_type, tensor, peer, route)) 

809 

810 by_peer = {} 

811 for item in tagged: 

812 by_peer.setdefault(item[2], []).append(item) 

813 

814 for items in by_peer.values(): 

815 ops = [self._p2p_op(op_type, tensor, peer) for op_type, tensor, peer, _ in items] 

816 handles = dist.batch_isend_irecv(ops) 

817 if not handles: 

818 continue 

819 if not self._overlap_p2p: 

820 self._wait_p2p(handles) 

821 continue 

822 recv_routes = [route for *_, route in items if route is not None] 

823 if recv_routes: 

824 for kind, si, mi in recv_routes: 

825 cache = self.fwd_handle_cache if kind == "fwd" else self.bwd_handle_cache 

826 cache[(si, mi)] = handles 

827 else: 

828 self._send_handles.append(handles) 

829 

830 

831 def _exec_step(self, cur_step, arg_mbs, kwarg_mbs, losses): 

832 """Execute one built-in step (non-custom, non-composite). 

833 

834 Each comm step dispatches to a single P2P primitive; each compute step 

835 first waits its cached recv (a no-op under ``overlap_p2p=False``) and 

836 then runs. 

837 """ 

838 # MPipe prestages use stage_index=-1 which isn't in self._stage_dict; 

839 # their branches below never touch ``stage``. 

840 stage_index = cur_step.stage_index 

841 stage = self._stage_dict[stage_index] if stage_index >= 0 else None 

842 micro_index = cur_step.micro_index 

843 step_type = cur_step.type 

844 

845 if step_type in ( 

846 MetaStepType.DATA_LOAD, 

847 MetaStepType.DATA_SEND, 

848 MetaStepType.DATA_RECV, 

849 ): 

850 if self.data_iterator is not None: 

851 self._exec_pipeline_data_steps(step_type, stage_index, micro_index, arg_mbs, kwarg_mbs) 

852 

853 elif step_type in ( 

854 MetaStepType.SWAP_LAUNCH_OFFLOAD, 

855 MetaStepType.SWAP_WAIT_OFFLOAD, 

856 MetaStepType.SWAP_LAUNCH_LOAD, 

857 MetaStepType.SWAP_WAIT_LOAD, 

858 ): 

859 self._exec_pipeline_swap_step(cur_step, arg_mbs, kwarg_mbs) 

860 

861 elif step_type == MetaStepType.FWD_RECV: 

862 self.recv_fwd(stage, micro_index) 

863 

864 elif step_type == MetaStepType.FWD: 

865 self.execute_fwd_leaf(cur_step, arg_mbs, kwarg_mbs, losses) 

866 

867 elif step_type == MetaStepType.FWD_SEND: 

868 self.send_fwd(stage, micro_index) 

869 

870 elif step_type == MetaStepType.BWD_RECV: 

871 self.recv_bwd(stage, micro_index) 

872 

873 elif step_type in (MetaStepType.BWD_INPUT, MetaStepType.BWD_WEIGHT, MetaStepType.BWD): 

874 self.execute_bwd_leaf(cur_step) 

875 

876 elif step_type == MetaStepType.BWD_SEND: 

877 self.send_bwd(stage, micro_index) 

878 

879 

880 def execute_fwd_leaf(self, step: MetaStep, arg_mbs: list, kwarg_mbs: list, losses: list) -> None: 

881 """Execute a forward leaf within its run-scoped swap group context.""" 

882 stage = self._stage_dict[step.stage_index] 

883 micro_index = step.micro_index 

884 self.wait_fwd_recv(stage.stage_index, micro_index) 

885 swap_managed = self._swap_session is not None and self._swap_session.manages(step) 

886 group_context = self._swap_session.group_context(step) if swap_managed else nullcontext() 

887 with group_context: 

888 out = stage.forward_one_chunk(micro_index, arg_mbs[micro_index], kwarg_mbs[micro_index]) 

889 if swap_managed: 

890 # Boundary transport may pop the stage output cache from the 

891 # after-forward hook before this leaf returns. Protect the 

892 # local output while it is still directly available. 

893 self._swap_session.protect_aliases(step, out) 

894 self.update_losses(stage, out, losses) 

895 

896 def execute_bwd_leaf(self, step: MetaStep) -> None: 

897 """Wait for incoming gradients and execute a full, input, or weight backward step.""" 

898 stage = self._stage_dict[step.stage_index] 

899 if step.type == MetaStepType.BWD: 

900 backward = stage.backward_one_chunk 

901 elif step.type == MetaStepType.BWD_INPUT: 

902 backward = stage.backward_input_one_chunk 

903 elif step.type == MetaStepType.BWD_WEIGHT: 

904 backward = stage.backward_weight_one_chunk 

905 else: 

906 raise ValueError(f"Expected a backward leaf, got {step.type}") 

907 self.wait_bwd_recv(step.stage_index, step.micro_index) 

908 backward(step.micro_index) 

909 

910 def _exec_pipeline_data_steps(self, 

911 step_type: MetaStepType, 

912 stage_index: int, 

913 micro_index: int, 

914 arg_mbs: list, 

915 kwarg_mbs: list): 

916 """Execute a pipeline data management step. 

917 

918 active only under ``run_with_dataiterator``; the legacy ``run()`` 

919 skip these step 

920 ie. None self.data_iterator will skip these steps 

921 """ 

922 # Only active under ``run_with_dataiterator``; the legacy ``run()`` 

923 # path pre-stages every per-micro kwarg on every rank already. 

924 if self.data_iterator is None: 

925 return 

926 if step_type == MetaStepType.DATA_LOAD: 

927 if stage_index <= 0: 

928 self._exec_data_load(micro_index, arg_mbs, kwarg_mbs) 

929 elif step_type == MetaStepType.DATA_SEND: 

930 self._exec_data_send(stage_index, micro_index, arg_mbs, kwarg_mbs) 

931 elif step_type == MetaStepType.DATA_RECV: 

932 self._exec_data_recv(stage_index, micro_index, arg_mbs, kwarg_mbs) 

933 

934 def _exec_data_load(self, micro_index: int, arg_mbs: list, kwarg_mbs: list) -> None: 

935 """Load the next micro-batch onto stage 0's device and stage it as ``micro_index``'s input.""" 

936 device = self.stages[0].device 

937 micro_batch = next(self.data_iterator) 

938 if isinstance(micro_batch, list): 

939 micro_batch = micro_batch[micro_index] 

940 micro_batch = { 

941 key: (value.to(device, non_blocking=True) if hasattr(value, "to") else value) 

942 for key, value in micro_batch.items() 

943 } 

944 input_ids = micro_batch["input_ids"] 

945 labels = micro_batch["labels"] 

946 # Ignore the final token after shifting next-token targets. 

947 pad_col = torch.full_like(labels[..., :1], -100) 

948 targets = torch.cat([labels[..., 1:], pad_col], dim=-1).contiguous() 

949 n_valid = max(int((targets != -100).sum().item()), 1) 

950 if getattr(self, "_pp_fsdp_composed", False): 

951 nt = torch.full((1,), n_valid).to(device) 

952 dist.all_reduce(nt, group=self._dp_group_info.group) 

953 n_valid = max(int(nt.item()), 1) 

954 self.last_local_tokens += n_valid 

955 

956 micro_batch["targets"] = targets 

957 for key in self.kwargs_batch_dim: 

958 if key in kwarg_mbs[micro_index].keys(): 

959 kwarg_mbs[micro_index][key] = torch.cat( 

960 [kwarg_mbs[micro_index][key], micro_batch[key]], dim=0) 

961 else: 

962 kwarg_mbs[micro_index][key] = micro_batch[key] 

963 arg_mbs[micro_index] = [input_ids] 

964 

965 def _exec_data_send(self, stage_index: int, micro_index: int, arg_mbs: list, kwarg_mbs: list) -> None: 

966 """Send ``micro_index``'s data keys to the stage that consumes them.""" 

967 if getattr(self, "_data_dst", False): 

968 dst_stage_idx = self._data_dst[stage_index][micro_index] 

969 else: 

970 dst_stage_idx = self.stages[0].dst_stage 

971 dst = self.stages[0]._global_rank(dst_stage_idx) # pylint: disable=protected-access 

972 # One meta round-trip per DATA_SEND instead of K; the matching 

973 # DATA_RECV unpacks the list in the same order. 

974 metas = [] 

975 tensors = [] 

976 for key in self._data_keys: 

977 tensor = (arg_mbs[micro_index][0] if key == "input_ids" 

978 else kwarg_mbs[micro_index][key]) 

979 metas.append([tuple(tensor.shape), tensor.dtype]) 

980 tensors.append(tensor) 

981 dist.send_object_list(metas, dst) 

982 handles = [dist.isend(t, dst) for t in tensors] 

983 self._wait_p2p(handles) 

984 

985 def _exec_data_recv(self, stage_index: int, micro_index: int, arg_mbs: list, kwarg_mbs: list) -> None: 

986 """Receive ``micro_index``'s data keys and stage them as its input.""" 

987 if getattr(self, "_data_src", False): 

988 src_stage_idx = self._data_src[stage_index][micro_index] 

989 else: 

990 src_stage_idx = self.stages[0].src_stage 

991 src = self.stages[0]._global_rank(src_stage_idx) # pylint: disable=protected-access 

992 device = self.stages[0].device 

993 # One recv_object_list unpacks every key's (shape, dtype) at 

994 # once, matching the packed DATA_SEND above. 

995 metas: list = [None] * len(self._data_keys) 

996 dist.recv_object_list(metas, src) 

997 handles = [] 

998 for key, meta in zip(self._data_keys, metas): 

999 shape, dtype = meta 

1000 buffer = torch.empty(shape, dtype=dtype, device=device) 

1001 handles.append(dist.irecv(buffer, src)) 

1002 if key == "input_ids": 

1003 arg_mbs[micro_index] = [buffer] 

1004 else: 

1005 kwarg_mbs[micro_index][key] = buffer 

1006 self._wait_p2p(handles) 

1007 

1008 def _exec_pipeline_swap_step(self, cur_step, arg_mbs, kwarg_mbs): 

1009 """Execute a pipeline activation-swap control step.""" 

1010 if self._swap_session is None: 

1011 raise RuntimeError("Pipeline swap step executed without an active run session.") 

1012 if cur_step.type == MetaStepType.SWAP_LAUNCH_OFFLOAD: 

1013 swap_launch_offload(cur_step, self, arg_mbs, kwarg_mbs, self._swap_session) 

1014 elif cur_step.type == MetaStepType.SWAP_WAIT_OFFLOAD: 

1015 swap_wait_offload(cur_step, self._swap_session) 

1016 elif cur_step.type == MetaStepType.SWAP_LAUNCH_LOAD: 

1017 swap_launch_load(cur_step, self._swap_session) 

1018 elif cur_step.type == MetaStepType.SWAP_WAIT_LOAD: 

1019 swap_wait_load(cur_step, self._swap_session) 

1020 

1021 def _handoff_fsdp_reduction_tail(self, step: MetaStep) -> None: 

1022 """Choose who consumes the previous HSDP tail for the next compute step.""" 

1023 if self.fsdp_comm_controller.reduction_tail_stage is None: 

1024 return 

1025 backward_types = (MetaStepType.BWD, MetaStepType.BWD_WEIGHT) 

1026 compute_types = (MetaStepType.FWD, MetaStepType.BWD_INPUT, *backward_types) 

1027 leaves = step.sub_steps or (step,) 

1028 if any(leaf.type in compute_types for leaf in leaves): 

1029 backward_stages = {leaf.stage_index for leaf in leaves if leaf.type in backward_types} 

1030 self.fsdp_comm_controller.handoff_reduction_tail(backward_stages) 

1031 

1032 def run_microbatches(self, arg_mbs: list, kwarg_mbs: list, losses: list) -> None: 

1033 """Execute the schedule step by step. 

1034 

1035 Steps whose :attr:`MetaStep.type` has a registered custom function 

1036 are delegated to that function with a :class:`PipelineContext`. 

1037 Composite ``OVERLAP_F_B`` / ``OVERLAP_B_F`` steps without a 

1038 registered handler fall back to executing their ``sub_steps`` 

1039 sequentially via :meth:`_exec_step` — correct but without 

1040 comm/compute overlap. All other steps are executed by 

1041 :meth:`_exec_step`. 

1042 

1043 Logs one ``DEBUG`` line per non-bubble step showing the rank's 

1044 progress: ``rank=<r> step=<i>/<n> <MetaStep>``. Enable with 

1045 ``logging.getLogger('hyper_parallel.core.pipeline_parallel.scheduler') 

1046 .setLevel(logging.DEBUG)`` to trace per-rank schedule advancement 

1047 (handy when diagnosing deadlocks or callback ordering issues). 

1048 """ 

1049 self._ensure_batch_p2p_group_initialized() 

1050 self._ensure_p2p_multi_stream_groups_initialized() 

1051 real_stage_index = self.stages[0].stage_index % self.real_stage_num 

1052 self.fsdp_comm_controller.begin() 

1053 self._send_handles = [] 

1054 self._boundary_issued = set() 

1055 self._pending_boundary = {} 

1056 ctx = None # lazily created 

1057 

1058 ordered = self.exec_order[real_stage_index] 

1059 total_steps = len(ordered) 

1060 logger.debug( 

1061 "run_microbatches start: rank=%d total_steps=%d micro_batch_num=%d", 

1062 real_stage_index, total_steps, self.micro_batch_num, 

1063 ) 

1064 

1065 for step_idx, cur_step in enumerate(ordered): 

1066 if cur_step is None: 

1067 continue 

1068 

1069 logger.debug( 

1070 "rank=%d step=%d/%d %s", 

1071 real_stage_index, step_idx, total_steps, cur_step, 

1072 ) 

1073 

1074 # Arm the fwd-boundary hook: when this step carries boundary_p2p, 

1075 # the stage's after-forward hook fires exec_boundary_p2p the moment 

1076 # the overlap's forward chunk completes (works for any callback — 

1077 # no callback cooperation needed). 

1078 armed_key = self._arm_boundary(cur_step) 

1079 self._handoff_fsdp_reduction_tail(cur_step) 

1080 

1081 # Check for registered custom function 

1082 custom_fn = self._custom_fn_map.get(cur_step.type) 

1083 if custom_fn is not None: 

1084 if ctx is None: 

1085 ctx = PipelineContext(self, arg_mbs, kwarg_mbs, losses) 

1086 custom_fn(cur_step, ctx) 

1087 # Safety net: if the forward hook never fired (custom fwd path), 

1088 # issue the boundary ops now (gap-time order) instead of 

1089 # dropping them. Idempotent. 

1090 self._finish_boundary(cur_step, armed_key) 

1091 elif cur_step.type == MetaStepType.BATCH_SEND_RECV: 

1092 # Coalesced P2P block issues one batch_isend_irecv per peer. 

1093 self._exec_batch_send_recv(cur_step) 

1094 

1095 # Default for composite OVERLAP steps: run sub_steps sequentially. 

1096 # P2P send/recv around these steps are already laid out in two 

1097 # virtual slots by ``add_send_recv``, so sequential execution is 

1098 # semantically equivalent to non-overlapped 1F1B. 

1099 elif (cur_step.type in (MetaStepType.OVERLAP_F_B, MetaStepType.OVERLAP_B_F) 

1100 and cur_step.sub_steps): 

1101 for sub in cur_step.sub_steps: 

1102 self._exec_step(sub, arg_mbs, kwarg_mbs, losses) 

1103 self._finish_boundary(cur_step, armed_key) 

1104 else: 

1105 self._exec_step(cur_step, arg_mbs, kwarg_mbs, losses) 

1106 self.fsdp_comm_controller.finish_handed_off_tail() 

1107 

1108 logger.debug( 

1109 "run_microbatches end: rank=%d pending_send_handles=%d", 

1110 real_stage_index, len(self._send_handles), 

1111 ) 

1112 for stage in self.stages: 

1113 stage.check_weight_backward_complete() 

1114 self.fsdp_comm_controller.finalize() 

1115 self.sync_shared_parameters_grad() 

1116 while self._send_handles: 

1117 self._wait_p2p(self._send_handles.pop()) 

1118 

1119 

1120class _OverlapPhantom: 

1121 """Internal marker used by :func:`add_send_recv` to expand an 

1122 ``OVERLAP_F_B`` or ``OVERLAP_B_F`` step into two virtual time slots. 

1123 

1124 An overlap step composes two sub-steps (``B + F`` or ``F + B``) that 

1125 execute concurrently on the GPU but occupy **two** logical time slots 

1126 in the column-scan sender timeline — the sender can only finish 

1127 emitting the second sub-step's output after the first sub-step has 

1128 completed. Treating an overlap step as a single slot places the RECV 

1129 triggered by the second sub-step too early on the receiver. 

1130 

1131 Each overlap step is expanded into two phantoms: 

1132 * ``is_first_half=True`` — represents the first sub-step's emission 

1133 slot; the original overlap step is emitted into the output 

1134 schedule here (only once). 

1135 * ``is_first_half=False`` — represents the second sub-step's emission 

1136 slot; only its send/recv comms are inserted. 

1137 """ 

1138 

1139 __slots__ = ('obf_step', 'sub_step', 'is_first_half') 

1140 

1141 def __init__(self, obf_step, sub_step, is_first_half: bool): 

1142 self.obf_step = obf_step 

1143 self.sub_step = sub_step 

1144 self.is_first_half = is_first_half 

1145 

1146 

1147def _expand_overlap_slots(scheduler, real_stage_num): 

1148 """Expand OVERLAP steps in a per-rank schedule into 2 virtual time slots. 

1149 

1150 Returns a new ``{rank: [MetaStep | _OverlapPhantom | None, ...]}`` dict 

1151 where each OVERLAP step is replaced by a pair of phantoms. Non-OVERLAP 

1152 entries pass through unchanged. 

1153 """ 

1154 expanded = {} 

1155 for rank in range(real_stage_num): 

1156 order = scheduler[rank] 

1157 exp = [] 

1158 for op in order: 

1159 if (op is not None 

1160 and op.type in (MetaStepType.OVERLAP_F_B, MetaStepType.OVERLAP_B_F) 

1161 and op.sub_steps): 

1162 exp.append(_OverlapPhantom(op, op.sub_steps[0], is_first_half=True)) 

1163 exp.append(_OverlapPhantom(op, op.sub_steps[1], is_first_half=False)) 

1164 else: 

1165 exp.append(op) 

1166 expanded[rank] = exp 

1167 return expanded 

1168 

1169 

1170def _process_rank_items(real_stage_num, current_items, insert_step_comms, new_schedule): 

1171 """Run ``insert_step_comms`` for each rank's current item, even ranks first. 

1172 

1173 Even-before-odd ordering avoids P2P deadlocks between adjacent ranks. 

1174 """ 

1175 for rank in range(0, real_stage_num, 2): 

1176 item = current_items.get(rank) 

1177 if item is not None: 

1178 sub = item.sub_step if isinstance(item, _OverlapPhantom) else item 

1179 insert_step_comms(sub, rank, new_schedule) 

1180 for rank in range(1, real_stage_num, 2): 

1181 item = current_items.get(rank) 

1182 if item is not None: 

1183 sub = item.sub_step if isinstance(item, _OverlapPhantom) else item 

1184 insert_step_comms(sub, rank, new_schedule) 

1185 

1186 

1187def _insert_dataload_before_fwd(schedule): 

1188 """Splice a zero-width ``DATA_LOAD`` immediately before every FWD. 

1189 

1190 Runs AFTER the column scan so the loads never occupy a schedule column: 

1191 a per-FWD DATA_LOAD slot would widen each rank's columns by its 

1192 (rank-dependent) warmup depth and desync the cross-rank scan — the 

1193 last rank's BWD_RECV then lands after the BWD that consumes it. 

1194 DATA_LOAD is local (no comm), so inserting it here cannot affect P2P 

1195 placement; the handler no-ops when ``run_with_dataiterator`` isn't 

1196 active. Composite OVERLAP steps get one load per FWD sub-step, placed 

1197 before the composite. 

1198 """ 

1199 def _loads_for(step): 

1200 """Zero-width DATA_LOADs to splice before ``step`` (may be empty).""" 

1201 if step is None: 

1202 return () 

1203 if step.type == MetaStepType.FWD: 

1204 return (MetaStep(step.micro_index, MetaStepType.DATA_LOAD, step.stage_index),) 

1205 if step.type in (MetaStepType.OVERLAP_F_B, MetaStepType.OVERLAP_B_F): 

1206 return tuple(MetaStep(sub.micro_index, MetaStepType.DATA_LOAD, sub.stage_index) 

1207 for sub in (step.sub_steps or ()) 

1208 if sub is not None and sub.type == MetaStepType.FWD) 

1209 return () 

1210 

1211 for rank, steps in schedule.items(): 

1212 out = [] 

1213 for step in steps: 

1214 out.extend(_loads_for(step)) 

1215 out.append(step) 

1216 schedule[rank] = out 

1217 return schedule 

1218 

1219 

1220def _column_scan_insert_comms(expanded, real_stage_num, insert_step_comms): 

1221 """Column-scan over an OVERLAP-expanded schedule to insert SEND/RECV. 

1222 

1223 Processes ``expanded`` one time slot at a time. Emits the original 

1224 overlap step into ``new_schedule`` only once (at the first-half 

1225 phantom). Delegates comm insertion to ``insert_step_comms`` for each 

1226 plain step or phantom's underlying sub-step. 

1227 

1228 Even ranks are processed before odd ranks at each time step to avoid 

1229 P2P deadlocks between adjacent ranks. 

1230 

1231 Args: 

1232 expanded: Result of :func:`_expand_overlap_slots`. 

1233 real_stage_num: Number of physical ranks. 

1234 insert_step_comms: Callable ``(step, rank, new_schedule) -> None`` 

1235 that inserts SEND/RECV for a single FWD/BWD step. 

1236 

1237 Returns: 

1238 ``{rank: [MetaStep, ...]}`` final schedule. 

1239 """ 

1240 max_length = max(len(order) for order in expanded.values()) 

1241 new_schedule = {rank: [] for rank in range(real_stage_num)} 

1242 

1243 for time_step in range(max_length): 

1244 current_items = {} 

1245 for rank in range(real_stage_num): 

1246 if time_step < len(expanded[rank]): 

1247 item = expanded[rank][time_step] 

1248 current_items[rank] = item 

1249 if item is None: 

1250 # Preserve bubble slots to keep per-rank time-step 

1251 # indexing aligned with the column scan. The runtime 

1252 # loop skips ``None`` entries, so this is execution- 

1253 # semantics-neutral. 

1254 new_schedule[rank].append(None) 

1255 continue 

1256 if isinstance(item, _OverlapPhantom): 

1257 # Emit the overlap step only once, at the first-half slot. 

1258 if item.is_first_half: 

1259 new_schedule[rank].append(item.obf_step) 

1260 else: 

1261 new_schedule[rank].append(item) 

1262 else: 

1263 current_items[rank] = None 

1264 

1265 _process_rank_items( 

1266 real_stage_num, current_items, insert_step_comms, new_schedule, 

1267 ) 

1268 

1269 return new_schedule 

1270 

1271 

1272_P2P_STEP_TYPES = frozenset({ 

1273 MetaStepType.FWD_SEND, MetaStepType.FWD_RECV, 

1274 MetaStepType.BWD_SEND, MetaStepType.BWD_RECV, 

1275}) 

1276 

1277 

1278def coalesce_p2p(exec_order): 

1279 """Coalesce maximal contiguous runs of >=2 P2P steps into BATCH_SEND_RECV. 

1280 

1281 A *run* is a maximal sequence of consecutive ``FWD_SEND`` / ``FWD_RECV`` / 

1282 ``BWD_SEND`` / ``BWD_RECV`` steps with no compute / overlap / bubble (``None``) 

1283 step between them — so no recv in the run is consumed before the batch is 

1284 issued, and all sends' data is already produced. Each such run is replaced 

1285 by a single :class:`MetaStep` of type ``BATCH_SEND_RECV`` carrying the run as 

1286 ``sub_steps`` (order preserved, so per-direction FIFO is kept); the runtime 

1287 groups those sub-steps by peer and issues one ``batch_isend_irecv`` per peer 

1288 (same-peer send+recv -> duplex). Runs of length 1 are left untouched (the 

1289 per-op batched path still batches them, so every transfer is still 

1290 batch-vs-batch). Pure ``exec_order -> exec_order`` transform. 

1291 

1292 Args: 

1293 exec_order: ``{rank: [MetaStep | None, ...]}``. 

1294 

1295 Returns: 

1296 A new ``{rank: [...]}`` with contiguous P2P runs coalesced. 

1297 """ 

1298 def _flush(run, new): 

1299 if len(run) >= 2: 

1300 new.append(MetaStep(None, MetaStepType.BATCH_SEND_RECV, None, sub_steps=tuple(run))) 

1301 else: 

1302 new.extend(run) 

1303 

1304 out = {} 

1305 for rank, order in exec_order.items(): 

1306 new = [] 

1307 run = [] 

1308 for step in order: 

1309 if step is not None and step.type in _P2P_STEP_TYPES: 

1310 run.append(step) 

1311 continue 

1312 _flush(run, new) 

1313 run = [] 

1314 new.append(step) 

1315 _flush(run, new) 

1316 out[rank] = new 

1317 return out 

1318 

1319 

1320_RECV_STEP_TYPES = frozenset({MetaStepType.FWD_RECV, MetaStepType.BWD_RECV}) 

1321 

1322 

1323def attach_fwd_boundary_p2p(exec_order): 

1324 """Hang each overlap gap's boundary-safe P2P on the OVERLAP_B_F step. 

1325 

1326 For every ``OVERLAP_B_F`` step, the contiguous P2P run right after it is 

1327 split by data readiness at the overlap's fwd/bwd boundary (forward is the 

1328 short side; backward, ~2x FLOPs, is the long pole): 

1329 

1330 * the forward's own ``FWD_SEND`` — its payload exists the moment the 

1331 forward sub-step finishes, no need to wait out the backward; 

1332 * every ``FWD_RECV`` / ``BWD_RECV`` — no data dependency at all; 

1333 

1334 are removed from the gap and attached to the OVERLAP step as 

1335 ``boundary_p2p`` (order: ``F_SEND`` first, then the recvs in original 

1336 order), to be issued by :meth:`PipelineScheduleRuntime.exec_boundary_p2p` 

1337 at the boundary, while the backward is still running. ``BWD_SEND`` (its 

1338 grad is produced by that backward) and any send not produced by this 

1339 overlap's forward stay in the gap. 

1340 

1341 Pairing shape (the reason this composition is safe where naive 

1342 hoist+coalesce hung): with every op issued as a per-op solo batch, each 

1343 pair's per-pair batch sequence per slot is ``[F_SEND, B_RECV]`` on the 

1344 prev end and ``[F_RECV, B_SEND]`` on the next end — complementary at every 

1345 position and equal in count, so it matches under both per-direction FIFO 

1346 and per-pair shape-mirroring semantics. Per-direction FIFO data order is 

1347 preserved (each direction's ops keep their relative order; they all shift 

1348 by the same amount). Pure ``exec_order -> exec_order`` transform. 

1349 

1350 Args: 

1351 exec_order: ``{rank: [MetaStep | None, ...]}``. 

1352 

1353 Returns: 

1354 A new ``{rank: [...]}`` with boundary P2P attached to OVERLAP steps. 

1355 """ 

1356 out = {} 

1357 for rank, order in exec_order.items(): 

1358 new = [] 

1359 i = 0 

1360 while i < len(order): 

1361 step = order[i] 

1362 if (step is None or step.type != MetaStepType.OVERLAP_B_F 

1363 or not step.sub_steps): 

1364 new.append(step) 

1365 i += 1 

1366 continue 

1367 run, j = _p2p_run_after(order, i + 1) 

1368 boundary, leftover = _split_boundary_run(step, run) 

1369 if not boundary: 

1370 new.append(step) 

1371 i += 1 

1372 continue 

1373 new.append(MetaStep(step.micro_index, step.type, step.stage_index, 

1374 sub_steps=step.sub_steps, boundary_p2p=boundary)) 

1375 new.extend(leftover) 

1376 i = j 

1377 out[rank] = new 

1378 return out 

1379 

1380 

1381def _p2p_run_after(order, start): 

1382 """Collect the contiguous P2P run starting at ``start``. 

1383 

1384 Returns ``(run, end)`` where ``end`` is the index of the first step past 

1385 the run (a compute step, ``None`` bubble, or end of order). 

1386 """ 

1387 run = [] 

1388 j = start 

1389 while j < len(order) and order[j] is not None and order[j].type in _P2P_STEP_TYPES: 

1390 run.append(order[j]) 

1391 j += 1 

1392 return run, j 

1393 

1394 

1395def _split_boundary_run(step, run): 

1396 """Split an overlap's trailing P2P run by fwd/bwd-boundary data readiness. 

1397 

1398 Returns ``(boundary, leftover)``: ``boundary`` holds the overlap's own 

1399 forward ``FWD_SEND`` (payload ready at the boundary) first, then every 

1400 recv (no data dependency), keeping original order; ``leftover`` keeps the 

1401 sends produced by the still-running backward, in place. 

1402 """ 

1403 fwd_sub = next((s for s in step.sub_steps 

1404 if s.type == MetaStepType.FWD), None) 

1405 

1406 def _is_own_fwd_send(s): 

1407 return (fwd_sub is not None 

1408 and s.type == MetaStepType.FWD_SEND 

1409 and s.stage_index == fwd_sub.stage_index 

1410 and s.micro_index == fwd_sub.micro_index) 

1411 

1412 boundary = ([s for s in run if _is_own_fwd_send(s)] 

1413 + [s for s in run if s.type in _RECV_STEP_TYPES]) 

1414 taken = {id(s) for s in boundary} 

1415 leftover = [s for s in run if id(s) not in taken] 

1416 return tuple(boundary), leftover 

1417 

1418 

1419def split_overlap_dxdw(exec_order: dict) -> dict: 

1420 """Split each OVERLAP_B_F backward into dx (in the pair) + dw (after the gap). 

1421 

1422 Rewrites ``(BWD, FWD)`` sub_steps to ``(BWD_INPUT, FWD)`` and inserts the 

1423 matching ``BWD_WEIGHT`` after the contiguous P2P run that follows the 

1424 overlap. The overlap then joins at ``max(dx, fwd)`` instead of 

1425 ``max(dx + dw, fwd)``, so the gap's ``BWD_SEND`` (dx already wrote its 

1426 grad to ``bwd_cache``) and the next slot's recvs are issued a dw earlier; 

1427 under ``overlap_p2p`` they are async and dw computes while they fly. 

1428 

1429 Comm placement is untouched: the pass runs after ``add_send_recv`` and 

1430 only moves local compute, so the cross-rank matching order is identical, 

1431 and the P2P run stays contiguous (dw lands after it, not inside) so 

1432 ``coalesce_p2p`` / ``attach_fwd_boundary_p2p`` see the same gap shape. 

1433 

1434 First-stage (``stage_index == 0``) backwards stay unified: their dx is a 

1435 no-op (no input grad to compute or send), so splitting would only move 

1436 the whole backward out of the overlap and lose its fwd overlap. 

1437 

1438 Args: 

1439 exec_order: ``{rank: [MetaStep | None, ...]}``. 

1440 

1441 Returns: 

1442 A new ``{rank: [...]}`` with overlap backwards split into dx/dw. 

1443 """ 

1444 out = {} 

1445 for rank, order in exec_order.items(): 

1446 new = [] 

1447 i = 0 

1448 n = len(order) 

1449 while i < n: 

1450 step = order[i] 

1451 i += 1 

1452 if (step is None or step.type != MetaStepType.OVERLAP_B_F 

1453 or not step.sub_steps): 

1454 new.append(step) 

1455 continue 

1456 bwd_sub, fwd_sub = step.sub_steps 

1457 if bwd_sub.type != MetaStepType.BWD or bwd_sub.stage_index == 0: 

1458 new.append(step) 

1459 continue 

1460 dx = MetaStep(bwd_sub.micro_index, MetaStepType.BWD_INPUT, bwd_sub.stage_index) 

1461 new.append(MetaStep(step.micro_index, step.type, step.stage_index, 

1462 sub_steps=(dx, fwd_sub))) 

1463 run, i = _p2p_run_after(order, i) 

1464 new.extend(run) 

1465 new.append(MetaStep(bwd_sub.micro_index, MetaStepType.BWD_WEIGHT, 

1466 bwd_sub.stage_index)) 

1467 out[rank] = new 

1468 return out 

1469 

1470 

1471def add_send_recv(scheduler, stage_num, real_stage_num, style='loop'): 

1472 """Insert P2P send/recv operations into a per-rank compute schedule. 

1473 

1474 For each FWD or BWD step that requires cross-rank communication, a 

1475 ``FWD_SEND`` / ``BWD_SEND`` is appended to the sender's schedule and a 

1476 ``FWD_RECV`` / ``BWD_RECV`` is appended to the receiver's schedule. 

1477 

1478 ``OVERLAP_F_B`` / ``OVERLAP_B_F`` composite steps are expanded into 

1479 **two** virtual time slots during the column scan so that the RECV 

1480 triggered by the **second** sub-step lands in the receiver's schedule 

1481 one slot later — matching the fact that the sender can only finish 

1482 emitting the second sub-step's output after the first completes. 

1483 

1484 Even ranks are processed before odd ranks at each time step to avoid 

1485 P2P deadlocks between adjacent ranks. 

1486 

1487 The resulting per-gap op order (steady state: 

1488 ``[B_RECV, B_SEND, F_RECV, F_SEND]``) is LOAD-BEARING, not cosmetic. 

1489 Each adjacent rank pair shares one comm (HCCL split-by-group) on which 

1490 plain send/recv execute in queue order, and this layout makes one end of 

1491 every pair recv-first while the other is send-first, so the two queue 

1492 heads always match (recv<->send), then the tails match (send<->recv). 

1493 Any later pass that reorders P2P ops relative to EACH OTHER breaks this: 

1494 a (since removed) hoist variant that moved recvs across sends made both 

1495 ends recv-first and deadlocked on hardware (2026-06). 

1496 ``attach_fwd_boundary_p2p`` (the ``"boundary"`` transport) is safe: it keeps 

1497 every per-direction FIFO and runs on the batch transport with per-op solo 

1498 batches, whose per-pair sequences stay complementary. 

1499 

1500 Args: 

1501 scheduler: ``{rank: [MetaStep | None, ...]}`` — compute schedule 

1502 with ``None`` for bubble slots. 

1503 stage_num: Total number of virtual pipeline stages. 

1504 real_stage_num: Number of physical ranks. 

1505 style: Topology mapping — ``'loop'`` or ``'v'``. 

1506 

1507 Returns: 

1508 ``{rank: [MetaStep, ...]}`` — schedule with communication ops inserted. 

1509 """ 

1510 

1511 def stage_to_rank(stage_index: int) -> int: 

1512 """Map a virtual stage index to its physical rank.""" 

1513 if style == 'loop': 

1514 return stage_index % real_stage_num 

1515 if style == 'v': 

1516 if stage_index < real_stage_num: 

1517 return stage_index 

1518 return stage_num - 1 - stage_index 

1519 raise ValueError(f"Argument 'style' must be 'loop' or 'v', but got {style!r}.") 

1520 

1521 def _fwd_peer(stage_index: int): 

1522 """Return the rank that receives this stage's forward output, or None.""" 

1523 if stage_index >= stage_num - 1: 

1524 return None 

1525 peer = stage_to_rank(stage_index + 1) 

1526 return peer if peer != stage_to_rank(stage_index) else None 

1527 

1528 def _bwd_peer(stage_index: int): 

1529 """Return the rank that receives this stage's backward gradient, or None.""" 

1530 if stage_index <= 0: 

1531 return None 

1532 peer = stage_to_rank(stage_index - 1) 

1533 return peer if peer != stage_to_rank(stage_index) else None 

1534 

1535 def _insert_comms_for_step(step, rank, new_schedule): 

1536 """Insert send/recv for a single FWD, BWD, or composite OVERLAP step. 

1537 

1538 Mirrors ``Schedule1F1B``: every forward that crosses a rank boundary 

1539 gets a ``DATA_SEND`` / ``DATA_RECV`` pair immediately followed by 

1540 ``FWD_SEND`` / ``FWD_RECV``. DATA_SEND/RECV are no-ops when 

1541 ``run_with_dataiterator`` isn't active (the handler short-circuits 

1542 on ``self.data_iterator is None``), so emitting them unconditionally 

1543 keeps Interleaved 1F1B correct under ``data.load: single`` without 

1544 penalising the legacy preload path. 

1545 """ 

1546 if step is None: 

1547 return 

1548 

1549 if step.type == MetaStepType.FWD: 

1550 peer = _fwd_peer(step.stage_index) 

1551 if peer is not None: 

1552 new_schedule[rank].append( 

1553 MetaStep(step.micro_index, MetaStepType.DATA_SEND, step.stage_index)) 

1554 new_schedule[rank].append( 

1555 MetaStep(step.micro_index, MetaStepType.FWD_SEND, step.stage_index)) 

1556 new_schedule[peer].append( 

1557 MetaStep(step.micro_index, MetaStepType.DATA_RECV, step.stage_index + 1)) 

1558 new_schedule[peer].append( 

1559 MetaStep(step.micro_index, MetaStepType.FWD_RECV, step.stage_index + 1)) 

1560 

1561 elif step.type == MetaStepType.BWD: 

1562 peer = _bwd_peer(step.stage_index) 

1563 if peer is not None: 

1564 new_schedule[rank].append( 

1565 MetaStep(step.micro_index, MetaStepType.BWD_SEND, step.stage_index)) 

1566 new_schedule[peer].append( 

1567 MetaStep(step.micro_index, MetaStepType.BWD_RECV, step.stage_index - 1)) 

1568 

1569 elif step.type in (MetaStepType.OVERLAP_F_B, MetaStepType.OVERLAP_B_F) and step.sub_steps: 

1570 for sub in step.sub_steps: 

1571 _insert_comms_for_step(sub, rank, new_schedule) 

1572 

1573 # --- Main logic: expand OVERLAP steps into 2 virtual slots, then scan --- 

1574 expanded = _expand_overlap_slots(scheduler, real_stage_num) 

1575 return _insert_dataload_before_fwd( 

1576 _column_scan_insert_comms(expanded, real_stage_num, _insert_comms_for_step)) 

1577 

1578 

1579_ALIGN_PAD = object() 

1580"""Sentinel marking a forced 1F1B-boundary bubble produced during alignment.""" 

1581 

1582 

1583def _step_dep_ready(step, rank, t, done, stage_num, stage_to_rank): 

1584 """Cross-rank data dependency check used by the alignment simulator. 

1585 

1586 A FWD step at stage ``s`` depends on FWD at stage ``s-1`` (on a 

1587 different rank); BWD at stage ``s`` depends on BWD at stage ``s+1``. 

1588 Steps at boundaries or whose producer lives on the same rank are 

1589 always ready. 

1590 """ 

1591 si, mi = step.stage_index, step.micro_index 

1592 if step.type == MetaStepType.FWD: 

1593 if si == 0 or stage_to_rank(si - 1) == rank: 

1594 return True 

1595 key = (MetaStepType.FWD, si - 1, mi) 

1596 return key in done and done[key] < t 

1597 if step.type == MetaStepType.BWD: 

1598 if si == stage_num - 1 or stage_to_rank(si + 1) == rank: 

1599 return True 

1600 key = (MetaStepType.BWD, si + 1, mi) 

1601 return key in done and done[key] < t 

1602 return True 

1603 

1604 

1605def _simulate_aligned_schedule(padded, stage_num, real_stage_num, stage_to_rank): 

1606 """Simulate execution time-step by time-step, inserting bubbles where 

1607 a step is not yet ready (cross-rank dep) or where the cooldown 

1608 rhythm requires it. 

1609 

1610 Args: 

1611 padded: ``{rank: [step | _ALIGN_PAD | None, ...]}`` after 

1612 1F1B-boundary padding. 

1613 stage_num: Total number of virtual pipeline stages. 

1614 real_stage_num: Number of physical ranks. 

1615 stage_to_rank: Topology mapping from stage to rank. 

1616 

1617 Returns: 

1618 ``{rank: [step | None, ...]}`` ready for the column-scan SEND/RECV 

1619 insertion phase. 

1620 """ 

1621 remaining_fwd = { 

1622 rank: sum( 

1623 1 for s in padded[rank] 

1624 if s is not _ALIGN_PAD and s is not None and s.type == MetaStepType.FWD 

1625 ) 

1626 for rank in range(real_stage_num) 

1627 } 

1628 cursors = {r: 0 for r in range(real_stage_num)} 

1629 aligned = {r: [] for r in range(real_stage_num)} 

1630 done = {} 

1631 last_was_cooldown_bwd = {r: False for r in range(real_stage_num)} 

1632 max_t = sum(len(v) for v in padded.values()) + real_stage_num * 20 

1633 

1634 def _emit_bubble(rank): 

1635 aligned[rank].append(None) 

1636 last_was_cooldown_bwd[rank] = False 

1637 

1638 def _emit_step(rank, step, t, in_cooldown): 

1639 aligned[rank].append(step) 

1640 done[(step.type, step.stage_index, step.micro_index)] = t 

1641 cursors[rank] += 1 

1642 if step.type == MetaStepType.FWD: 

1643 remaining_fwd[rank] -= 1 

1644 last_was_cooldown_bwd[rank] = in_cooldown and step.type == MetaStepType.BWD 

1645 

1646 def _step_rank_at(t, rank): 

1647 if cursors[rank] >= len(padded[rank]): 

1648 return 

1649 item = padded[rank][cursors[rank]] 

1650 if item is _ALIGN_PAD: 

1651 _emit_bubble(rank) 

1652 cursors[rank] += 1 

1653 return 

1654 in_cooldown = remaining_fwd[rank] == 0 

1655 # Cooldown rhythm: alternate None / BWD in pure-BWD phase. 

1656 cooldown_skip = ( 

1657 in_cooldown 

1658 and item.type == MetaStepType.BWD 

1659 and last_was_cooldown_bwd[rank] 

1660 ) 

1661 if cooldown_skip: 

1662 _emit_bubble(rank) 

1663 return 

1664 if not _step_dep_ready(item, rank, t, done, stage_num, stage_to_rank): 

1665 _emit_bubble(rank) 

1666 return 

1667 _emit_step(rank, item, t, in_cooldown) 

1668 

1669 for t in range(max_t): 

1670 if all(cursors[r] >= len(padded[r]) for r in range(real_stage_num)): 

1671 break 

1672 for rank in range(real_stage_num): 

1673 _step_rank_at(t, rank) 

1674 return aligned 

1675 

1676 

1677def auto_align_and_add_send_recv(scheduler, stage_num, real_stage_num, style='loop'): 

1678 """Auto-insert bubble alignment and P2P send/recv into a pure-compute schedule. 

1679 

1680 Unlike :func:`add_send_recv` which requires the caller to pre-insert 

1681 ``None`` bubble slots for time-step alignment, this function accepts a 

1682 **pure compute order** (``FWD`` / ``BWD`` only, no ``None`` needed) and 

1683 automatically determines bubble placement via execution simulation. 

1684 

1685 Three constraints are enforced: 

1686 

1687 1. **Data dependency** — a ``FWD(stage_k)`` cannot execute until 

1688 ``FWD(stage_{k-1})`` on its source rank has completed (and 

1689 analogously for ``BWD``). 

1690 2. **1F1B transition alignment** — ``real_stage_num - 1 - rank`` padding 

1691 slots are inserted at the warmup → 1F1B boundary (detected as the 

1692 first ``FWD`` immediately followed by a ``BWD`` in the compute order) 

1693 so that all ranks enter the 1F1B steady state in lockstep. 

1694 3. **Cooldown rhythm** — once a rank exhausts its ``FWD`` ops and enters 

1695 pure-``BWD`` cooldown, consecutive ``BWD`` steps are separated by a 

1696 ``None`` slot, maintaining the column-phase-sync property (no rank 

1697 does ``BWD`` while another does ``FWD`` at the same time step). 

1698 

1699 After alignment, a column-scan pass inserts ``FWD_SEND`` / ``FWD_RECV`` 

1700 and ``BWD_SEND`` / ``BWD_RECV`` with the same prefetch semantics as 

1701 :func:`add_send_recv`. 

1702 

1703 Args: 

1704 scheduler: ``{rank: [MetaStep, ...]}`` — pure compute schedule. 

1705 ``None`` entries are silently stripped before processing. 

1706 stage_num: Total number of virtual pipeline stages. 

1707 real_stage_num: Number of physical ranks. 

1708 style: Topology mapping — ``'loop'`` or ``'v'``. 

1709 

1710 Returns: 

1711 ``{rank: [MetaStep, ...]}`` — fully aligned schedule with bubbles 

1712 and communication ops inserted. 

1713 """ 

1714 

1715 # ---- topology helpers (shared with column-scan phase) ---- 

1716 

1717 def stage_to_rank(stage_index: int) -> int: 

1718 if style == 'loop': 

1719 return stage_index % real_stage_num 

1720 if style == 'v': 

1721 if stage_index < real_stage_num: 

1722 return stage_index 

1723 return stage_num - 1 - stage_index 

1724 raise ValueError(f"Argument 'style' must be 'loop' or 'v', but got {style!r}.") 

1725 

1726 def _fwd_peer(stage_index: int): 

1727 if stage_index >= stage_num - 1: 

1728 return None 

1729 peer = stage_to_rank(stage_index + 1) 

1730 return peer if peer != stage_to_rank(stage_index) else None 

1731 

1732 def _bwd_peer(stage_index: int): 

1733 if stage_index <= 0: 

1734 return None 

1735 peer = stage_to_rank(stage_index - 1) 

1736 return peer if peer != stage_to_rank(stage_index) else None 

1737 

1738 # ---- Phase 1: strip None, detect 1F1B boundary, insert transition padding ---- 

1739 

1740 def _find_1f1b_boundary(order): 

1741 """Index of the first FWD followed by BWD; ``len(order)`` if absent.""" 

1742 for i in range(len(order) - 1): 

1743 if (order[i].type == MetaStepType.FWD 

1744 and order[i + 1].type == MetaStepType.BWD): 

1745 return i 

1746 return len(order) 

1747 

1748 padded = {} 

1749 for rank in range(real_stage_num): 

1750 order = [s for s in scheduler[rank] if s is not None] 

1751 boundary = _find_1f1b_boundary(order) 

1752 pad_count = real_stage_num - 1 - rank 

1753 padded[rank] = order[:boundary] + [_ALIGN_PAD] * pad_count + order[boundary:] 

1754 

1755 # ---- Phase 2: simulate execution with data deps + cooldown rhythm ---- 

1756 

1757 aligned = _simulate_aligned_schedule(padded, stage_num, real_stage_num, stage_to_rank) 

1758 

1759 # ---- Phase 3: column-scan SEND/RECV insertion (same as add_send_recv) ---- 

1760 

1761 def _insert_comms_for_step(step, rank, new_schedule): 

1762 # The DATA pair precedes the FWD pair so ``data.load: single`` ships raw 

1763 # inputs stage-to-stage; it no-ops without run_with_dataiterator. 

1764 if step is None: 

1765 return 

1766 if step.type == MetaStepType.FWD: 

1767 peer = _fwd_peer(step.stage_index) 

1768 if peer is not None: 

1769 new_schedule[rank].append( 

1770 MetaStep(step.micro_index, MetaStepType.DATA_SEND, step.stage_index)) 

1771 new_schedule[rank].append( 

1772 MetaStep(step.micro_index, MetaStepType.FWD_SEND, step.stage_index)) 

1773 new_schedule[peer].append( 

1774 MetaStep(step.micro_index, MetaStepType.DATA_RECV, step.stage_index + 1)) 

1775 new_schedule[peer].append( 

1776 MetaStep(step.micro_index, MetaStepType.FWD_RECV, step.stage_index + 1)) 

1777 elif step.type == MetaStepType.BWD: 

1778 peer = _bwd_peer(step.stage_index) 

1779 if peer is not None: 

1780 new_schedule[rank].append( 

1781 MetaStep(step.micro_index, MetaStepType.BWD_SEND, step.stage_index)) 

1782 new_schedule[peer].append( 

1783 MetaStep(step.micro_index, MetaStepType.BWD_RECV, step.stage_index - 1)) 

1784 elif step.type in (MetaStepType.OVERLAP_F_B, MetaStepType.OVERLAP_B_F) and step.sub_steps: 

1785 for sub in step.sub_steps: 

1786 _insert_comms_for_step(sub, rank, new_schedule) 

1787 

1788 # Expand OVERLAP steps into 2 virtual slots before the column scan so 

1789 # the RECV triggered by an overlap's second sub-step lands one slot 

1790 # later on the receiver — matching the fact that the sender can only 

1791 # finish emitting the second sub-step after the first completes. 

1792 expanded = _expand_overlap_slots(aligned, real_stage_num) 

1793 return _insert_dataload_before_fwd( 

1794 _column_scan_insert_comms(expanded, real_stage_num, _insert_comms_for_step)) 

1795 

1796 

1797class ScheduleGPipe(PipelineScheduleRuntime): 

1798 """ 

1799 The Gpipe schedule. 

1800 It first executes all forward micro batches and then execute all backward micro batches. 

1801 """ 

1802 def __init__(self, 

1803 stages, 

1804 micro_batch_num, 

1805 args_batch_dim=None, 

1806 kwargs_batch_dim=None, 

1807 output_concat_dim=None, 

1808 swap=False): 

1809 super().__init__(stages, 

1810 micro_batch_num, 

1811 args_batch_dim=args_batch_dim, 

1812 kwargs_batch_dim=kwargs_batch_dim, 

1813 output_concat_dim=output_concat_dim, 

1814 swap=swap) 

1815 self.build_exec_order() 

1816 

1817 def _build_stage_to_rank_index(self) -> None: 

1818 self._stage_to_rank_index = generate_stage_to_rank_mapping( 

1819 self.real_stage_num, self._stage_num, style='loop' 

1820 ) 

1821 

1822 def construct_exec_order(self): 

1823 """construct_exec_order of Gpipe.""" 

1824 for stage_index in range(self.real_stage_num): 

1825 order_list = [] 

1826 for mb_index in range(self.micro_batch_num): 

1827 order_list.append(MetaStep(mb_index, MetaStepType.DATA_LOAD, stage_index)) 

1828 if stage_index != 0: 

1829 order_list.append(MetaStep(mb_index, MetaStepType.DATA_RECV, stage_index)) 

1830 order_list.append(MetaStep(mb_index, MetaStepType.FWD_RECV, stage_index)) 

1831 order_list.append(MetaStep(mb_index, MetaStepType.FWD, stage_index)) 

1832 if stage_index != self.real_stage_num - 1: 

1833 order_list.append(MetaStep(mb_index, MetaStepType.DATA_SEND, stage_index)) 

1834 order_list.append(MetaStep(mb_index, MetaStepType.FWD_SEND, stage_index)) 

1835 for mb_index in range(self.micro_batch_num): 

1836 if stage_index != self.real_stage_num - 1: 

1837 order_list.append(MetaStep(mb_index, MetaStepType.BWD_RECV, stage_index)) 

1838 order_list.append(MetaStep(mb_index, MetaStepType.BWD, stage_index)) 

1839 if stage_index != 0: 

1840 order_list.append(MetaStep(mb_index, MetaStepType.BWD_SEND, stage_index)) 

1841 self.exec_order[stage_index] = order_list 

1842 

1843 

1844class Schedule1F1B(PipelineScheduleRuntime): 

1845 """ 

1846 The 1F1B schedule. 

1847 It will perform one forward and one backward on the micro batches in steady state. 

1848 """ 

1849 def __init__(self, 

1850 stages, 

1851 micro_batch_num, 

1852 args_batch_dim=None, 

1853 kwargs_batch_dim=None, 

1854 output_concat_dim=None, 

1855 swap=False): 

1856 super().__init__(stages, 

1857 micro_batch_num, 

1858 args_batch_dim=args_batch_dim, 

1859 kwargs_batch_dim=kwargs_batch_dim, 

1860 output_concat_dim=output_concat_dim, 

1861 swap=swap) 

1862 self.build_exec_order() 

1863 

1864 def _build_stage_to_rank_index(self) -> None: 

1865 self._stage_to_rank_index = generate_stage_to_rank_mapping( 

1866 self.real_stage_num, self._stage_num, style='loop' 

1867 ) 

1868 

1869 def construct_exec_order(self): 

1870 """construct_exec_order of 1F1B.""" 

1871 for stage_index in range(self.real_stage_num): 

1872 order_list = [] 

1873 fwd_index = 0 

1874 bwd_index = 0 

1875 # warmup phase 

1876 warmup_micro_batches = min(self.real_stage_num - stage_index, self.micro_batch_num) 

1877 for _ in range(warmup_micro_batches): 

1878 order_list.append(MetaStep(fwd_index, MetaStepType.DATA_LOAD, stage_index)) 

1879 if stage_index != 0: 

1880 order_list.append(MetaStep(fwd_index, MetaStepType.DATA_RECV, stage_index)) 

1881 order_list.append(MetaStep(fwd_index, MetaStepType.FWD_RECV, stage_index)) 

1882 if stage_index % 2 == 0: 

1883 order_list.append(MetaStep(fwd_index, MetaStepType.FWD, stage_index)) 

1884 if fwd_index != warmup_micro_batches - 1: 

1885 order_list.append(MetaStep(fwd_index, MetaStepType.DATA_SEND, stage_index)) 

1886 order_list.append(MetaStep(fwd_index, MetaStepType.FWD_SEND, stage_index)) 

1887 else: 

1888 if fwd_index > 0: 

1889 order_list.append(MetaStep(fwd_index - 1, MetaStepType.DATA_SEND, stage_index)) 

1890 order_list.append(MetaStep(fwd_index - 1, MetaStepType.FWD_SEND, stage_index)) 

1891 order_list.append(MetaStep(fwd_index, MetaStepType.FWD, stage_index)) 

1892 fwd_index += 1 

1893 

1894 # if warmup phase cannot filled up, then we need to execute fwd send in advance 

1895 if self.real_stage_num - stage_index > self.micro_batch_num: 

1896 order_list.append(MetaStep(fwd_index - 1, MetaStepType.DATA_SEND, stage_index)) 

1897 order_list.append(MetaStep(fwd_index - 1, MetaStepType.FWD_SEND, stage_index)) 

1898 fwd_index += 1 

1899 # steady phase 

1900 steady_micro_batches = self.micro_batch_num - warmup_micro_batches 

1901 for _ in range(steady_micro_batches): 

1902 if stage_index != self.real_stage_num - 1: 

1903 order_list.append(MetaStep(bwd_index, MetaStepType.BWD_RECV, stage_index)) 

1904 order_list.append(MetaStep(fwd_index - 1, MetaStepType.DATA_SEND, stage_index)) 

1905 order_list.append(MetaStep(fwd_index - 1, MetaStepType.FWD_SEND, stage_index)) 

1906 order_list.append(MetaStep(bwd_index, MetaStepType.BWD, stage_index)) 

1907 

1908 order_list.append(MetaStep(fwd_index, MetaStepType.DATA_LOAD, stage_index)) 

1909 if stage_index != 0: 

1910 order_list.append(MetaStep(bwd_index, MetaStepType.BWD_SEND, stage_index)) 

1911 order_list.append(MetaStep(fwd_index, MetaStepType.DATA_RECV, stage_index)) 

1912 order_list.append(MetaStep(fwd_index, MetaStepType.FWD_RECV, stage_index)) 

1913 order_list.append(MetaStep(fwd_index, MetaStepType.FWD, stage_index)) 

1914 fwd_index += 1 

1915 bwd_index += 1 

1916 

1917 # cooldown phase 

1918 cooldown_micro_batches = warmup_micro_batches 

1919 for _ in range(cooldown_micro_batches): 

1920 if stage_index != self.real_stage_num - 1: 

1921 order_list.append(MetaStep(bwd_index, MetaStepType.BWD_RECV, stage_index)) 

1922 if bwd_index == self.micro_batch_num - warmup_micro_batches and fwd_index <= self.micro_batch_num: 

1923 order_list.append(MetaStep(fwd_index - 1, MetaStepType.DATA_SEND, stage_index)) 

1924 order_list.append(MetaStep(fwd_index - 1, MetaStepType.FWD_SEND, stage_index)) 

1925 order_list.append(MetaStep(bwd_index, MetaStepType.BWD, stage_index)) 

1926 

1927 if stage_index != 0: 

1928 order_list.append(MetaStep(bwd_index, MetaStepType.BWD_SEND, stage_index)) 

1929 bwd_index += 1 

1930 self.exec_order[stage_index] = order_list 

1931 

1932 

1933class ScheduleInterleaved1F1B(PipelineScheduleRuntime): 

1934 """The Interleaved 1F1B schedule. 

1935 

1936 Supports multiple stages per rank. In steady state, performs one 

1937 forward followed by one backward on each micro-batch. Handles the 

1938 cases where ``micro_batch_num`` is less than, equal to, or greater 

1939 than the stage count, including non-evenly-divisible micro counts. 

1940 

1941 Two orthogonal overlap modes can be enabled via constructor flags: 

1942 

1943 * ``overlap_p2p=True``: defer P2P recv ``handle.wait()`` until the 

1944 consuming FWD/BWD step (or the OVERLAP_B_F callback when 

1945 ``overlap_b_f=True``), letting recv overlap with prior compute. 

1946 * ``overlap_b_f=True``: in the 1F1B steady state, pair consecutive 

1947 ``(B_i, F_{i+1})`` steps into ``OVERLAP_B_F`` composite steps so 

1948 a registered callback can drive comm/compute overlap (typically 

1949 via :class:`CommComputeOverlap` for MoE EP A2A). Users register 

1950 the callback through :meth:`register_custom_function`. 

1951 * ``enable_dxdw_split=True`` (requires ``overlap_b_f``): each 

1952 steady-state pair becomes ``(BWD_INPUT_i, F_{i+1})`` and the 

1953 ``BWD_WEIGHT_i`` runs as its own step after the pair's P2P gap 

1954 (see :func:`split_overlap_dxdw`), so the input-grad send is 

1955 issued once dx and the paired forward finish instead of waiting 

1956 out the full backward. 

1957 

1958 The two overlap flags are independent and can be combined. 

1959 

1960 ``less_memory=True`` selects the shallow-warmup variant: each stage's 

1961 warmup depth becomes ``(V-1)*R + (P-1-i)`` instead of the classic 

1962 ``(V-1)*R + 2*(P-1-i)``, so at most ``V*P - i`` micro-batch 

1963 activations are in flight per stage instead of ``2*P - 2*i - 1`` extra 

1964 on the early stages. At ``V == 1`` this reproduces the plain 1F1B 

1965 depth exactly. The steady-state 1F1B rhythm and the cooldown are 

1966 unchanged; only the warmup/cooldown lengths shift. 

1967 

1968 Example: 

1969 >>> # Plain interleaved 1F1B 

1970 >>> sched = ScheduleInterleaved1F1B(stages, 8) 

1971 >>> # With B/F overlap (dual-pipe-style comm/compute overlap) 

1972 >>> sched = ScheduleInterleaved1F1B(stages, 8, overlap_b_f=True) 

1973 >>> sched.register_custom_function(MetaStepType.OVERLAP_B_F, callback) 

1974 """ 

1975 

1976 # Class-level default so schedules built through the pure-construction 

1977 # path (``object.__new__`` in offline tests) keep the classic warmup. 

1978 _less_memory = False 

1979 

1980 def __init__(self, 

1981 stages, 

1982 micro_batch_num, 

1983 args_batch_dim=None, 

1984 kwargs_batch_dim=None, 

1985 output_concat_dim=None, 

1986 overlap_p2p=False, 

1987 overlap_b_f=False, 

1988 swap=False, 

1989 enable_dxdw_split=False, 

1990 p2p_transport="auto", 

1991 less_memory=False): 

1992 super().__init__(stages, 

1993 micro_batch_num, 

1994 args_batch_dim=args_batch_dim, 

1995 kwargs_batch_dim=kwargs_batch_dim, 

1996 output_concat_dim=output_concat_dim, 

1997 overlap_p2p=overlap_p2p, 

1998 swap=swap, 

1999 p2p_transport=p2p_transport) 

2000 # Selects plain F/B vs OVERLAP_B_F pairing in the steady state; must 

2001 # be set before ``construct_stage_exec_order`` below. 

2002 self._overlap_b_f = overlap_b_f 

2003 # Shallow-warmup variant; must be set before build_exec_order below. 

2004 self._less_memory = less_memory 

2005 # dx/dw split: ``construct_exec_order`` rewrites each steady-state 

2006 # OVERLAP_B_F pair to ``(BWD_INPUT, FWD)`` and re-emits the matching 

2007 # BWD_WEIGHT after the pair's P2P gap (``split_overlap_dxdw``), so the 

2008 # input-grad send leaves at ``max(dx, fwd)`` and dw overlaps with the 

2009 # in-flight P2P instead of delaying it. 

2010 self._enable_dxdw_split = enable_dxdw_split 

2011 if enable_dxdw_split and not overlap_b_f: 

2012 raise ValueError( 

2013 "enable_dxdw_split=True requires overlap_b_f=True; the split " 

2014 "is only applied to BWD sub-steps inside OVERLAP_B_F composite steps." 

2015 ) 

2016 self._init_round_layout() 

2017 self.build_exec_order() 

2018 

2019 def _init_round_layout(self): 

2020 """Compute per-round micro-batch counts used by stage-order emission. 

2021 

2022 Populates ``n_rounds``, ``n_microbatch_per_round`` and its prefix-sum 

2023 ``n_microbatch_per_round_accu`` from ``micro_batch_num``, 

2024 ``real_stage_num`` and ``n_local_stages``. Factored out of 

2025 ``__init__`` so the pure schedule-construction path (used by offline 

2026 unit tests) can be exercised without instantiating stages. 

2027 """ 

2028 self.n_rounds = max(1, self.micro_batch_num // self.real_stage_num) 

2029 if self.micro_batch_num < self.real_stage_num: 

2030 base = self.micro_batch_num - self.real_stage_num 

2031 remainder = 0 

2032 else: 

2033 n_extra_microbatch = self.micro_batch_num % self.real_stage_num 

2034 base = n_extra_microbatch // self.n_rounds 

2035 remainder = n_extra_microbatch % self.n_rounds 

2036 self.n_microbatch_per_round = \ 

2037 [self.real_stage_num + base + 1 if i < remainder else 

2038 self.real_stage_num + base for i in range(self.n_rounds)] 

2039 self.n_microbatch_per_round_accu = \ 

2040 [x * self.n_local_stages for x in itertools.accumulate(self.n_microbatch_per_round)] 

2041 self.n_microbatch_per_round_accu.insert(0, 0) 

2042 

2043 def construct_exec_order(self): 

2044 # One line for the whole warmup vector, pp-rank-0 hosts only 

2045 # (per-stage lines are too chatty at high rank counts). 

2046 own = getattr(self, "stages", None) 

2047 if not own or getattr(own[0], "stage_index", 0) == 0: 

2048 logger.info("interleaved warmup: warmup_ops=%s less_memory=%s", 

2049 [self.warmup_ops(s) for s in range(self.real_stage_num)], 

2050 self._less_memory) 

2051 for stage_index in range(self.real_stage_num): 

2052 self.exec_order[stage_index] = self.construct_stage_exec_order(stage_index) 

2053 self.exec_order = add_send_recv(self.exec_order, self._stage_num, self.real_stage_num, style='loop') 

2054 if self.enable_dxdw_split: 

2055 self.exec_order = split_overlap_dxdw(self.exec_order) 

2056 

2057 def _build_stage_to_rank_index(self) -> None: 

2058 self._stage_to_rank_index = generate_stage_to_rank_mapping( 

2059 self.real_stage_num, self._stage_num, style='loop' 

2060 ) 

2061 

2062 def warmup_ops(self, stage_index): 

2063 """warmup phase.""" 

2064 warmup_ops_last_stage = (self.n_local_stages - 1) * self.n_microbatch_per_round[0] 

2065 depth = self.real_stage_num - 1 - stage_index 

2066 # less_memory: plain-1F1B stagger (depth) instead of the classic 

2067 # doubled stagger (2*depth) — fewer activations in flight per stage. 

2068 warmup_ops = warmup_ops_last_stage + (depth if self._less_memory else 2 * depth) 

2069 return min(warmup_ops, self.micro_batch_num * self.n_local_stages) 

2070 

2071 def forward_stage_index(self, op_index, stage_index): 

2072 """obtain forward stage_index based on op_index.""" 

2073 accu_index = bisect.bisect_right(self.n_microbatch_per_round_accu, op_index) - 1 

2074 local_index = (op_index - self.n_microbatch_per_round_accu[accu_index]) // \ 

2075 self.n_microbatch_per_round[accu_index] 

2076 return (local_index * self.real_stage_num) + stage_index 

2077 

2078 def backward_stage_index(self, op_index, stage_index): 

2079 """obtain backward stage_index based on op_index.""" 

2080 accu_index = bisect.bisect_right(self.n_microbatch_per_round_accu, op_index) - 1 

2081 local_index = (op_index - self.n_microbatch_per_round_accu[accu_index]) // \ 

2082 self.n_microbatch_per_round[accu_index] 

2083 local_index = self.n_local_stages - 1 - local_index 

2084 return (local_index * self.real_stage_num) + stage_index 

2085 

2086 def _short_micro(self) -> bool: 

2087 """True when ``micro_batch_num < real_stage_num`` (extra-bubble regime).""" 

2088 return self.micro_batch_num < self.real_stage_num 

2089 

2090 def _trailing_bubble(self) -> int: 

2091 """Bubble count appended after a BWD with ``micro == micro_batch_num - 1`` 

2092 in the short-micro regime. 

2093 """ 

2094 return self.real_stage_num - self.micro_batch_num 

2095 

2096 def _emit_warmup_ops(self, stage_index, warmup_ops, fwd_stage_micro_index): 

2097 """Emit pure-FWD warmup ops with optional short-micro bubble padding.""" 

2098 ops = [] 

2099 short = self._short_micro() 

2100 last_micro = self.micro_batch_num - 1 

2101 last_stage = self.real_stage_num - 1 

2102 bubble = self._trailing_bubble() 

2103 for op_idx in range(warmup_ops): 

2104 fwd_stage_idx = self.forward_stage_index(op_idx, stage_index) 

2105 fwd_micro_idx = fwd_stage_micro_index[fwd_stage_idx] 

2106 # No DATA_LOAD slot here: it is spliced in after comm insertion, else this 

2107 # rank's extra columns desync the cross-rank column scan in add_send_recv. 

2108 ops.append(MetaStep(fwd_micro_idx, MetaStepType.FWD, fwd_stage_idx)) 

2109 need_pad = ( 

2110 short 

2111 and fwd_micro_idx == last_micro 

2112 and (op_idx != warmup_ops - 1 or stage_index == last_stage) 

2113 ) 

2114 if need_pad: 

2115 ops.extend([None] * bubble) 

2116 fwd_stage_micro_index[fwd_stage_idx] += 1 

2117 return ops 

2118 

2119 def _emit_cooldown_ops(self, stage_index, warmup_ops, fwd_bwd_ops, total_ops, 

2120 bwd_stage_micro_index): 

2121 """Emit pure-BWD cooldown ops (each preceded by a bubble) with 

2122 optional short-micro trailing padding. 

2123 """ 

2124 ops = [] 

2125 short = self._short_micro() 

2126 last_micro = self.micro_batch_num - 1 

2127 # Double the bubble at each chunk's last-micro BWD: one ``bubble`` covers 

2128 # the missing ``rs - micro`` micros, the second offsets the next chunk 

2129 # by 2 slots so the wrap-around grad (rank 0 stage ``rs`` -> rank 

2130 # last_stage stage ``rs - 1``) lands AFTER its producer in column-scan 

2131 # time. Matches the +2 cooldown-rhythm offset that non-short Interleaved 

2132 # 1F1B naturally has from extra 1F1B ops on rank last_stage. 

2133 bubble = 2 * self._trailing_bubble() 

2134 for op_idx in range(warmup_ops + fwd_bwd_ops, total_ops): 

2135 ops.append(None) 

2136 bwd_stage_idx = self.backward_stage_index(op_idx - warmup_ops, stage_index) 

2137 bwd_micro_idx = bwd_stage_micro_index[bwd_stage_idx] 

2138 ops.append(MetaStep(bwd_micro_idx, MetaStepType.BWD, bwd_stage_idx)) 

2139 if short and bwd_micro_idx == last_micro: 

2140 ops.extend([None] * bubble) 

2141 bwd_stage_micro_index[bwd_stage_idx] += 1 

2142 return ops 

2143 

2144 def _emit_1f1b_ops(self, stage_index, warmup_ops, fwd_bwd_ops, 

2145 fwd_stage_micro_index, bwd_stage_micro_index): 

2146 """Emit interleaved (FWD, BWD) pairs for the 1F1B steady-state phase.""" 

2147 ops = [] 

2148 short = self._short_micro() 

2149 last_micro = self.micro_batch_num - 1 

2150 last_stage = self.real_stage_num - 1 

2151 # Double the bubble at the 1F1B->cooldown chunk boundary on rank 

2152 # last_stage; see :meth:`_emit_cooldown_ops` for the alignment rationale. 

2153 bubble = 2 * self._trailing_bubble() 

2154 for op_idx in range(warmup_ops, warmup_ops + fwd_bwd_ops): 

2155 fwd_stage_idx = self.forward_stage_index(op_idx, stage_index) 

2156 fwd_micro_idx = fwd_stage_micro_index[fwd_stage_idx] 

2157 # DATA_LOAD spliced in after comm insertion — see _emit_warmup_ops. 

2158 ops.append(MetaStep(fwd_micro_idx, MetaStepType.FWD, fwd_stage_idx)) 

2159 fwd_stage_micro_index[fwd_stage_idx] += 1 

2160 bwd_stage_idx = self.backward_stage_index(op_idx - warmup_ops, stage_index) 

2161 bwd_micro_idx = bwd_stage_micro_index[bwd_stage_idx] 

2162 ops.append(MetaStep(bwd_micro_idx, MetaStepType.BWD, bwd_stage_idx)) 

2163 need_pad = ( 

2164 short 

2165 and bwd_micro_idx == last_micro 

2166 and stage_index == last_stage 

2167 ) 

2168 if need_pad: 

2169 ops.extend([None] * bubble) 

2170 bwd_stage_micro_index[bwd_stage_idx] += 1 

2171 return ops 

2172 

2173 @staticmethod 

2174 def _collect_fwd_bwd_steps(emit_fwd, emit_bwd, fwd_bwd_ops, warmup_ops): 

2175 """Walk the 1F1B range collecting parallel ``fwd_steps`` / ``bwd_steps``. 

2176 

2177 ``emit_fwd(op_idx)`` and ``emit_bwd(op_idx)`` build a single 

2178 :class:`MetaStep` and advance their respective per-stage micro 

2179 counters as a side effect. 

2180 """ 

2181 fwd_steps = [] 

2182 bwd_steps = [] 

2183 for op_idx in range(warmup_ops, warmup_ops + fwd_bwd_ops): 

2184 fwd_steps.append(emit_fwd(op_idx)) 

2185 bwd_steps.append(emit_bwd(op_idx)) 

2186 return fwd_steps, bwd_steps 

2187 

2188 @staticmethod 

2189 def _pair_into_overlap_b_f(fwd_steps, bwd_steps): 

2190 """Build ``F₁, [B_i, F_{i+1}], B_n`` ordering with OVERLAP_B_F pairs. 

2191 

2192 ``sub_steps`` carry the ``(bwd, fwd)`` tuple — callbacks access 

2193 them via ``step.sub_steps`` to recover per-direction stage / 

2194 micro info. 

2195 """ 

2196 ops = [] 

2197 if fwd_steps: 

2198 ops.append(fwd_steps[0]) # F₁ runs alone 

2199 for i in range(len(bwd_steps) - 1): 

2200 ops.append(MetaStep( 

2201 None, MetaStepType.OVERLAP_B_F, None, 

2202 sub_steps=(bwd_steps[i], fwd_steps[i + 1]), 

2203 )) 

2204 if bwd_steps: 

2205 ops.append(bwd_steps[-1]) # B_n runs alone 

2206 return ops 

2207 

2208 def _emit_1f1b_overlap_ops(self, stage_index, warmup_ops, fwd_bwd_ops, 

2209 fwd_stage_micro_index, bwd_stage_micro_index): 

2210 """Emit ``F₁, [B_i, F_{i+1}], B_n`` for the 1F1B phase under 

2211 ``overlap_b_f=True``. Each ``[B_i, F_{i+1}]`` becomes an 

2212 ``OVERLAP_B_F`` composite step; a registered callback drives the 

2213 actual concurrent execution. Short-micro extra-bubble padding 

2214 on the last rank is appended after ``B_n``. 

2215 """ 

2216 def emit_fwd(op_idx): 

2217 fwd_si = self.forward_stage_index(op_idx, stage_index) 

2218 fwd_mi = fwd_stage_micro_index[fwd_si] 

2219 fwd_stage_micro_index[fwd_si] += 1 

2220 return MetaStep(fwd_mi, MetaStepType.FWD, fwd_si) 

2221 

2222 def emit_bwd(op_idx): 

2223 bwd_si = self.backward_stage_index(op_idx - warmup_ops, stage_index) 

2224 bwd_mi = bwd_stage_micro_index[bwd_si] 

2225 bwd_stage_micro_index[bwd_si] += 1 

2226 return MetaStep(bwd_mi, MetaStepType.BWD, bwd_si) 

2227 

2228 fwd_steps, bwd_steps = self._collect_fwd_bwd_steps( 

2229 emit_fwd, emit_bwd, fwd_bwd_ops, warmup_ops, 

2230 ) 

2231 ops = self._pair_into_overlap_b_f(fwd_steps, bwd_steps) 

2232 

2233 last_stage = self.real_stage_num - 1 

2234 if self._short_micro() and stage_index == last_stage and bwd_steps: 

2235 if bwd_steps[-1].micro_index == self.micro_batch_num - 1: 

2236 # Double the bubble at the 1F1B->cooldown chunk boundary; 

2237 # see :meth:`_emit_cooldown_ops` for the alignment rationale. 

2238 ops.extend([None] * (2 * self._trailing_bubble())) 

2239 return ops 

2240 

2241 def construct_stage_exec_order(self, stage_index): 

2242 """Construct the execution order for ``stage_index``. 

2243 

2244 Builds: warmup → bubbles → 1F1B steady state → cooldown. The 

2245 1F1B segment switches between :meth:`_emit_1f1b_ops` (plain) and 

2246 :meth:`_emit_1f1b_overlap_ops` (OVERLAP_B_F pairing) based on 

2247 the ``overlap_b_f`` constructor flag. 

2248 """ 

2249 warmup_ops = self.warmup_ops(stage_index) 

2250 fwd_bwd_ops = self.n_local_stages * self.micro_batch_num - warmup_ops 

2251 total_ops = 2 * warmup_ops + fwd_bwd_ops 

2252 order_list = [None for _ in range(stage_index)] 

2253 fwd_stage_micro_index = defaultdict(int) 

2254 bwd_stage_micro_index = defaultdict(int) 

2255 order_list.extend(self._emit_warmup_ops(stage_index, warmup_ops, fwd_stage_micro_index)) 

2256 # One bubble per warmup op lost to the short-micro cap: the uncapped 

2257 # stagger is depth (less_memory) or 2*depth (classic) beyond V*M. 

2258 depth = self.real_stage_num - 1 - stage_index 

2259 bubbles_before_1f1b = max( 

2260 0, 

2261 (depth if self._less_memory else 2 * depth) - self.micro_batch_num, 

2262 ) 

2263 order_list.extend([None] * bubbles_before_1f1b) 

2264 order_list.extend([None] * (self.real_stage_num - 1 - stage_index)) 

2265 if self._overlap_b_f: 

2266 order_list.extend(self._emit_1f1b_overlap_ops( 

2267 stage_index, warmup_ops, fwd_bwd_ops, 

2268 fwd_stage_micro_index, bwd_stage_micro_index, 

2269 )) 

2270 else: 

2271 order_list.extend(self._emit_1f1b_ops( 

2272 stage_index, warmup_ops, fwd_bwd_ops, 

2273 fwd_stage_micro_index, bwd_stage_micro_index, 

2274 )) 

2275 order_list.extend(self._emit_cooldown_ops( 

2276 stage_index, warmup_ops, fwd_bwd_ops, total_ops, bwd_stage_micro_index, 

2277 )) 

2278 return order_list 

2279 

2280 

2281def detect_cycle_in_graph(ranks_map): 

2282 """ 

2283 Detects a cycle in the directed graph constructed from ranks_map. 

2284 

2285 Args: 

2286 ranks_map: A dictionary where keys are rank names and values are lists of nodes. 

2287 

2288 Returns: 

2289 tuple: (cycle_path, cycle_ranks) where cycle_path is a list of nodes forming the cycle and cycle_ranks 

2290 is a list of rank transitions corresponding to the cycle path. 

2291 """ 

2292 graph = defaultdict(list) 

2293 rank_edges = {} 

2294 

2295 for rank, nodes in ranks_map.items(): 

2296 for i in range(len(nodes) - 1): 

2297 u, v = nodes[i], nodes[i + 1] 

2298 graph[u].append(v) 

2299 rank_edges[(u, v)] = rank 

2300 

2301 visited = set() 

2302 path = [] 

2303 node_indices = {} 

2304 cycle_path = [] 

2305 cycle_ranks = [] 

2306 

2307 stack = [] 

2308 for node in list(graph.keys()): 

2309 if node not in visited: 

2310 stack.append((node, False)) 

2311 while stack: 

2312 current_node, is_processed = stack.pop() 

2313 

2314 if is_processed: 

2315 path.pop() 

2316 del node_indices[current_node] 

2317 continue 

2318 

2319 if current_node in node_indices: 

2320 cycle_start = node_indices[current_node] 

2321 cycle_path = path[cycle_start:] + [current_node] 

2322 for i in range(cycle_start, len(path)): 

2323 u = path[i] 

2324 v = path[i + 1] if i + 1 < len(path) else current_node 

2325 cycle_ranks.append(f"{rank_edges[(u, v)]} {u} -> {v}") 

2326 return cycle_path, cycle_ranks 

2327 

2328 if current_node in visited: 

2329 continue 

2330 

2331 visited.add(current_node) 

2332 node_indices[current_node] = len(path) 

2333 path.append(current_node) 

2334 

2335 stack.append((current_node, True)) 

2336 for neighbor in reversed(graph[current_node]): 

2337 stack.append((neighbor, False)) 

2338 

2339 return None, None 

2340 

2341 

2342def output_cycle_results(cycle_path, cycle_ranks): 

2343 """ 

2344 Helper function to output cycle detection results. 

2345 

2346 Args: 

2347 cycle_path (list): List of nodes forming a cycle, if any. 

2348 cycle_ranks (list): List of ranks involved in the cycle. 

2349 

2350 Returns: 

2351 None: Outputs results to the console. 

2352 """ 

2353 if cycle_path: 

2354 logger.error("Cycle detected:") 

2355 path_str = " -> ".join(str(node) for node in cycle_path) 

2356 logger.error("%s -> %s", path_str, cycle_path[0]) # Close the cycle 

2357 logger.error("Involving ranks:") 

2358 for rank in cycle_ranks: 

2359 logger.error(rank) 

2360 else: 

2361 logger.warning("Cycle Check succeeded. There is no cycle in the graph.") 

2362 

2363 

2364def parse_and_validate(data: dict, all_rank: bool = True): 

2365 """ 

2366 Parse and validate execution orders in a directed graph structure. 

2367 

2368 This function checks the integrity and consistency of a given dataset, ensuring all required 

2369 keys are present and correctly referenced. It also validates the structure of the input data 

2370 and parses string values to extract meaningful components. 

2371 

2372 Args: 

2373 data (dict): A dictionary where keys are string identifiers and values are lists of strings. 

2374 Each value represents a dependency or reference to other keys. 

2375 all_rank (bool): If True, checks that all elements referenced in the data are present as keys 

2376 in the dictionary. If False, only checks intersections. 

2377 

2378 Returns: 

2379 None: Log error messages to the console if validation fails, otherwise completes silently. 

2380 

2381 Raises: 

2382 ValueError: Raised indirectly if `parse_elements` encounters malformed input strings. 

2383 TypeError: Raised indirectly if data contains unexpected types. 

2384 """ 

2385 

2386 def parse_elements(value: str, max_groups: int = 2) -> set: 

2387 """Extract unique elements inside the first one or two parentheses from a string.""" 

2388 

2389 groups = re.findall(r'\((\d+)\)', value) 

2390 limited_groups = groups[:max_groups] # Limit to the first `max_groups` matches 

2391 

2392 return {item.strip() for item in limited_groups} 

2393 

2394 if not isinstance(data, dict): 

2395 logger.error("Input must be a dictionary with string keys and lists of strings as values.") 

2396 return 

2397 

2398 key_to_values = {key: set(values) for key, values in data.items() if 

2399 isinstance(values, list) and all(isinstance(v, str) for v in values)} 

2400 

2401 for key, values in data.items(): 

2402 if not isinstance(values, list) or not all(isinstance(v, str) for v in values): 

2403 logger.error("Values for key '%s' must be a list of strings.", key) 

2404 continue 

2405 

2406 for value in values: 

2407 try: 

2408 elements = parse_elements(value) 

2409 except (ValueError, TypeError, AttributeError) as e: 

2410 logger.error("Unable to parse elements from value '%s' in key '%s'. Error: %s", value, key, e) 

2411 continue 

2412 

2413 # Check for missing keys if all_rank is True 

2414 if all_rank: 

2415 missing_keys = elements - key_to_values.keys() 

2416 if missing_keys: 

2417 logger.error("The following keys are missing for value '%s': %s", value, missing_keys) 

2418 continue 

2419 

2420 # Check if the value is present in the referenced keys 

2421 for element in elements & key_to_values.keys() if not all_rank else elements: 

2422 if value not in key_to_values[element]: 

2423 logger.error("Key '%s' is missing the value '%s'.", element, value) 

2424 

2425 

2426def generate_operations(order_list: dict[int, list[MetaStep]], 

2427 chunk_num: int, 

2428 com_type: str = 'loop') -> dict[str, list[str]]: 

2429 """ 

2430 Generate formatted operations dictionary from pipeline execution order. 

2431 

2432 Args: 

2433 order_list (dict): Dictionary where keys are rank IDs and values are MetaStep execution sequences 

2434 chunk_num (int): Number of chunks (virtual pipeline stages) 

2435 com_type (str): Stage-to-rank mapping type ('loop' for cyclic, 'v' for V-shaped) 

2436 

2437 Returns: 

2438 Dictionary where keys are rank IDs (as strings) and values are lists of formatted operation strings 

2439 """ 

2440 

2441 def stage_to_rank(stage_index, style, stage_num, real_stage_num): 

2442 """Map stage index to rank""" 

2443 if style == 'loop': 

2444 return stage_index % real_stage_num 

2445 if style == 'v': 

2446 if stage_index < real_stage_num: 

2447 return stage_index 

2448 return stage_num - 1 - stage_index 

2449 raise ValueError("Invalid style") 

2450 

2451 def find_send_target(stage_idx, op_type): 

2452 """Find target stage for SEND operation""" 

2453 if op_type == MetaStepType.FWD_SEND: 

2454 return forward_comm.get(stage_idx) 

2455 return backward_comm.get(stage_idx) 

2456 

2457 def find_recv_source(stage_idx, op_type): 

2458 """Find source stage for RECV operation""" 

2459 if op_type == MetaStepType.FWD_RECV: 

2460 # Reverse lookup in forward_comm 

2461 for src, dst in forward_comm.items(): 

2462 if dst == stage_idx: 

2463 return src 

2464 else: 

2465 # Reverse lookup in backward_comm 

2466 for src, dst in backward_comm.items(): 

2467 if dst == stage_idx: 

2468 return src 

2469 return None 

2470 

2471 real_stage = len(order_list) 

2472 total_stages = real_stage * chunk_num 

2473 

2474 # Build communication rules 

2475 forward_comm = {} 

2476 backward_comm = {} 

2477 

2478 for i in range(total_stages): 

2479 if i + 1 < total_stages: 

2480 forward_comm[i] = i + 1 

2481 if i - 1 >= 0: 

2482 backward_comm[i] = i - 1 

2483 

2484 formatted_operations = defaultdict(list) 

2485 

2486 for rank, steps in order_list.items(): 

2487 operation_counter = defaultdict(int) 

2488 

2489 for step in steps: 

2490 if step.type in [MetaStepType.FWD_SEND, MetaStepType.BWD_SEND]: 

2491 target_stage = find_send_target(step.stage_index, step.type) 

2492 if target_stage is not None: 

2493 target_rank = stage_to_rank(target_stage, com_type, total_stages, real_stage) 

2494 comm_pair = (rank, target_rank, step.micro_index) 

2495 operation_counter[comm_pair] += 1 

2496 count = operation_counter[comm_pair] 

2497 formatted_op = f"Send_Receive_({rank})->({target_rank})_micro{step.micro_index}_{count}th" 

2498 formatted_operations[str(rank)].append(formatted_op) 

2499 

2500 elif step.type in [MetaStepType.FWD_RECV, MetaStepType.BWD_RECV]: 

2501 source_stage = find_recv_source(step.stage_index, step.type) 

2502 if source_stage is not None: 

2503 source_rank = stage_to_rank(source_stage, com_type, total_stages, real_stage) 

2504 comm_pair = (source_rank, rank, step.micro_index) 

2505 operation_counter[comm_pair] += 1 

2506 count = operation_counter[comm_pair] 

2507 formatted_op = f"Send_Receive_({source_rank})->({rank})_micro{step.micro_index}_{count}th" 

2508 formatted_operations[str(rank)].append(formatted_op) 

2509 

2510 # Convert defaultdict to dict 

2511 return dict(formatted_operations) 

2512 

2513 

2514def validate_pipeline_execution(order_list: dict[int, list[MetaStep]], 

2515 chunk_num: int, 

2516 com_type: str = 'loop') -> dict[str, any]: 

2517 """ 

2518 Comprehensive validation function for pipeline parallel execution order. 

2519 

2520 This function validates the execution order of pipeline parallelism by: 

2521 1. Checking SEND/RECV communication pair matching 

2522 2. Detecting duplicate operations 

2523 3. Detecting cycles in communication graphs 

2524 4. Verifying computation-SEND matching 

2525 

2526 Args: 

2527 order_list: Dictionary where keys are rank IDs and values are MetaStep execution sequences 

2528 chunk_num: Number of chunks (virtual pipeline stages) 

2529 com_type: Stage-to-rank mapping type ('loop' for cyclic, 'v' for V-shaped) 

2530 

2531 Returns: 

2532 Dictionary containing validation results with the following keys: 

2533 - validation: Communication pair validation results 

2534 - cycle_detection: Cycle detection results 

2535 - computation_send_matching: Computation-SEND matching validation results 

2536 - has_errors: Boolean indicating if any errors were found 

2537 - error_messages: List of all error messages found 

2538 - formatted_operations: Generated formatted operations 

2539 """ 

2540 

2541 # Generate operations 

2542 formatted_operations = generate_operations(order_list, chunk_num, com_type) 

2543 

2544 parse_and_validate(formatted_operations, True) 

2545 

2546 # Detect cycles 

2547 cycle_path, cycle_ranks = detect_cycle_in_graph(formatted_operations) 

2548 

2549 # Output results 

2550 output_cycle_results(cycle_path, cycle_ranks) 

2551 

2552 result = { 

2553 'formatted_operations': formatted_operations, 

2554 'cycle_path': cycle_path, 

2555 'cycle_ranks': cycle_ranks, 

2556 'has_cycle': bool(cycle_path) 

2557 } 

2558 return result