Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / passes / parallel / pp_pass.py: 93%

715 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-12-05 05:12 +0800

1# Portions copyright (c) Meta Platforms, Inc. and affiliates. 

2# Licensed under the BSD-3-Clause license; see 

3# Third_Party_Open_Source_Software_Notice. 

4# Copyright 2026 Huawei Technologies Co., Ltd 

5# 

6# Licensed under the Apache License, Version 2.0 (the "License"); 

7# you may not use this file except in compliance with the License. 

8# You may obtain a copy of the License at 

9# 

10# http://www.apache.org/licenses/LICENSE-2.0 

11# 

12# Unless required by applicable law or agreed to in writing, software 

13# distributed under the License is distributed on an "AS IS" BASIS, 

14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

15# See the License for the specific language governing permissions and 

16# limitations under the License. 

17# ============================================================================ 

18""" 

19PP Pass - Pipeline-Parallel Graph Split Pass 

20 

21Splits the (already FSDP-transformed) joint fwd+bwd FX graph into this 

22rank's pipeline stage, entirely at graph level — no model deepcopy, no 

23``torch.distributed.pipelining`` dependency. Where torchtitan splits at the 

24*module* level (``_split_module`` deepcopy + layer deletion, then wraps each 

25chunk in a ``PipelineStage``), this pass: 

26 

271. Attributes every FX node to a stage via ``nn_module_stack`` metadata 

28 (parameters are static placeholders, attributed by FQN ancestor walk). 

29 Root-level nodes the stack cannot resolve (residual adds written in the 

30 parent's ``forward``, loss glue) are attributed by their CONSUMERS, so a 

31 residual add sandwiched between two stages rides with the stage that 

32 consumes it. 

332. Detects the stage boundary as the set of values crossing each cut — 

34 activations forward, gradients backward. Real ATen graphs cross with 

35 more than the trunk tensor: dynamic-shape ``sym_size`` scalars and 

36 parent-level views all cross, so every crossing value is shipped (int 

37 scalars are packed as 0-d int64 tensors by the schedule and unwrapped 

38 with ``item()`` on arrival). 

393. Slices stage ``k`` into a forward subgraph and a backward subgraph. The 

40 forward outputs (all crossing activations plus every intermediate the 

41 backward references) become backward placeholders, so the GPipe schedule 

42 can run all forwards before all backwards. 

434. Prunes foreign-stage submodules from the live model (torch's 

44 ``named_parameters`` then yields only this stage's entries, keeping the 

45 trainer / optimizer FSDP- and PP-agnostic). 

465. Installs a self-contained pipeline schedule as a ``call_module`` node in 

47 a stub graph — the trainer's ``graph_module(*flat_inputs)`` dispatches to 

48 it unchanged, and the stub survives any later ``recompile()`` because the 

49 schedule lives in the graph itself, not in an overwritten ``forward``. 

50 ``ScheduleGPipe`` / ``Schedule1F1B`` drive one stage per rank; 

51 ``ScheduleInterleaved1F1B`` drives ``PassConfig.pp_chunks`` virtual stages 

52 per rank (VPP) using the loop mapping ``rank, rank + pp_degree, ...``. 

53 

54Run order in ``PassPipeline``: AFTER ``FSDPPass``. The FSDP collectives are 

55value-level FX nodes that follow the data flow: this stage's all_gather / 

56reduce_scatter nodes land inside its slices untouched, while foreign 

57stages' collectives are simply never copied. Splitting first (PP before 

58FSDP) would instead hand ``FSDPPass`` two subgraphs and a loss-less output 

59list, breaking its grad-index contract. This ordering is also what makes 

60the PP+DP hybrid work with no extra machinery: with the 2-D ``(pp, DP)`` 

61mesh (``GraphCompiler._init_pp_dp_mesh``), ``FSDPPass`` shards parameters 

62over the intra-stage DP group and ``PpPass`` pipelines each DP replica with 

63the same DP replica of the neighbouring stages over the cross-stage 

64``"pp"`` group. FSDP's backward re-gather / remat nodes are tagged 

65``autograd_backward`` by ``FSDPPass`` precisely so this pass classifies 

66them into the backward slice (lazy re-gather), and forward-phase reshard 

67nodes stay in the forward slice. 

68""" 

69 

70__all__ = ["PpPass", "_auto_stage_split"] 

71 

72import logging 

73from dataclasses import dataclass 

74from typing import Any, Dict, Iterator, List, Optional, Sequence, Set, Tuple 

75 

76import torch 

77import torch.distributed as dist 

78from torch import fx, nn 

79from torch.distributed.distributed_c10d import _resolve_process_group 

80 

81from ...pass_config import PassConfig, normalize_dp_mode 

82from ..base import GraphPass 

83from ...graph_parallel_plan import GraphParallelPlan 

84from .pp_schedule import ( 

85 PipelineScheduleBase, 

86 ScheduleInterleaved1F1B, 

87 get_schedule_class, 

88) 

89 

90_LOG = logging.getLogger(__name__) 

91 

92_FWD = "fwd" 

93_BWD = "bwd" 

94 

95 

96def _sanitize(name: str) -> str: 

97 """Turn a dotted FQN into a codegen-safe placeholder name.""" 

98 return name.replace(".", "_") 

99 

100 

101def _iter_node_args(node: fx.Node) -> Iterator[fx.Node]: 

102 """Yield every ``fx.Node`` reachable in ``node.args`` / ``node.kwargs``.""" 

103 stack: List[Any] = list(node.args) + list(node.kwargs.values()) 

104 while stack: 

105 item = stack.pop() 

106 if isinstance(item, fx.Node): 

107 yield item 

108 elif isinstance(item, (tuple, list)): 

109 stack.extend(item) 

110 elif isinstance(item, dict): 

111 stack.extend(item.values()) 

112 

113 

114def _tensor_arg_stages(node: fx.Node, node_stage: Dict[fx.Node, int]) -> List[int]: 

115 """Stages of ``node``'s TENSOR-valued resolved args. 

116 

117 Shape-metadata args (dynamic-shape ``sym_size`` scalars) are excluded: 

118 they are born wherever shapes are known, carry no data dependency, and 

119 would otherwise drag a node's placement against its dataflow (e.g. a 

120 boundary-gradient view whose ``sym_size`` args are stage-0 born while 

121 the gradient itself is born downstream). 

122 """ 

123 stages = [] 

124 for arg in _iter_node_args(node): 

125 stage = node_stage.get(arg) 

126 if stage is None: 

127 continue 

128 val = arg.meta.get("val") 

129 if val is not None and not isinstance(val, torch.Tensor): 

130 continue 

131 stages.append(stage) 

132 return stages 

133 

134 

135def _innermost_fqns(node: fx.Node) -> List[str]: 

136 """Module FQNs on ``node``'s ``nn_module_stack``, innermost first.""" 

137 stack = node.meta.get("nn_module_stack") or {} 

138 return [fqn for fqn, _ in reversed(list(stack.values()))] 

139 

140 

141def _even_split(names: List[str], pp_degree: int, prefix: str = "") -> List[List[str]]: 

142 """Distribute ``names`` across ``pp_degree`` stages as evenly as possible. 

143 

144 The first ``len(names) % pp_degree`` stages get one extra entry; each 

145 entry is prefixed (``prefix``) so bare child names become FQNs. 

146 """ 

147 base, rem = divmod(len(names), pp_degree) 

148 stages: List[List[str]] = [[] for _ in range(pp_degree)] 

149 cursor = 0 

150 for s in range(pp_degree): 

151 size = base + (1 if s < rem else 0) 

152 stages[s] = [f"{prefix}{name}" for name in names[cursor : cursor + size]] 

153 cursor += size 

154 return stages 

155 

156 

157def _auto_stage_split(model: nn.Module, pp_degree: int) -> List[List[str]]: 

158 """Default PP split: even distribution of the model's layer container. 

159 

160 Mirrors torchtitan's ``_generate_llm_fqn_per_model_part`` weighting 

161 without hardcoding LLM module names: 

162 

163 - The first top-level child that is an ``nn.ModuleList`` with at least 

164 ``pp_degree`` entries is the *layer container* (typically ``layers``). 

165 - Top-level children registered before it go to stage 0 (input side, 

166 e.g. embeddings); children after it go to the last stage (output 

167 side, e.g. norm / lm_head). 

168 - Container elements are distributed as evenly as possible (see 

169 ``_even_split``). 

170 

171 Without a qualifying container, all top-level children are split evenly 

172 in registration order. 

173 

174 Returns: 

175 ``pp_degree`` lists of exact module FQNs, one per stage. 

176 """ 

177 if pp_degree < 2: 

178 raise ValueError(f"pp_degree must be >= 2 for a PP split, got {pp_degree}") 

179 

180 children = [name for name, _ in model.named_children()] 

181 

182 container: Optional[str] = None 

183 for name, child in model.named_children(): 

184 if isinstance(child, nn.ModuleList) and len(child) >= pp_degree: 

185 container = name 

186 break 

187 

188 if container is None: 

189 if len(children) < pp_degree: 

190 raise ValueError( 

191 f"Cannot split {len(children)} top-level children across " 

192 f"{pp_degree} PP stages; provide a manual stage plan via " 

193 f"GraphParallelPlan.pp_stage()" 

194 ) 

195 return _even_split(children, pp_degree) 

196 

197 container_mod = getattr(model, container) 

198 if isinstance(container_mod, nn.ModuleDict): 

199 elem_keys = list(container_mod.keys()) 

200 else: 

201 elem_keys = [str(i) for i in range(len(container_mod))] 

202 

203 idx = children.index(container) 

204 before, after = children[:idx], children[idx + 1 :] 

205 

206 stages = _even_split(elem_keys, pp_degree, prefix=f"{container}.") 

207 stages[0] = before + stages[0] 

208 stages[-1] = stages[-1] + after 

209 return stages 

210 

211 

212@dataclass 

213class _RunContext: 

214 """This rank's PP execution context, resolved and guarded for ``run``. 

215 

216 ``pp_degree`` is the number of PHYSICAL ranks in the PP group, while 

217 ``num_stages`` is the number of VIRTUAL stages (``pp_degree * chunks``). 

218 Rank ``stage_idx`` owns the virtual stages in ``stage_indices`` using the 

219 interleaved (loop) assignment ``stage_idx, stage_idx + pp_degree, ...``. 

220 With the default ``chunks == 1`` the two coincide. 

221 """ 

222 

223 model: nn.Module 

224 pp_degree: int 

225 group: Any 

226 stage_idx: int 

227 chunks: int 

228 num_stages: int 

229 stage_indices: List[int] 

230 

231 

232@dataclass 

233class _StageGraphs: 

234 """One virtual stage's sliced graphs and boundary contract.""" 

235 

236 stage_idx: int 

237 fwd_gm: fx.GraphModule 

238 bwd_gm: fx.GraphModule 

239 boundaries: "_Boundaries" 

240 state_indices: List[int] 

241 num_trainable: int 

242 

243 

244@dataclass 

245class _StageSplit: 

246 """Stage plan and per-node classification produced by ``_classify_stage``. 

247 

248 Bundles what the boundary-detection and subgraph-construction phases 

249 need, so ``run`` orchestrates phases instead of threading a dozen 

250 parallel locals through every call. 

251 """ 

252 

253 state_fqns: List[str] 

254 state_is_param: List[bool] 

255 stage_plan: List[List[str]] 

256 node_stage: Dict[fx.Node, int] 

257 node_phase: Dict[fx.Node, str] 

258 user_input_phs: List[fx.Node] 

259 user_input_stages: List[int] 

260 user_input_stage_sets: List[Tuple[int, ...]] 

261 state_phs: List[fx.Node] 

262 stage_state_indices: List[int] 

263 stage_state_fqns: List[str] 

264 

265 

266@dataclass 

267class _GraphClassification: 

268 """Per-node stage/phase classification produced by ``_classify_graph``.""" 

269 

270 stage_state_indices: List[int] 

271 node_stage: Dict[fx.Node, int] 

272 node_phase: Dict[fx.Node, str] 

273 user_input_phs: List[fx.Node] 

274 user_input_stages: List[int] 

275 user_input_stage_sets: List[Tuple[int, ...]] 

276 state_phs: List[fx.Node] 

277 

278 

279@dataclass 

280class _Boundaries: 

281 """Boundary value lists crossing this stage's cuts. 

282 

283 All lists are in joint-graph topological order so the producer and 

284 consumer of a cut agree on P2P ordering: 

285 

286 - ``act_in``: stage-(k-1) values consumed by stage k (tensors, 

287 dynamic-shape scalars, parent-level views — everything a real ATen 

288 graph pushes across a cut). 

289 - ``act_out``: stage-k values consumed by stage k+1. 

290 - ``grad_in``: stage-(k+1) backward values consumed by stage k. 

291 - ``grad_out``: stage-k backward values consumed by stage k-1. 

292 - ``saved``: forward-phase values referenced by this stage's backward 

293 nodes — exported as forward outputs and replayed as backward inputs. 

294 """ 

295 

296 act_in: List[fx.Node] 

297 act_out: List[fx.Node] 

298 grad_in: List[fx.Node] 

299 grad_out: List[fx.Node] 

300 saved: List[fx.Node] 

301 

302 

303@dataclass 

304class _SubgraphBuilder: 

305 """Accumulator for assembling one stage subgraph. 

306 

307 ``env`` maps already-copied same-slice nodes; ``foreign`` maps 

308 boundary values to their placeholder stand-ins; ``used`` carries the 

309 taken placeholder names for ``_unique``. 

310 """ 

311 

312 g: fx.Graph 

313 used: Set[str] 

314 env: Dict[fx.Node, fx.Node] 

315 foreign: Dict[fx.Node, fx.Node] 

316 

317 

318class PpPass(GraphPass): 

319 """Pipeline-parallel partitioning pass (graph-level stage split).""" 

320 

321 name = "pp_parallel" 

322 

323 def __init__(self, parallel_plan: Optional[GraphParallelPlan] = None) -> None: 

324 """Initialize PP pass state. 

325 

326 Args: 

327 parallel_plan: Declarative plan; ``pp_module_fqns_per_stage`` (from 

328 ``pp_stage()``) overrides the automatic even-by-layers 

329 split. 

330 """ 

331 super().__init__() 

332 self._parallel_plan = parallel_plan 

333 

334 def run( 

335 self, 

336 graph_module: fx.GraphModule, 

337 pass_config: PassConfig, 

338 **kwargs: Any, 

339 ) -> fx.GraphModule: 

340 """Split the joint graph to this rank's stage and install the schedule. 

341 

342 Args: 

343 graph_module: Joint fwd+bwd FX graph (post-``FSDPPass``). 

344 pass_config: Parallel configuration; ``pp_degree`` (``None`` 

345 resolves to ``world_size``) and ``pp_microbatch_size`` are 

346 read directly. 

347 **kwargs: Must include ``model`` (the live ``nn.Module``); may 

348 include ``parallel_plan``. 

349 

350 Returns: 

351 The same graph module, rewritten into a stage stub whose 

352 ``call_module`` node invokes the installed pipeline schedule 

353 (``ScheduleGPipe`` / ``Schedule1F1B`` / 

354 ``ScheduleInterleaved1F1B`` per ``pass_config.pp_schedule``). 

355 """ 

356 run_ctx = self._resolve_run_context(pass_config, kwargs) 

357 if run_ctx is None: 

358 return graph_module 

359 

360 split = self._classify_stage(graph_module, run_ctx) 

361 self._build_and_install_stage(graph_module, pass_config, run_ctx, split) 

362 return graph_module 

363 

364 def _resolve_run_context( 

365 self, 

366 pass_config: PassConfig, 

367 kwargs: Dict[str, Any], 

368 ) -> Optional[_RunContext]: 

369 """Guard and resolve the model, PP group, and this rank's stage. 

370 

371 Returns: 

372 The run context, or ``None`` when the pass is skipped 

373 (distributed not initialized, ``world_size == 1``, or 

374 ``pp_degree < 2``). 

375 """ 

376 if not dist.is_initialized() or dist.get_world_size() == 1: 

377 _LOG.info("Skipped: distributed not initialized or world_size=1") 

378 return None 

379 

380 model = kwargs.get("model") 

381 if model is None: 

382 raise ValueError( 

383 "PpPass requires the live model via kwargs (model=...) so it " 

384 "can resolve the stage plan and prune foreign-stage modules" 

385 ) 

386 self._parallel_plan = kwargs.get("parallel_plan", self._parallel_plan) 

387 

388 # Skip BEFORE _resolve_group_and_stage so a disabled pass does not 

389 # execute the collective dist.new_group. 

390 pp_degree = pass_config.pp_degree or dist.get_world_size() 

391 if pp_degree < 2: 

392 _LOG.info("Skipped: pp_degree=%s < 2", pp_degree) 

393 return None 

394 pp_degree, group, stage_idx = self._resolve_group_and_stage(pass_config, kwargs) 

395 chunks = pass_config.pp_chunks 

396 num_stages = pp_degree * chunks 

397 stage_indices = list(range(stage_idx, num_stages, pp_degree)) 

398 _LOG.info( 

399 "Running: rank %s/%s owns virtual stages %s/%s, world_size=%s", 

400 stage_idx, 

401 pp_degree, 

402 stage_indices, 

403 num_stages, 

404 dist.get_world_size(), 

405 ) 

406 return _RunContext( 

407 model=model, 

408 pp_degree=pp_degree, 

409 group=group, 

410 stage_idx=stage_idx, 

411 chunks=chunks, 

412 num_stages=num_stages, 

413 stage_indices=stage_indices, 

414 ) 

415 

416 def _classify_stage( 

417 self, graph_module: fx.GraphModule, run_ctx: _RunContext 

418 ) -> _StageSplit: 

419 """Resolve the stage plan and classify every node's stage + phase. 

420 

421 Chains the state-list contract checks, the stage-plan resolution, 

422 node classification, the gradient-output anchoring with its stage 

423 propagation, and the adjacent-dataflow validation. 

424 

425 Args: 

426 graph_module: Joint fwd+bwd FX graph (post-``FSDPPass``). 

427 run_ctx: This rank's PP execution context. 

428 

429 Returns: 

430 The ``_StageSplit`` bundling the plan and per-node 

431 classification for the construction phase. 

432 """ 

433 state_fqns = self._require_state_list(graph_module) 

434 state_is_param = self._require_is_param(graph_module, state_fqns) 

435 num_state_inputs = getattr(graph_module, "num_state_inputs", len(state_fqns)) 

436 

437 stage_plan = self._resolve_stage_plan(run_ctx.model, run_ctx.num_stages) 

438 stage_of_fqn = {fqn: s for s, fqns in enumerate(stage_plan) for fqn in fqns} 

439 

440 graph_cls = self._classify_graph( 

441 graph_module, 

442 run_ctx, 

443 stage_of_fqn, 

444 state_fqns, 

445 num_state_inputs, 

446 ) 

447 

448 self._anchor_grad_outputs( 

449 graph_module, 

450 graph_cls.node_stage, 

451 stage_of_fqn, 

452 state_fqns, 

453 run_ctx.model, 

454 ) 

455 self._propagate_anchor_stages( 

456 graph_module, graph_cls.node_stage, graph_cls.node_phase 

457 ) 

458 self._validate_adjacent_dataflow(graph_module, graph_cls.node_stage) 

459 

460 return _StageSplit( 

461 state_fqns=state_fqns, 

462 state_is_param=state_is_param, 

463 stage_plan=stage_plan, 

464 node_stage=graph_cls.node_stage, 

465 node_phase=graph_cls.node_phase, 

466 user_input_phs=graph_cls.user_input_phs, 

467 user_input_stages=graph_cls.user_input_stages, 

468 user_input_stage_sets=graph_cls.user_input_stage_sets, 

469 state_phs=graph_cls.state_phs, 

470 stage_state_indices=graph_cls.stage_state_indices, 

471 stage_state_fqns=[state_fqns[i] for i in graph_cls.stage_state_indices], 

472 ) 

473 

474 def _build_and_install_stage( 

475 self, 

476 graph_module: fx.GraphModule, 

477 pass_config: PassConfig, 

478 run_ctx: _RunContext, 

479 split: _StageSplit, 

480 ) -> None: 

481 """Build the owned virtual-stage subgraphs, prune, and install the stub. 

482 

483 Trainable-state resolution must precede ``_prune_live_model``: the 

484 gradient-output nodes map positionally onto the FULL trainable list, 

485 so pruning foreign-stage parameters first would shift the positions. 

486 

487 Args: 

488 graph_module: Joint fwd+bwd FX graph, rewritten in place. 

489 pass_config: Parallel configuration (microbatch size read). 

490 run_ctx: This rank's PP execution context. 

491 split: Stage plan and per-node classification. 

492 """ 

493 trainable_indices = self._trainable_state_indices( 

494 split.state_fqns, split.state_is_param, run_ctx.model 

495 ) 

496 state_positions = { 

497 idx: pos for pos, idx in enumerate(split.stage_state_indices) 

498 } 

499 

500 stage_graphs: List[_StageGraphs] = [] 

501 for stage_idx in run_ctx.stage_indices: 

502 boundaries = self._find_boundaries( 

503 graph_module, 

504 split.node_stage, 

505 split.node_phase, 

506 run_ctx.num_stages, 

507 stage_idx, 

508 split.user_input_phs, 

509 split.user_input_stage_sets, 

510 ) 

511 stage_state_indices = [ 

512 idx 

513 for idx in split.stage_state_indices 

514 if split.node_stage[split.state_phs[idx]] == stage_idx 

515 ] 

516 stage_state_set = set(stage_state_indices) 

517 stage_trainable = [i for i in trainable_indices if i in stage_state_set] 

518 fwd_gm, bwd_gm = self._build_stage_graphs( 

519 graph_module, 

520 split, 

521 boundaries, 

522 stage_idx, 

523 run_ctx.num_stages, 

524 stage_state_indices, 

525 trainable_indices, 

526 ) 

527 stage_graphs.append( 

528 _StageGraphs( 

529 stage_idx=stage_idx, 

530 fwd_gm=fwd_gm, 

531 bwd_gm=bwd_gm, 

532 boundaries=boundaries, 

533 state_indices=stage_state_indices, 

534 num_trainable=len(stage_trainable), 

535 ) 

536 ) 

537 

538 keep_fqns: List[str] = [] 

539 for stage_idx in run_ctx.stage_indices: 

540 keep_fqns.extend(split.stage_plan[stage_idx]) 

541 self._prune_live_model(run_ctx.model, keep_fqns) 

542 

543 sched = self._build_schedule( 

544 stage_graphs, 

545 pass_config, 

546 run_ctx, 

547 split, 

548 trainable_indices, 

549 state_positions, 

550 ) 

551 self._install_stub( 

552 graph_module, 

553 sched, 

554 split.stage_state_fqns, 

555 split.state_is_param, 

556 split.stage_state_indices, 

557 len(split.user_input_phs), 

558 ) 

559 

560 _LOG.info( 

561 "Completed: rank %s owns virtual stages %s, %d state entries, " 

562 "%d trainable params", 

563 run_ctx.stage_idx, 

564 run_ctx.stage_indices, 

565 len(split.stage_state_fqns), 

566 sum(stage.num_trainable for stage in stage_graphs), 

567 ) 

568 

569 def _build_stage_graphs( 

570 self, 

571 graph_module: fx.GraphModule, 

572 split: _StageSplit, 

573 boundaries: _Boundaries, 

574 stage_idx: int, 

575 num_stages: int, 

576 stage_state_indices: List[int], 

577 trainable_indices: List[int], 

578 ) -> Tuple[fx.GraphModule, fx.GraphModule]: 

579 """Build one virtual stage's forward and backward subgraphs.""" 

580 stage_state_fqns = [split.state_fqns[i] for i in stage_state_indices] 

581 fwd_gm, fwd_out_orig = self._build_fwd_graph( 

582 graph_module, 

583 split, 

584 boundaries, 

585 stage_idx, 

586 num_stages, 

587 stage_state_indices, 

588 stage_state_fqns, 

589 ) 

590 bwd_gm = self._build_bwd_graph( 

591 graph_module, 

592 split, 

593 boundaries, 

594 stage_idx, 

595 num_stages, 

596 stage_state_indices, 

597 stage_state_fqns, 

598 fwd_out_orig, 

599 trainable_indices, 

600 ) 

601 return fwd_gm, bwd_gm 

602 

603 # ------------------------------------------------------------------ 

604 # Tracer contract helpers 

605 # ------------------------------------------------------------------ 

606 

607 @staticmethod 

608 def _require_state_list(graph_module: fx.GraphModule) -> List[str]: 

609 """Return the graph's live ``state_fqns`` list (shared with JointGraph). 

610 

611 The tracer attaches the SAME list object to the GraphModule and the 

612 ``JointGraph``; mutating it in place (done in ``_install_stub``) 

613 keeps ``run_traced_graph``'s validation consistent with the pruned 

614 model. Copying here would desynchronize the two. 

615 """ 

616 state_fqns = getattr(graph_module, "state_fqns", None) 

617 if state_fqns is None: 

618 raise ValueError( 

619 "PpPass requires the tracer's state_fqns attribute on the " 

620 "joint graph (attach it via trace_model_graph)" 

621 ) 

622 return state_fqns 

623 

624 @staticmethod 

625 def _require_is_param( 

626 graph_module: fx.GraphModule, state_fqns: List[str] 

627 ) -> List[bool]: 

628 """Return the graph's live ``state_is_param`` list, defaulting to 

629 all-params (matching the tracer's fallback for older traces).""" 

630 state_is_param = getattr(graph_module, "state_is_param", None) 

631 if state_is_param is None: 

632 state_is_param = [True] * len(state_fqns) 

633 graph_module.state_is_param = state_is_param 

634 return state_is_param 

635 

636 @staticmethod 

637 def _loss_node(graph_module: fx.GraphModule) -> Optional[fx.Node]: 

638 """The original joint graph's loss node (output index 0).""" 

639 output = next((n for n in graph_module.graph.nodes if n.op == "output"), None) 

640 if output is None: 

641 return None 

642 returned = output.args[0] 

643 if isinstance(returned, (list, tuple)) and returned: 

644 first = returned[0] 

645 if isinstance(first, fx.Node): 

646 return first 

647 return None 

648 

649 # ------------------------------------------------------------------ 

650 # Group / plan resolution 

651 # ------------------------------------------------------------------ 

652 

653 def _resolve_group_and_stage( 

654 self, pass_config: PassConfig, kwargs: Dict[str, Any] 

655 ) -> Tuple[int, Any, int]: 

656 """Resolve PP degree, process group, and this rank's stage index. 

657 

658 Two layouts are supported: 

659 

660 - **PP+DP hybrid** (``pp_group_name`` kwarg, registered by 

661 ``GraphCompiler._init_pp_dp_mesh``): the group spans one rank per 

662 stage at this rank's DP position, so the stage index is simply this 

663 rank's position within the group and every DP replica of a stage 

664 pipelines with the same DP replica of its neighbours. Requires 

665 ``pp_degree * dp_degree == world_size`` (validated here). 

666 - **Pure PP** (no ``pp_group_name``): the group is the whole world and 

667 each rank owns one or more virtual stages. ``fsdp_enabled`` is 

668 rejected here — a 1-D fallback FSDP mesh spans the whole world and 

669 would shard parameters across stage boundaries; the hybrid must go 

670 through the 2-D mesh path. 

671 

672 A single PP process group carries both forward activations and 

673 backward gradients; the schedule keeps the two ends of every 

674 neighbour pair's FIFO complementary (see ``Schedule1F1B`` and 

675 ``ScheduleInterleaved1F1B``). 

676 """ 

677 pp_group_name = kwargs.get("pp_group_name") 

678 if pp_group_name is not None: 

679 return self._resolve_from_pp_group(pass_config, pp_group_name) 

680 

681 world_size = dist.get_world_size() 

682 rank = dist.get_rank() 

683 pp_degree = pass_config.pp_degree or world_size 

684 

685 if pp_degree not in (1, world_size): 

686 raise ValueError( 

687 f"Without a pp process group only pure-PP is supported: " 

688 f"pp_degree={pp_degree} must equal world_size={world_size} " 

689 f"(or be 1 to disable PP). For the PP+DP hybrid pass " 

690 f"pp_group_name (registered by GraphCompiler's 2-D pp mesh)." 

691 ) 

692 if pass_config.fsdp_enabled: 

693 raise ValueError( 

694 "PP+FSDP hybrid requires a 2-D (pp, DP) mesh expressing both " 

695 "dimensions: let GraphCompiler build it (fsdp_enabled=True + " 

696 "pp_enabled=True, which registers the cross-stage 'pp' group " 

697 "and passes pp_group_name to this pass). The 1-D fallback " 

698 "FSDP mesh spans the whole world and cannot host PP — FSDP " 

699 "would shard parameters across stage boundaries. Run pure-PP " 

700 "(fsdp_enabled=False, pp_degree == world_size) or the mesh " 

701 "path." 

702 ) 

703 

704 group = dist.new_group(list(range(world_size))) 

705 # Pure-PP (pp_degree == world_size, checked above), so each rank's 

706 # physical stage index is its rank. Keep the general formula so a 

707 # future DP-replication layout (pp_degree < world_size) maps 

708 # rank->stage contiguously rather than silently assuming 1:1. 

709 stage_idx = rank * pp_degree // world_size 

710 return pp_degree, group, stage_idx 

711 

712 def _resolve_from_pp_group( 

713 self, pass_config: PassConfig, group_name: str 

714 ) -> Tuple[int, Any, int]: 

715 """Resolve stage/pp-degree from the registered ``"pp"`` group. 

716 

717 Validates the hybrid topology: the configured ``pp_degree`` (when 

718 set) must match the group size, and with the DP axis enabled 

719 ``pp_degree * dp_degree`` must tile the world. HSDP needs a 3-D mesh 

720 and is rejected outright. 

721 """ 

722 group = _resolve_process_group(group_name) 

723 pp_degree = dist.get_world_size(group) 

724 stage_idx = dist.get_rank(group) 

725 

726 configured = pass_config.pp_degree 

727 if configured is not None and configured != pp_degree: 

728 raise ValueError( 

729 f"pass_config.pp_degree={configured} does not match the " 

730 f"registered pp group size ({pp_degree})" 

731 ) 

732 

733 if pass_config.fsdp_enabled: 

734 dp_mode = normalize_dp_mode(pass_config.dp_mode) 

735 if dp_mode == "hsdp": 

736 raise ValueError( 

737 "PP + HSDP requires a 3-D (pp, dp_replicate, fsdp_shard) " 

738 "mesh, which is not supported yet; run PP with " 

739 "dp_mode='fsdp' or 'ddp'" 

740 ) 

741 dp_degree = ( 

742 pass_config.fsdp_degree 

743 if dp_mode == "fsdp" 

744 else pass_config.dp_replicate_degree 

745 ) 

746 world_size = dist.get_world_size() 

747 if dp_degree is None: 

748 if world_size % pp_degree != 0: 

749 raise ValueError( 

750 f"world_size ({world_size}) not divisible by the pp " 

751 f"group size ({pp_degree}); cannot derive the DP " 

752 f"degree" 

753 ) 

754 dp_degree = world_size // pp_degree 

755 if pp_degree * dp_degree != world_size: 

756 raise ValueError( 

757 f"PP+DP degrees must tile the world: pp_degree " 

758 f"({pp_degree}) x dp_degree ({dp_degree}) != world_size " 

759 f"({world_size})" 

760 ) 

761 

762 _LOG.info( 

763 "Resolved stage %s/%s from pp group '%s'", stage_idx, pp_degree, group_name 

764 ) 

765 return pp_degree, group, stage_idx 

766 

767 def _resolve_stage_plan(self, model: nn.Module, num_stages: int) -> List[List[str]]: 

768 """Resolve the per-virtual-stage module FQN lists (manual or auto).""" 

769 manual = ( 

770 self._parallel_plan.pp_module_fqns_per_stage 

771 if self._parallel_plan is not None 

772 else None 

773 ) 

774 if manual is not None: 

775 if len(manual) != num_stages: 

776 raise ValueError( 

777 f"Manual PP plan declares {len(manual)} stages but the " 

778 f"pipeline has {num_stages} virtual stages " 

779 f"(pp_degree * pp_chunks)" 

780 ) 

781 seen: Set[str] = set() 

782 for s, fqns in enumerate(manual): 

783 for fqn in fqns: 

784 if fqn in seen: 

785 raise ValueError( 

786 f"Module '{fqn}' is assigned to multiple stages " 

787 f"(stage {s} repeats it)" 

788 ) 

789 seen.add(fqn) 

790 stage_plan = [list(fqns) for fqns in manual] 

791 else: 

792 stage_plan = _auto_stage_split(model, num_stages) 

793 

794 known = dict(model.named_modules()) 

795 for s, fqns in enumerate(stage_plan): 

796 for fqn in fqns: 

797 if fqn not in known: 

798 raise ValueError(f"Stage {s} declares unknown module '{fqn}'") 

799 self._warn_unassigned_modules(model, stage_plan) 

800 return stage_plan 

801 

802 @staticmethod 

803 def _warn_unassigned_modules(model: nn.Module, stage_plan: List[List[str]]) -> None: 

804 """Warn about live modules no stage declares. 

805 

806 A module that is neither declared itself, nor lives inside a 

807 declared one, nor is an ancestor of a declared one (a container 

808 whose elements are declared) has its graph nodes attributed by 

809 the dataflow fallbacks (consumer stage, then last stage) — rarely 

810 what a manual plan intends. Auto splits declare every top-level 

811 child, so they never warn. 

812 """ 

813 declared = [fqn for fqns in stage_plan for fqn in fqns] 

814 unassigned: List[str] = [] 

815 for fqn, _ in model.named_modules(): 

816 if not fqn: 

817 # Root: parent-level glue is attributed by dataflow. 

818 continue 

819 covered = any( 

820 fqn == d or fqn.startswith(d + ".") or d.startswith(fqn + ".") 

821 for d in declared 

822 ) 

823 if not covered: 

824 unassigned.append(fqn) 

825 if not unassigned: 

826 return 

827 shown = unassigned[:10] 

828 if len(unassigned) > len(shown): 

829 shown.append(f"... {len(unassigned) - len(shown)} more") 

830 _LOG.warning( 

831 "No PP stage declares modules %s — their nodes ride with the " 

832 "dataflow attribution (consumer stage, then last stage). " 

833 "Declare them via GraphParallelPlan.pp_stage() if that is not intended.", 

834 shown, 

835 ) 

836 

837 # ------------------------------------------------------------------ 

838 # Node classification (stage + phase, topo order) 

839 # ------------------------------------------------------------------ 

840 

841 def _classify_graph( # pylint: disable=too-many-locals 

842 self, 

843 graph_module: fx.GraphModule, 

844 run_ctx: _RunContext, 

845 stage_of_fqn: Dict[str, int], 

846 state_fqns: Sequence[str], 

847 num_state_inputs: int, 

848 ) -> _GraphClassification: 

849 """Resolve every node's stage and fwd/bwd phase in topological order. 

850 

851 Phase: explicit ``autograd_backward`` tag, else inherited from args 

852 (post-trace inserts such as FSDP's reduce_scatter/wait inherit the 

853 bwd phase through their grad arguments). 

854 

855 Stage resolution, in priority order: 

856 

857 1. ``nn_module_stack`` walk (traced nodes, innermost module first) 

858 2. argument inheritance (post-trace inserts — state placeholders 

859 win, since backward compute nodes reference their params) 

860 3. consumer attribution for stack-less root-level glue (residual 

861 adds written in the parent's forward): the stage of their 

862 consumers, minimum when several — resolved in reverse topo 

863 4. last stage as the final fallback (loss chain, dead nodes) 

864 

865 User-input placeholders are NOT anchors: they are routed AFTER the 

866 fwd/bwd classification by dataflow (``_route_user_inputs``) — each 

867 rides with the single stage that consumes it, so kwargs-general 

868 inputs (multiple features on stage 0, several labels on the last 

869 stage, an auxiliary input on a middle stage) all work without 

870 positional heuristics. 

871 

872 ``stage_state_indices`` lists the state entries owned by the virtual 

873 stages THIS rank owns (``run_ctx.stage_indices``); every state 

874 placeholder still gets a stage so foreign consumers can be 

875 attributed. 

876 

877 Root-level state (no stage-owning module ancestor) is assigned to 

878 the stage of its (single) consumer; multi-stage consumption is the 

879 RoPE-cache-shaped error case and fails with an actionable message. 

880 """ 

881 graph = graph_module.graph 

882 placeholders = [n for n in graph.nodes if n.op == "placeholder"] 

883 state_ph_set = set(placeholders[:num_state_inputs]) 

884 num_stages = run_ctx.num_stages 

885 

886 node_stage: Dict[fx.Node, int] = {} 

887 node_phase: Dict[fx.Node, str] = {} 

888 

889 ( 

890 state_phs, 

891 deferred_state, 

892 stage_state_indices, 

893 user_input_phs, 

894 ) = self._classify_placeholders( 

895 placeholders, 

896 node_stage, 

897 node_phase, 

898 state_fqns, 

899 stage_of_fqn, 

900 num_state_inputs, 

901 run_ctx, 

902 ) 

903 self._classify_forward_nodes( 

904 graph, state_ph_set, stage_of_fqn, num_stages, node_stage, node_phase 

905 ) 

906 self._classify_backward_nodes( 

907 graph, state_ph_set, num_stages, node_stage, node_phase 

908 ) 

909 user_input_stages, user_input_stage_sets = self._route_user_inputs( 

910 user_input_phs, node_stage, num_stages 

911 ) 

912 self._assign_deferred_state( 

913 deferred_state, 

914 state_phs, 

915 state_fqns, 

916 node_stage, 

917 run_ctx.stage_indices, 

918 stage_state_indices, 

919 ) 

920 

921 return _GraphClassification( 

922 stage_state_indices=sorted(stage_state_indices), 

923 node_stage=node_stage, 

924 node_phase=node_phase, 

925 user_input_phs=user_input_phs, 

926 user_input_stages=user_input_stages, 

927 user_input_stage_sets=user_input_stage_sets, 

928 state_phs=state_phs, 

929 ) 

930 

931 def _classify_placeholders( # pylint: disable=too-many-locals 

932 self, 

933 placeholders: List[fx.Node], 

934 node_stage: Dict[fx.Node, int], 

935 node_phase: Dict[fx.Node, str], 

936 state_fqns: Sequence[str], 

937 stage_of_fqn: Dict[str, int], 

938 num_state_inputs: int, 

939 run_ctx: _RunContext, 

940 ) -> Tuple[List[fx.Node], List[int], List[int], List[fx.Node]]: 

941 """Classify placeholder nodes and collect this stage's state entries. 

942 

943 Only STATE placeholders get a stage here (via their FQN's module 

944 ancestor); user-input placeholders are routed later by dataflow 

945 (``_route_user_inputs``), once their consumers' stages are known. 

946 

947 Args: 

948 placeholders: All placeholder nodes in graph order. 

949 node_stage: Stage assignment accumulator to fill. 

950 node_phase: Phase assignment accumulator to fill. 

951 state_fqns: FQNs of the traced state entries (params/buffers). 

952 stage_of_fqn: Module FQN -> owning stage map. 

953 num_state_inputs: Number of leading state placeholders. 

954 run_ctx: This rank's PP execution context. 

955 

956 Returns: 

957 ``(state_phs, deferred_state, stage_state_indices, 

958 user_input_phs)``. ``deferred_state`` lists root-level state 

959 indices whose stage is resolved later from their consumers. 

960 """ 

961 state_phs: List[fx.Node] = [] 

962 deferred_state: List[int] = [] 

963 stage_state_indices: List[int] = [] 

964 for idx, ph in enumerate(placeholders): 

965 node_phase[ph] = _FWD 

966 if idx < num_state_inputs: 

967 stage = self._state_stage(state_fqns[idx], stage_of_fqn) 

968 state_phs.append(ph) 

969 if stage is None: 

970 deferred_state.append(idx) 

971 else: 

972 node_stage[ph] = stage 

973 if stage in run_ctx.stage_indices: 

974 stage_state_indices.append(idx) 

975 user_input_phs = list(placeholders[num_state_inputs:]) 

976 return state_phs, deferred_state, stage_state_indices, user_input_phs 

977 

978 @staticmethod 

979 def _route_user_inputs( 

980 user_input_phs: List[fx.Node], 

981 node_stage: Dict[fx.Node, int], 

982 num_stages: int, 

983 ) -> Tuple[List[int], List[Tuple[int, ...]]]: 

984 """Assign each user-input placeholder to the stages consuming it. 

985 

986 Runs after the fwd/bwd classification, so every consumer node 

987 already carries its final stage (user inputs are deliberately not 

988 anchors — see ``_classify_graph``). Every rank receives the full 

989 flattened input list, so an input consumed on several stages (an 

990 embedding's token ids reused by its backward, a mask/position ids 

991 shared by many layers) is replicated directly to each consumer with 

992 no P2P. An input consumed by NO node (an ignored kwarg — the 

993 hand-built test fixtures' ``y``, an ``epoch`` scalar train_fn never 

994 reads) is warned about and routed to the last stage, where unused 

995 inputs have always ridden. 

996 

997 Args: 

998 user_input_phs: User-input placeholders in stub arg order. 

999 node_stage: Final per-node stage assignment (fwd+bwd done). 

1000 num_stages: Total PP stage count. 

1001 

1002 Returns: 

1003 ``(primary_stages, stage_sets)`` in stub arg order. 

1004 ``primary_stages[i]`` is the first consumer stage (kept for 

1005 diagnostics and backward compatibility); ``stage_sets[i]`` is 

1006 every stage that consumes the input. 

1007 """ 

1008 primary: List[int] = [] 

1009 stage_sets: List[Tuple[int, ...]] = [] 

1010 for ph in user_input_phs: 

1011 consumer_stages = { 

1012 node_stage[u] 

1013 for u in ph.users 

1014 if u.op != "output" and node_stage.get(u) is not None 

1015 } 

1016 if not consumer_stages: 

1017 _LOG.warning( 

1018 "Model input '%s' is not consumed by the traced graph — " 

1019 "routing it to the last stage with the other unused " 

1020 "inputs (a misspelled keyword argument would leave its " 

1021 "tensor unused too)", 

1022 ph.name, 

1023 ) 

1024 consumers = (num_stages - 1,) 

1025 else: 

1026 consumers = tuple(sorted(consumer_stages)) 

1027 node_stage[ph] = consumers[0] 

1028 primary.append(consumers[0]) 

1029 stage_sets.append(consumers) 

1030 _LOG.info( 

1031 "User input '%s' routed to stages %s of %s", 

1032 ph.name, 

1033 consumers, 

1034 num_stages, 

1035 ) 

1036 return primary, stage_sets 

1037 

1038 def _classify_forward_nodes( 

1039 self, 

1040 graph: fx.Graph, 

1041 state_ph_set: Set[fx.Node], 

1042 stage_of_fqn: Dict[str, int], 

1043 num_stages: int, 

1044 node_stage: Dict[fx.Node, int], 

1045 node_phase: Dict[fx.Node, str], 

1046 ) -> None: 

1047 """Assign stages to forward nodes in topological order. 

1048 

1049 Anchors: module stack, then state-ph args, then max-args over 

1050 TENSOR args (data flows forward; shape-metadata scalars carry no 

1051 data dependency). Leftover root-level glue rides with its 

1052 consumers (reverse topo), else the last stage. 

1053 """ 

1054 floating: List[fx.Node] = [] 

1055 for node in graph.nodes: 

1056 if node.op in ("placeholder", "output"): 

1057 continue 

1058 phase = _BWD if node.meta.get("autograd_backward", False) else _FWD 

1059 if phase == _FWD: 

1060 for arg in _iter_node_args(node): 

1061 if node_phase.get(arg) == _BWD: 

1062 phase = _BWD 

1063 break 

1064 node_phase[node] = phase 

1065 if phase == _FWD: 

1066 stage = self._resolve_fwd_stage( 

1067 node, node_stage, state_ph_set, stage_of_fqn 

1068 ) 

1069 if stage is None: 

1070 floating.append(node) 

1071 else: 

1072 node_stage[node] = stage 

1073 

1074 self._assign_floating_fwd_nodes( 

1075 graph, floating, num_stages, node_stage, node_phase 

1076 ) 

1077 

1078 def _resolve_fwd_stage( 

1079 self, 

1080 node: fx.Node, 

1081 node_stage: Dict[fx.Node, int], 

1082 state_ph_set: Set[fx.Node], 

1083 stage_of_fqn: Dict[str, int], 

1084 ) -> Optional[int]: 

1085 """Resolve a forward node's stage anchor. 

1086 

1087 Priority: module stack, then state-ph args, then max-args over 

1088 TENSOR args (data flows forward; shape-metadata scalars carry no 

1089 data dependency). ``None`` means root-level glue to be resolved 

1090 from its consumers (see ``_assign_floating_fwd_nodes``). 

1091 """ 

1092 stage = self._stage_from_stack(node, stage_of_fqn) 

1093 if stage is None: 

1094 stage = self._stage_from_state_arg(node, node_stage, state_ph_set) 

1095 if stage is None: 

1096 arg_stages = _tensor_arg_stages(node, node_stage) 

1097 if arg_stages: 

1098 stage = max(arg_stages) 

1099 return stage 

1100 

1101 @staticmethod 

1102 def _assign_floating_fwd_nodes( 

1103 graph: fx.Graph, 

1104 floating: List[fx.Node], 

1105 num_stages: int, 

1106 node_stage: Dict[fx.Node, int], 

1107 node_phase: Dict[fx.Node, str], 

1108 ) -> None: 

1109 """Leftover fwd glue: consumers first (reverse topo), else last.""" 

1110 for node in reversed(list(graph.nodes)): 

1111 if node not in floating or node_phase[node] != _FWD: 

1112 continue 

1113 consumer_stages = { 

1114 node_stage[u] 

1115 for u in node.users 

1116 if u.op != "output" and node_stage.get(u) is not None 

1117 } 

1118 node_stage[node] = ( 

1119 min(consumer_stages) if consumer_stages else num_stages - 1 

1120 ) 

1121 

1122 def _classify_backward_nodes( 

1123 self, 

1124 graph: fx.Graph, 

1125 state_ph_set: Set[fx.Node], 

1126 num_stages: int, 

1127 node_stage: Dict[fx.Node, int], 

1128 node_phase: Dict[fx.Node, str], 

1129 ) -> None: 

1130 """Assign stages to backward nodes in topological order. 

1131 

1132 A bwd node runs where its earliest TENSOR input lives: gradients 

1133 born downstream are shipped down during the backward sweep, and 

1134 upstream activations arrive as replayed forward outputs. Weight- 

1135 gradient nodes that consume early activations are corrected by 

1136 the positional anchor (the param's stage owns its grad). 

1137 """ 

1138 for node in graph.nodes: 

1139 if node.op in ("placeholder", "output"): 

1140 continue 

1141 if node_phase[node] != _BWD: 

1142 continue 

1143 stage = self._stage_from_state_arg(node, node_stage, state_ph_set) 

1144 if stage is None: 

1145 arg_stages = _tensor_arg_stages(node, node_stage) 

1146 if arg_stages: 

1147 stage = min(arg_stages) 

1148 if stage is None: 

1149 # Dead-end bwd glue: ride with consumers if any, else last. 

1150 consumer_stages = { 

1151 node_stage[u] 

1152 for u in node.users 

1153 if u.op != "output" and node_stage.get(u) is not None 

1154 } 

1155 stage = min(consumer_stages) if consumer_stages else num_stages - 1 

1156 node_stage[node] = stage 

1157 

1158 def _assign_deferred_state( 

1159 self, 

1160 deferred_state: List[int], 

1161 state_phs: List[fx.Node], 

1162 state_fqns: Sequence[str], 

1163 node_stage: Dict[fx.Node, int], 

1164 owned_stages: Sequence[int], 

1165 stage_state_indices: List[int], 

1166 ) -> None: 

1167 """Assign root-level state to the stage of its (single) consumer. 

1168 

1169 Multi-stage consumption is the RoPE-cache-shaped error case and 

1170 fails with an actionable message. 

1171 """ 

1172 owned = set(owned_stages) 

1173 for idx in deferred_state: 

1174 ph = state_phs[idx] 

1175 consumer_stages = {node_stage[u] for u in ph.users if u.op != "output"} 

1176 if len(consumer_stages) > 1: 

1177 raise ValueError( 

1178 f"Root-level state '{state_fqns[idx]}' is consumed by " 

1179 f"stages {sorted(consumer_stages)} — v1 requires state " 

1180 f"to live under a single stage's module (e.g. move a " 

1181 f"shared RoPE cache under a per-stage module or split " 

1182 f"it per stage)" 

1183 ) 

1184 stage = next(iter(consumer_stages), 0) 

1185 node_stage[ph] = stage 

1186 if stage in owned: 

1187 stage_state_indices.append(idx) 

1188 _LOG.info( 

1189 "Root-level state '%s' assigned to stage %s by its consumer", 

1190 state_fqns[idx], 

1191 stage, 

1192 ) 

1193 

1194 def _state_stage(self, fqn: str, stage_of_fqn: Dict[str, int]) -> Optional[int]: 

1195 """Stage of a state entry via longest-ancestor walk over its FQN.""" 

1196 parts = fqn.split(".") 

1197 for i in range(len(parts) - 1, 0, -1): 

1198 stage = stage_of_fqn.get(".".join(parts[:i])) 

1199 if stage is not None: 

1200 return stage 

1201 return stage_of_fqn.get(fqn) 

1202 

1203 def _stage_from_stack( 

1204 self, node: fx.Node, stage_of_fqn: Dict[str, int] 

1205 ) -> Optional[int]: 

1206 """Stage from ``nn_module_stack``, innermost module first.""" 

1207 for fqn in _innermost_fqns(node): 

1208 stage = stage_of_fqn.get(fqn) 

1209 if stage is not None: 

1210 return stage 

1211 return None 

1212 

1213 def _stage_from_state_arg( 

1214 self, 

1215 node: fx.Node, 

1216 node_stage: Dict[fx.Node, int], 

1217 state_ph_set: Set[fx.Node], 

1218 ) -> Optional[int]: 

1219 """Stage from a state-placeholder argument, if any. 

1220 

1221 Post-trace inserts (FSDP collectives, weight-grad compute) reference 

1222 their owning stage's parameters — a state placeholder arg pins the 

1223 node to that stage. Generic argument inheritance is deliberately 

1224 NOT done here: it would let an early-stage argument pull a node 

1225 against the dataflow (see the max/min-args rules in 

1226 ``_classify_graph``). 

1227 """ 

1228 for arg in _iter_node_args(node): 

1229 if arg in state_ph_set: 

1230 return node_stage.get(arg) 

1231 return None 

1232 

1233 @staticmethod 

1234 def _propagate_anchor_stages( 

1235 graph_module: fx.GraphModule, 

1236 node_stage: Dict[fx.Node, int], 

1237 node_phase: Dict[fx.Node, str], 

1238 ) -> None: 

1239 """Pull bwd args up to anchored consumers (one reverse-topo pass). 

1240 

1241 A bwd value consumed by a DOWNSTREAM-stage bwd node must be 

1242 recomputed there: gradients flow downstream -> upstream, so a 

1243 downstream consumer cannot receive an upstream-born bwd value in 

1244 time (its own bwd sweep runs first). Fwd-phase args are untouched — 

1245 they arrive as replayed forward outputs; downstream-born args are 

1246 untouched — they arrive via the grad crossings. 

1247 

1248 A single REVERSE topological sweep reaches the fixpoint: a node is 

1249 visited only after every user of it has been visited and pulled it 

1250 to its final stage, so the node propagates its final value to its 

1251 own args. The previous iterate-to-fixpoint loop was quadratic in 

1252 the worst case on large joint graphs. 

1253 """ 

1254 for node in reversed(list(graph_module.graph.nodes)): 

1255 if node.op in ("placeholder", "output"): 

1256 continue 

1257 if node_phase.get(node) != _BWD: 

1258 continue 

1259 stage = node_stage.get(node) 

1260 if stage is None: 

1261 continue 

1262 for arg in _iter_node_args(node): 

1263 if node_phase.get(arg) != _BWD or node_stage.get(arg) is None: 

1264 continue 

1265 if node_stage[arg] < stage: 

1266 node_stage[arg] = stage 

1267 

1268 # ------------------------------------------------------------------ 

1269 # Boundary detection 

1270 # ------------------------------------------------------------------ 

1271 

1272 @staticmethod 

1273 def _validate_adjacent_dataflow( 

1274 graph_module: fx.GraphModule, 

1275 node_stage: Dict[fx.Node, int], 

1276 ) -> None: 

1277 """Reject skip-stage dataflow before it reaches the slice copy. 

1278 

1279 v1 ships boundary values between NEIGHBOURING stages only: a value 

1280 produced on stage ``j`` and consumed on stage ``k`` with 

1281 ``abs(j - k) > 1`` has no route (it would have to transit 

1282 intermediate stages untouched). Without this check such graphs die 

1283 later inside ``_copy_node`` / the fwd-output assembly with a 

1284 generic "outside this stage's slice" error that hides the root 

1285 cause. 

1286 

1287 Raises: 

1288 ValueError: When any producer-consumer pair spans more than 

1289 one stage cut (e.g. a dense skip connection across two 

1290 stages, or a stage plan that leaves a module's nodes to 

1291 the dataflow fallbacks). 

1292 """ 

1293 for node in graph_module.graph.nodes: 

1294 if node.op == "output": 

1295 continue 

1296 producer = node_stage.get(node) 

1297 if producer is None: 

1298 continue 

1299 for user in node.users: 

1300 if user.op == "output": 

1301 continue 

1302 consumer = node_stage.get(user) 

1303 if consumer is None or abs(consumer - producer) <= 1: 

1304 continue 

1305 raise ValueError( 

1306 f"Value '{node.name}' is produced on stage {producer} " 

1307 f"but consumed on stage {consumer}: v1 ships boundary " 

1308 f"values between neighbouring stages only. A skip " 

1309 f"connection spanning 2+ stages or a stage plan that " 

1310 f"leaves modules unattributed produces this — adjust " 

1311 f"GraphParallelPlan.pp_stage() so the dataflow crosses one cut " 

1312 f"at a time." 

1313 ) 

1314 

1315 def _anchor_grad_outputs( 

1316 self, 

1317 graph_module: fx.GraphModule, 

1318 node_stage: Dict[fx.Node, int], 

1319 stage_of_fqn: Dict[str, int], 

1320 state_fqns: Sequence[str], 

1321 model: Optional[nn.Module], 

1322 ) -> None: 

1323 """Pin each gradient-output node to its parameter's stage. 

1324 

1325 Gradient-output node i differentiates the i-th trainable parameter 

1326 (positional mapping, mirroring the tracer); it runs on the stage 

1327 owning that parameter even when min-args would place it upstream 

1328 (a later stage's weight-grad consumes an earlier stage's 

1329 activation, replayed from the forward outputs). 

1330 """ 

1331 output = next((n for n in graph_module.graph.nodes if n.op == "output"), None) 

1332 if output is None or model is None: 

1333 return 

1334 returned = output.args[0] 

1335 if not isinstance(returned, (list, tuple)): 

1336 return 

1337 state_is_param = getattr( 

1338 graph_module, "state_is_param", [True] * len(state_fqns) 

1339 ) 

1340 trainable = self._trainable_state_indices(state_fqns, state_is_param, model) 

1341 for i, grad_node in enumerate(returned[1:]): 

1342 if i >= len(trainable) or not isinstance(grad_node, fx.Node): 

1343 continue 

1344 pstage = self._state_stage(state_fqns[trainable[i]], stage_of_fqn) 

1345 if pstage is not None: 

1346 node_stage[grad_node] = pstage 

1347 

1348 def _find_boundaries( # pylint: disable=too-many-locals 

1349 self, 

1350 graph_module: fx.GraphModule, 

1351 node_stage: Dict[fx.Node, int], 

1352 node_phase: Dict[fx.Node, str], 

1353 num_stages: int, 

1354 stage_idx: int, 

1355 user_input_phs: Sequence[fx.Node], 

1356 user_input_stage_sets: Sequence[Sequence[int]], 

1357 ) -> _Boundaries: 

1358 """Locate the value lists crossing this virtual stage's cuts. 

1359 

1360 Returns: 

1361 The ``_Boundaries`` lists, all in joint-graph topological order 

1362 so the producer and consumer of a cut agree on P2P ordering. 

1363 See ``_Boundaries`` for the per-field semantics. 

1364 """ 

1365 k = stage_idx 

1366 is_last = k == num_stages - 1 

1367 nodes = [ 

1368 n for n in graph_module.graph.nodes if n.op not in ("placeholder", "output") 

1369 ] 

1370 

1371 def crossing( 

1372 producer: int, consumer: int, phase: Optional[str] 

1373 ) -> List[fx.Node]: 

1374 """Values produced by one stage and consumed by another. 

1375 

1376 ``phase=None`` matches any phase (backward crossings may carry 

1377 gradients as well as functionalized fwd views). 

1378 """ 

1379 found = [] 

1380 for v in nodes: 

1381 if node_stage[v] != producer: 

1382 continue 

1383 if phase is not None and node_phase[v] != phase: 

1384 continue 

1385 if any(node_stage.get(u) == consumer for u in v.users): 

1386 found.append(v) 

1387 return found 

1388 

1389 # FWD-phase only: values born in this stage's forward sweep and 

1390 # consumed downstream. Bwd-phase values cannot ship forward (they 

1391 # do not exist yet during the forward sweep); downstream-born 

1392 # gradients flow back via grad crossings below. 

1393 act_in_list = crossing(k - 1, k, _FWD) if k > 0 else [] 

1394 act_out_list = [] if is_last else crossing(k, k + 1, _FWD) 

1395 # Backward crossings are phase-AGNOSTIC: besides plain gradients, 

1396 # functionalized views (fwd nodes) can be consumed by an earlier 

1397 # stage's backward (weight-grad compute) — those values flow back 

1398 # during the backward sweep just the same. 

1399 grad_in_list = [] if is_last else crossing(k + 1, k, None) 

1400 grad_out_list = crossing(k, k - 1, None) if k > 0 else [] 

1401 

1402 # Forward-phase values the backward references. Stage-owned 

1403 # placeholders (state / routed user inputs of this stage) may appear 

1404 # and round-trip through the forward outputs; foreign placeholders 

1405 # cannot be shipped and fail loudly during the slice copy. 

1406 stage_owned_phs = { 

1407 p 

1408 for p in graph_module.graph.nodes 

1409 if p.op == "placeholder" and node_stage.get(p) == k 

1410 } 

1411 stage_owned_phs.update( 

1412 ph 

1413 for ph, stages in zip(user_input_phs, user_input_stage_sets) 

1414 if k in stages 

1415 ) 

1416 saved = self._collect_saved_values( 

1417 nodes, 

1418 node_stage, 

1419 node_phase, 

1420 k, 

1421 stage_owned_phs, 

1422 set(act_in_list), 

1423 grad_out_list, 

1424 ) 

1425 return _Boundaries( 

1426 act_in=act_in_list, 

1427 act_out=act_out_list, 

1428 grad_in=grad_in_list, 

1429 grad_out=grad_out_list, 

1430 saved=saved, 

1431 ) 

1432 

1433 @staticmethod 

1434 def _collect_saved_values( 

1435 nodes: List[fx.Node], 

1436 node_stage: Dict[fx.Node, int], 

1437 node_phase: Dict[fx.Node, str], 

1438 stage_idx: int, 

1439 stage_owned_phs: Set[fx.Node], 

1440 act_in_set: Set[fx.Node], 

1441 grad_out_list: List[fx.Node], 

1442 ) -> List[fx.Node]: 

1443 """Forward-phase values this stage's backward references. 

1444 

1445 Stage-owned placeholders (state / routed user inputs of this stage) 

1446 may appear and round-trip through the forward outputs; foreign 

1447 placeholders cannot be shipped and fail loudly during the slice 

1448 copy. Fwd-phase values this stage must ship BACKWARD (consumed by 

1449 the previous stage's backward) ride the fwd outputs as 

1450 pass-throughs: computed once in the fwd subgraph, replayed into 

1451 the bwd subgraph, and appended to its outputs. 

1452 """ 

1453 saved: List[fx.Node] = [] 

1454 seen: Set[fx.Node] = set() 

1455 for node in nodes: 

1456 if node_phase[node] != _BWD or node_stage[node] != stage_idx: 

1457 continue 

1458 for arg in _iter_node_args(node): 

1459 if not isinstance(arg, fx.Node) or arg in seen: 

1460 continue 

1461 # Fwd-phase values replay from the fwd outputs; bwd-phase 

1462 # values are only shippable when they arrived as boundary 

1463 # inputs (e.g. gradient-shape sym_size scalars). 

1464 if node_phase.get(arg) != _FWD and arg not in act_in_set: 

1465 continue 

1466 if arg.op == "placeholder" and arg not in stage_owned_phs: 

1467 continue 

1468 seen.add(arg) 

1469 saved.append(arg) 

1470 for v in grad_out_list: 

1471 if node_phase[v] == _FWD and v not in seen: 

1472 seen.add(v) 

1473 saved.append(v) 

1474 return saved 

1475 

1476 # ------------------------------------------------------------------ 

1477 # Subgraph construction 

1478 # ------------------------------------------------------------------ 

1479 

1480 @staticmethod 

1481 def _unique(name: str, used: Set[str]) -> str: 

1482 """Return ``name`` (or a suffixed variant) not yet in ``used``.""" 

1483 candidate = name 

1484 suffix = 1 

1485 while candidate in used: 

1486 candidate = f"{name}_{suffix}" 

1487 suffix += 1 

1488 used.add(candidate) 

1489 return candidate 

1490 

1491 def _copy_node( 

1492 self, 

1493 builder: _SubgraphBuilder, 

1494 node: fx.Node, 

1495 ) -> None: 

1496 """Copy ``node`` into ``builder.g``, remapping args through the 

1497 builder's env/foreign maps. 

1498 

1499 ``env`` maps already-copied same-slice nodes; ``foreign`` maps 

1500 boundary values to their placeholder stand-ins. The copy is 

1501 registered under ``builder.env[node]``; nothing is returned — 

1502 callers consume the copy through the builder's maps. 

1503 """ 

1504 if node.op == "get_attr": 

1505 raise ValueError( 

1506 f"Unexpected get_attr node '{node.name}' — the tracer " 

1507 f"contracts parameters/buffers to be static placeholders" 

1508 ) 

1509 

1510 def map_fn(a: Any) -> Any: 

1511 """Remap a single arg: env first, then foreign placeholders.""" 

1512 if isinstance(a, fx.Node): 

1513 if a in builder.env: 

1514 return builder.env[a] 

1515 if a in builder.foreign: 

1516 return builder.foreign[a] 

1517 raise ValueError( 

1518 f"Node '{node.name}' references '{a.name}' which lies " 

1519 f"outside this stage's slice — boundary detection or " 

1520 f"the stage plan is inconsistent" 

1521 ) 

1522 return a 

1523 

1524 new_args = fx.map_arg(node.args, map_fn) 

1525 new_kwargs = fx.map_arg(node.kwargs, map_fn) 

1526 new_node = builder.g.create_node(node.op, node.target, new_args, new_kwargs) 

1527 new_node.meta = dict(node.meta) 

1528 builder.env[node] = new_node 

1529 

1530 def _build_fwd_graph( 

1531 self, 

1532 graph_module: fx.GraphModule, 

1533 split: _StageSplit, 

1534 boundaries: _Boundaries, 

1535 stage_idx: int, 

1536 num_stages: int, 

1537 state_indices: Sequence[int], 

1538 state_fqns: Sequence[str], 

1539 ) -> Tuple[fx.GraphModule, List[fx.Node]]: 

1540 """Build one virtual stage's forward subgraph. 

1541 

1542 Outputs: ``(*act_out, *saved)`` for non-last stages, ``(loss, 

1543 *saved)`` for the last stage — where ``saved`` contains every 

1544 forward-phase value the backward references that is not already 

1545 crossing. The schedule ships the crossing prefix and replays the 

1546 full output tuple into the backward subgraph. 

1547 

1548 Returns: 

1549 ``(fwd_gm, fwd_out_orig)`` — the subgraph module together with 

1550 the ORIGINAL nodes at each output position, so the backward 

1551 builder can key its placeholder mapping on them. 

1552 """ 

1553 is_last = stage_idx == num_stages - 1 

1554 builder = _SubgraphBuilder(g=fx.Graph(), used=set(), env={}, foreign={}) 

1555 

1556 self._create_fwd_placeholders( 

1557 builder, split, boundaries, stage_idx, state_indices, state_fqns 

1558 ) 

1559 

1560 for node in graph_module.graph.nodes: 

1561 if node.op in ("placeholder", "output"): 

1562 continue 

1563 if split.node_phase[node] != _FWD or split.node_stage[node] != stage_idx: 

1564 continue 

1565 self._copy_node(builder, node) 

1566 

1567 loss_node = self._loss_node(graph_module) 

1568 out_orig = self._resolve_fwd_outputs( 

1569 boundaries.act_out, boundaries.saved, loss_node, is_last 

1570 ) 

1571 out_nodes = [ 

1572 builder.env[n] if n in builder.env else builder.foreign[n] for n in out_orig 

1573 ] 

1574 builder.g.output(tuple(out_nodes)) 

1575 return fx.GraphModule(nn.Module(), builder.g), out_orig 

1576 

1577 def _create_fwd_placeholders( 

1578 self, 

1579 builder: _SubgraphBuilder, 

1580 split: _StageSplit, 

1581 boundaries: _Boundaries, 

1582 stage_idx: int, 

1583 state_indices: Sequence[int], 

1584 state_fqns: Sequence[str], 

1585 ) -> None: 

1586 """Create the fwd subgraph's placeholders (state / boundary / inputs). 

1587 

1588 Incoming boundary values (virtual stage > 0) become placeholders; 

1589 each stage additionally takes the user inputs routed to it (stage 0 

1590 typically the feature batch, the last stage the labels; see 

1591 ``_route_user_inputs``). 

1592 """ 

1593 for i, orig_idx in enumerate(state_indices): 

1594 ph = builder.g.placeholder( 

1595 self._unique(_sanitize(state_fqns[i]), builder.used) 

1596 ) 

1597 ph.meta = dict(split.state_phs[orig_idx].meta) 

1598 builder.env[split.state_phs[orig_idx]] = ph 

1599 

1600 for i, act in enumerate(boundaries.act_in): 

1601 ph = builder.g.placeholder(self._unique(f"pp_act_in_{i}", builder.used)) 

1602 ph.meta = dict(act.meta) 

1603 builder.foreign[act] = ph 

1604 

1605 for i, (ph, stages) in enumerate( 

1606 zip(split.user_input_phs, split.user_input_stage_sets) 

1607 ): 

1608 if stage_idx not in stages: 

1609 continue 

1610 in_ph = builder.g.placeholder(self._unique(f"pp_input_{i}", builder.used)) 

1611 in_ph.meta = dict(ph.meta) 

1612 builder.env[ph] = in_ph 

1613 

1614 @staticmethod 

1615 def _resolve_fwd_outputs( 

1616 act_out_list: List[fx.Node], 

1617 saved: List[fx.Node], 

1618 loss_node: Optional[fx.Node], 

1619 is_last: bool, 

1620 ) -> List[fx.Node]: 

1621 """Order the fwd subgraph's outputs: boundary values first, then saved.""" 

1622 if is_last: 

1623 if loss_node is None: 

1624 raise ValueError("Last PP stage requires a loss node in the output") 

1625 out_orig: List[fx.Node] = [loss_node] 

1626 else: 

1627 if not act_out_list: 

1628 raise ValueError( 

1629 "Stage ships no boundary values but is not the last " 

1630 "stage — the stage plan does not cut the graph" 

1631 ) 

1632 out_orig = list(act_out_list) 

1633 

1634 crossing_ids = {id(v) for v in act_out_list} 

1635 for node in saved: 

1636 if id(node) in crossing_ids or (is_last and node is loss_node): 

1637 continue 

1638 out_orig.append(node) 

1639 return out_orig 

1640 

1641 def _build_bwd_graph( 

1642 self, 

1643 graph_module: fx.GraphModule, 

1644 split: _StageSplit, 

1645 boundaries: _Boundaries, 

1646 stage_idx: int, 

1647 num_stages: int, 

1648 state_indices: Sequence[int], 

1649 state_fqns: Sequence[str], 

1650 fwd_out_orig: List[fx.Node], 

1651 trainable_indices: List[int], 

1652 ) -> fx.GraphModule: 

1653 """Build one virtual stage's backward subgraph. 

1654 

1655 Placeholders: ``(*state, *grad_in, *fwd_outputs)`` — the schedule 

1656 passes the received boundary gradients and then the forward 

1657 outputs verbatim (on the last stage a single ``ones_like(loss)`` 

1658 takes the gradient slots' place). Outputs: ``(*param_grads,)`` 

1659 plus the boundary gradients for every stage except stage 0. 

1660 """ 

1661 builder = _SubgraphBuilder(g=fx.Graph(), used=set(), env={}, foreign={}) 

1662 self._create_bwd_placeholders( 

1663 builder, 

1664 graph_module, 

1665 split, 

1666 boundaries, 

1667 stage_idx, 

1668 num_stages, 

1669 state_indices, 

1670 state_fqns, 

1671 fwd_out_orig, 

1672 ) 

1673 

1674 stage_bwd_set = self._collect_stage_bwd_nodes( 

1675 graph_module.graph, split.node_stage, split.node_phase, stage_idx 

1676 ) 

1677 

1678 # Gradient-output nodes of this stage's trainable params (by state 

1679 # index identity, not module attribution — post-trace inserts like 

1680 # zeros_like carry no module stack). A LIST — output order is the 

1681 # positional gradient contract; only membership uses the set. 

1682 stage_grad_nodes = self._stage_grad_nodes( 

1683 graph_module.graph, trainable_indices, set(state_indices) 

1684 ) 

1685 stage_grad_set = set(stage_grad_nodes) 

1686 

1687 for node in graph_module.graph.nodes: 

1688 if node.op in ("placeholder", "output"): 

1689 continue 

1690 if node not in stage_bwd_set and node not in stage_grad_set: 

1691 continue 

1692 self._copy_node(builder, node) 

1693 

1694 out_nodes = [builder.env[gn] for gn in stage_grad_nodes] 

1695 out_nodes.extend(builder.env[gn] for gn in boundaries.grad_out) 

1696 builder.g.output(tuple(out_nodes)) 

1697 return fx.GraphModule(nn.Module(), builder.g) 

1698 

1699 @staticmethod 

1700 def _collect_stage_bwd_nodes( 

1701 graph: fx.Graph, 

1702 node_stage: Dict[fx.Node, int], 

1703 node_phase: Dict[fx.Node, str], 

1704 stage_idx: int, 

1705 ) -> Set[fx.Node]: 

1706 """Bwd-phase nodes owned by ``stage_idx``, as a set. 

1707 

1708 Membership is probed once per graph node by ``_build_bwd_graph`` 

1709 and real joint graphs carry tens of thousands of nodes. 

1710 """ 

1711 return { 

1712 node 

1713 for node in graph.nodes 

1714 if node.op not in ("placeholder", "output") 

1715 and node_phase[node] == _BWD 

1716 and node_stage[node] == stage_idx 

1717 } 

1718 

1719 def _create_bwd_placeholders( 

1720 self, 

1721 builder: _SubgraphBuilder, 

1722 graph_module: fx.GraphModule, 

1723 split: _StageSplit, 

1724 boundaries: _Boundaries, 

1725 stage_idx: int, 

1726 num_stages: int, 

1727 state_indices: Sequence[int], 

1728 state_fqns: Sequence[str], 

1729 fwd_out_orig: List[fx.Node], 

1730 ) -> None: 

1731 """Create the bwd subgraph's placeholders (state / grads / fwd outs). 

1732 

1733 The schedule passes the received boundary gradients and then the 

1734 forward outputs verbatim (on the last stage a single 

1735 ``ones_like(loss)`` takes the gradient slots' place). The 

1736 ``foreign`` entries double as the remap for backward nodes 

1737 referencing forward values. 

1738 """ 

1739 for i, orig_idx in enumerate(state_indices): 

1740 ph = builder.g.placeholder( 

1741 self._unique(_sanitize(state_fqns[i]), builder.used) 

1742 ) 

1743 ph.meta = dict(split.state_phs[orig_idx].meta) 

1744 builder.env[split.state_phs[orig_idx]] = ph 

1745 

1746 for i, grad in enumerate(boundaries.grad_in): 

1747 ph = builder.g.placeholder(self._unique(f"pp_grad_in_{i}", builder.used)) 

1748 ph.meta = dict(grad.meta) 

1749 builder.foreign[grad] = ph 

1750 if not boundaries.grad_in and stage_idx == num_stages - 1: 

1751 # Last stage: the schedule feeds ones_like(loss) into the 

1752 # single gradient slot. 

1753 ph = builder.g.placeholder(self._unique("pp_grad_ones", builder.used)) 

1754 loss = self._loss_node(graph_module) 

1755 if loss is not None: 

1756 ph.meta = dict(loss.meta) 

1757 

1758 # One placeholder per forward output, same order — the schedule 

1759 # passes the forward outputs verbatim after the gradients. 

1760 for orig in fwd_out_orig: 

1761 ph = builder.g.placeholder( 

1762 self._unique(f"pp_fwd_{orig.name}", builder.used) 

1763 ) 

1764 ph.meta = dict(orig.meta) 

1765 builder.foreign[orig] = ph 

1766 

1767 @staticmethod 

1768 def _stage_grad_nodes( 

1769 graph: fx.Graph, trainable_indices: List[int], stage_state_set: Set[int] 

1770 ) -> List[fx.Node]: 

1771 """Gradient-output nodes of the stage's trainable params.""" 

1772 output = next((n for n in graph.nodes if n.op == "output"), None) 

1773 returned = output.args[0] if output is not None else [] 

1774 stage_grad_nodes: List[fx.Node] = [] 

1775 for i, grad_node in enumerate(returned[1:]): 

1776 if i >= len(trainable_indices): 

1777 break 

1778 if trainable_indices[i] in stage_state_set: 

1779 stage_grad_nodes.append(grad_node) 

1780 return stage_grad_nodes 

1781 

1782 # ------------------------------------------------------------------ 

1783 # Live model pruning 

1784 # ------------------------------------------------------------------ 

1785 

1786 def _prune_live_model(self, model: nn.Module, keep_fqns: List[str]) -> None: 

1787 """Remove foreign-stage submodules from the live model in place. 

1788 

1789 Mirrors torchtitan's ``_split_module`` (``None``-out unkept 

1790 children, filter ModuleList/ModuleDict entries) while PRESERVING 

1791 original index keys — reindexing a ModuleList would rename the 

1792 surviving parameters' FQNs and break ``run_traced_graph``'s state 

1793 validation against the sliced ``state_fqns``. Manual plans may cut 

1794 inside a container element; such elements are recursed into 

1795 (mixed subtree), exactly like plain modules. 

1796 """ 

1797 keep = set(keep_fqns) 

1798 

1799 def is_kept(fqn: str) -> bool: 

1800 """True when ``fqn`` equals or descends from a stage module.""" 

1801 return any(fqn == kf or fqn.startswith(kf + ".") for kf in keep) 

1802 

1803 def prune_container_child(child: nn.Module, cfqn: str) -> None: 

1804 """Prune a ModuleList/ModuleDict child, preserving index keys. 

1805 

1806 Reindexing would rename the surviving parameters' FQNs and break 

1807 ``run_traced_graph``'s state validation. An element is kept 

1808 whole, deleted, or recursed into when a manual plan cuts inside 

1809 it (same rule as plain modules). 

1810 """ 

1811 children = child._modules # pylint: disable=protected-access 

1812 keys = list(children.keys()) 

1813 if all(is_kept(f"{cfqn}.{key}") for key in keys): 

1814 return 

1815 for key in keys: 

1816 elem_fqn = f"{cfqn}.{key}" 

1817 if is_kept(elem_fqn): 

1818 continue 

1819 elem = children[key] 

1820 descendants = [f for f, _ in elem.named_modules() if f] 

1821 if any(is_kept(f"{elem_fqn}.{f}") for f in descendants): 

1822 prune(elem, elem_fqn + ".") 

1823 else: 

1824 del children[key] 

1825 

1826 def prune_plain_child( 

1827 mod: nn.Module, name: str, child: nn.Module, cfqn: str 

1828 ) -> None: 

1829 """Prune a non-container child: delete it or recurse when mixed.""" 

1830 descendants = [f for f, _ in child.named_modules() if f] 

1831 if not descendants: 

1832 # Leaf module (e.g. a bare Linear): keep only if declared. 

1833 if not is_kept(cfqn): 

1834 setattr(mod, name, None) 

1835 return 

1836 if not any(is_kept(f"{cfqn}.{f}") for f in descendants): 

1837 setattr(mod, name, None) 

1838 else: 

1839 # Mixed subtree (manual plans may cut inside a child). 

1840 prune(child, cfqn + ".") 

1841 

1842 def prune(mod: nn.Module, prefix: str) -> None: 

1843 """Recursively prune non-stage children under ``prefix``.""" 

1844 for name, child in list(mod.named_children()): 

1845 cfqn = f"{prefix}{name}" 

1846 if is_kept(cfqn): 

1847 # Declared (or ancestor of a declared) stage module — 

1848 # keep the whole subtree. 

1849 continue 

1850 if isinstance(child, (nn.ModuleList, nn.ModuleDict)): 

1851 prune_container_child(child, cfqn) 

1852 continue 

1853 prune_plain_child(mod, name, child, cfqn) 

1854 

1855 prune(model, "") 

1856 

1857 # ------------------------------------------------------------------ 

1858 # Schedule + stub installation 

1859 # ------------------------------------------------------------------ 

1860 

1861 def _trainable_state_indices( 

1862 self, 

1863 state_fqns: Sequence[str], 

1864 state_is_param: Sequence[bool], 

1865 model: Optional[nn.Module], 

1866 ) -> List[int]: 

1867 """Trainable-parameter state indices, mirroring the tracer's order.""" 

1868 param_lookup = ( 

1869 dict(model.named_parameters(remove_duplicate=False)) 

1870 if model is not None 

1871 else {} 

1872 ) 

1873 trainable: List[int] = [] 

1874 for idx, fqn in enumerate(state_fqns): 

1875 if idx < len(state_is_param) and not state_is_param[idx]: 

1876 continue 

1877 param = param_lookup.get(fqn) 

1878 if param is not None and param.requires_grad: 

1879 trainable.append(idx) 

1880 return trainable 

1881 

1882 @staticmethod 

1883 def _value_spec( 

1884 nodes: Sequence[fx.Node], stage_idx: int, kind: str 

1885 ) -> List[Tuple[Any, ...]]: 

1886 """Build the schedule's recv descriptor for a boundary value list. 

1887 

1888 Tensor values yield ``("tensor", shape, dtype, device)``; int/SymInt 

1889 scalars (dynamic-shape ``sym_size`` nodes) yield ``("scalar",)`` 

1890 and are shipped as 0-d int64 tensors, unwrapped via ``item()``. 

1891 Scalars carry no device of their own — the schedule anchors them to 

1892 the first tensor entry's device, so a non-empty list must contain 

1893 at least one tensor. 

1894 """ 

1895 spec: List[Tuple[Any, ...]] = [] 

1896 for v in nodes: 

1897 val = v.meta.get("val") 

1898 if isinstance(val, torch.Tensor): 

1899 # int(s): trace-time dims are SymInts (symbolic over the 

1900 # sample input); the schedule allocates real buffers from 

1901 # this spec, and ATen rejects symbolic sizes at runtime. 

1902 # Training uses static shapes per compile, so the hinted 

1903 # concrete values are stable. 

1904 shape = tuple(int(s) for s in val.shape) 

1905 spec.append(("tensor", shape, val.dtype, val.device)) 

1906 elif val is None: 

1907 raise ValueError( 

1908 f"Boundary {kind} value '{v.name}' on stage {stage_idx} " 

1909 f"has no 'val' meta (traced without FakeTensor " 

1910 f"metadata) — cannot size the P2P receive buffer" 

1911 ) 

1912 else: 

1913 spec.append(("scalar",)) 

1914 if nodes and not any(entry[0] == "tensor" for entry in spec): 

1915 raise ValueError( 

1916 f"Boundary {kind} list on stage {stage_idx} carries only " 

1917 f"scalar values — no tensor entry to anchor the P2P " 

1918 f"receive device on" 

1919 ) 

1920 return spec 

1921 

1922 def _build_schedule( 

1923 self, 

1924 stage_graphs: Sequence[_StageGraphs], 

1925 pass_config: PassConfig, 

1926 run_ctx: _RunContext, 

1927 split: _StageSplit, 

1928 trainable_indices: Sequence[int], 

1929 state_positions: Dict[int, int], 

1930 ) -> PipelineScheduleBase: 

1931 """Assemble this rank's pipeline schedule (``pass_config.pp_schedule``). 

1932 

1933 Receive descriptors come from the boundary values' fake-tensor 

1934 ``val`` metas; the send side packs by value type at runtime. The 

1935 single-stage schedules take one graph pair; the interleaved schedule 

1936 takes every virtual stage this rank owns. 

1937 """ 

1938 schedule_cls = get_schedule_class(pass_config.pp_schedule) 

1939 if issubclass(schedule_cls, ScheduleInterleaved1F1B): 

1940 return self._build_interleaved_schedule( 

1941 schedule_cls, 

1942 stage_graphs, 

1943 pass_config, 

1944 run_ctx, 

1945 split, 

1946 trainable_indices, 

1947 state_positions, 

1948 ) 

1949 if run_ctx.chunks != 1: 

1950 raise ValueError( 

1951 f"pp_chunks={run_ctx.chunks} requires the interleaved " 

1952 f"schedule, got {pass_config.pp_schedule!r}" 

1953 ) 

1954 return self._build_single_stage_schedule( 

1955 schedule_cls, 

1956 stage_graphs[0], 

1957 pass_config, 

1958 run_ctx, 

1959 split, 

1960 ) 

1961 

1962 def _build_single_stage_schedule( 

1963 self, 

1964 schedule_cls: Any, 

1965 stage: _StageGraphs, 

1966 pass_config: PassConfig, 

1967 run_ctx: _RunContext, 

1968 split: _StageSplit, 

1969 ) -> PipelineScheduleBase: 

1970 """Build one of the single-virtual-stage schedules (GPipe / 1F1B).""" 

1971 boundaries = stage.boundaries 

1972 stage_idx = stage.stage_idx 

1973 recv_spec = ( 

1974 self._value_spec(boundaries.act_in, stage_idx, "activation") 

1975 if stage_idx > 0 

1976 else [] 

1977 ) 

1978 grad_recv_spec = ( 

1979 self._value_spec(boundaries.grad_in, stage_idx, "gradient") 

1980 if stage_idx < run_ctx.num_stages - 1 

1981 else [] 

1982 ) 

1983 return schedule_cls( 

1984 stage.fwd_gm, 

1985 stage.bwd_gm, 

1986 stage_idx=stage_idx, 

1987 pp_degree=run_ctx.num_stages, 

1988 num_state=len(split.stage_state_fqns), 

1989 num_trainable=stage.num_trainable, 

1990 num_send=len(boundaries.act_out), 

1991 grad_send_count=len(boundaries.grad_out), 

1992 microbatch_size=pass_config.pp_microbatch_size, 

1993 pp_group=run_ctx.group, 

1994 recv_spec=recv_spec, 

1995 grad_recv_spec=grad_recv_spec, 

1996 user_input_stages=split.user_input_stages, 

1997 user_input_stage_sets=split.user_input_stage_sets, 

1998 ) 

1999 

2000 def _build_interleaved_schedule( # pylint: disable=too-many-locals 

2001 self, 

2002 schedule_cls: Any, 

2003 stage_graphs: Sequence[_StageGraphs], 

2004 pass_config: PassConfig, 

2005 run_ctx: _RunContext, 

2006 split: _StageSplit, 

2007 trainable_indices: Sequence[int], 

2008 state_positions: Dict[int, int], 

2009 ) -> PipelineScheduleBase: 

2010 """Build the VPP schedule from this rank's virtual-stage graph list.""" 

2011 owned_pos = {v: i for i, v in enumerate(run_ctx.stage_indices)} 

2012 grad_owner = [ 

2013 owned_pos[split.node_stage[split.state_phs[idx]]] 

2014 for idx in trainable_indices 

2015 if idx in state_positions 

2016 ] 

2017 state_positions_per_stage = [ 

2018 [state_positions[i] for i in stage.state_indices] for stage in stage_graphs 

2019 ] 

2020 recv_specs = [ 

2021 self._recv_spec_for(stage, run_ctx.num_stages, gradient=False) 

2022 for stage in stage_graphs 

2023 ] 

2024 grad_recv_specs = [ 

2025 self._recv_spec_for(stage, run_ctx.num_stages, gradient=True) 

2026 for stage in stage_graphs 

2027 ] 

2028 return schedule_cls( 

2029 [stage.fwd_gm for stage in stage_graphs], 

2030 [stage.bwd_gm for stage in stage_graphs], 

2031 stage_indices=list(run_ctx.stage_indices), 

2032 num_stages=run_ctx.num_stages, 

2033 pp_degree=run_ctx.pp_degree, 

2034 state_positions=state_positions_per_stage, 

2035 num_states=[len(stage.state_indices) for stage in stage_graphs], 

2036 num_trainables=[stage.num_trainable for stage in stage_graphs], 

2037 num_sends=[len(stage.boundaries.act_out) for stage in stage_graphs], 

2038 grad_send_counts=[len(stage.boundaries.grad_out) for stage in stage_graphs], 

2039 microbatch_size=pass_config.pp_microbatch_size, 

2040 pp_group=run_ctx.group, 

2041 recv_specs=recv_specs, 

2042 grad_recv_specs=grad_recv_specs, 

2043 user_input_stages=split.user_input_stages, 

2044 user_input_stage_sets=split.user_input_stage_sets, 

2045 grad_owner=grad_owner, 

2046 ) 

2047 

2048 def _recv_spec_for( 

2049 self, 

2050 stage: _StageGraphs, 

2051 num_stages: int, 

2052 gradient: bool, 

2053 ) -> List[Tuple[Any, ...]]: 

2054 """Build one virtual stage's activation or gradient receive specs.""" 

2055 if gradient: 

2056 if stage.stage_idx >= num_stages - 1: 

2057 return [] 

2058 return self._value_spec( 

2059 stage.boundaries.grad_in, stage.stage_idx, "gradient" 

2060 ) 

2061 if stage.stage_idx == 0: 

2062 return [] 

2063 return self._value_spec(stage.boundaries.act_in, stage.stage_idx, "activation") 

2064 

2065 def _install_stub( 

2066 self, 

2067 graph_module: fx.GraphModule, 

2068 sched: PipelineScheduleBase, 

2069 stage_state_fqns: List[str], 

2070 state_is_param: Sequence[bool], 

2071 stage_state_indices: List[int], 

2072 num_user_inputs: int, 

2073 ) -> None: 

2074 """Rewrite the graph module into a schedule-dispatching stub. 

2075 

2076 The schedule is added as a submodule and invoked through a 

2077 ``call_module`` node, so it survives any later ``recompile()`` and 

2078 the trainer's ``graph_module(*flat_inputs)`` dispatches to it 

2079 unchanged. The stub takes ``(*state, *user_inputs)`` — every rank 

2080 receives the full flattened user-input list; the schedule picks 

2081 the inputs routed to this stage. ``state_fqns`` / 

2082 ``state_is_param`` are updated IN PLACE (the JointGraph shares the 

2083 list objects). 

2084 """ 

2085 g = fx.Graph() 

2086 used: Set[str] = set() 

2087 state_phs = [ 

2088 g.placeholder(self._unique(_sanitize(fqn), used)) 

2089 for fqn in stage_state_fqns 

2090 ] 

2091 user_phs = [ 

2092 g.placeholder(self._unique(f"pp_input_{i}", used)) 

2093 for i in range(num_user_inputs) 

2094 ] 

2095 

2096 graph_module.add_module("pp_schedule", sched) 

2097 call = g.call_module("pp_schedule", args=tuple(state_phs) + tuple(user_phs)) 

2098 g.output(call) 

2099 

2100 graph_module.graph = g 

2101 graph_module.state_fqns[:] = stage_state_fqns 

2102 graph_module.state_is_param[:] = [ 

2103 state_is_param[i] for i in stage_state_indices 

2104 ] 

2105 graph_module.num_state_inputs = len(stage_state_fqns) 

2106 graph_module.recompile()