Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / compiler.py: 92%

621 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""" 

16Graph Compiler - compile a model into a parallel graph and run fwd+bwd. 

17 

18Compiler surface of the graph-mode stack: 

19 

20- ``compile`` traces the model into a joint forward+backward FX graph and 

21 runs the partitioning passes (FSDP / PP / overlap) on it. 

22- ``forward_backward`` executes the compiled graph against the live model 

23 state and deposits gradients into ``param.grad`` (accumulating, so several 

24 micro-batch calls may run before the caller's optimizer step). 

25 

26Training-policy concerns (optimizer, dataloader loop, logging, batch device 

27placement) are deliberately out of scope: ``GraphTrainer`` composes this 

28class and owns them. 

29""" 

30 

31from __future__ import annotations 

32 

33__all__ = ["GraphCompiler"] 

34 

35import logging 

36import math 

37from copy import copy 

38from typing import Any, Callable, Dict, List, Optional, Tuple 

39 

40import torch 

41import torch.distributed as dist 

42from torch._prims_common import make_contiguous_strides_for 

43from torch.distributed.distributed_c10d import _register_process_group 

44 

45from hyper_parallel.core.dtensor.device_mesh import DeviceMesh, init_device_mesh 

46from hyper_parallel.core.dtensor.layout import Layout 

47from hyper_parallel.core.dtensor.placement_types import Replicate, Shard, StridedShard 

48from hyper_parallel.distributed._builder.fsdp_adapter import FSDP2Manager 

49from hyper_parallel.distributed.mesh import MeshContext 

50from hyper_parallel.models.build_options import FSDP2Config, get_device_type 

51from hyper_parallel.models.external_state import get_model_external_state 

52 

53from . import checkpoint_metadata, optimizer_state 

54from .graph_parallel_plan import GraphParallelPlan 

55from .mixed_precision import GraphMixedPrecision 

56from .pass_config import ( 

57 GradientReduction, 

58 PassConfig, 

59 build_pass_config_from_trainer_config, 

60 normalize_dp_mode, 

61) 

62from .passes.pipeline import PassPipeline 

63from .passes.inductor_pass import validate_inductor_backend 

64from .passes.parallel.fsdp_pass import FsdpParamSpec, FsdpPlan 

65from .passes.activation_checkpoint import prepare_activation_checkpoint 

66from .passes.aclgraph_runtime import teardown_aclgraph 

67from .tracer.dynamic_shapes import normalize_dynamic_arg_dims 

68from .tracer.graph_tracer import run_traced_graph, trace_model_graph 

69 

70_LOG = logging.getLogger(__name__) 

71 

72 

73class GraphCompiler: 

74 """ 

75 Graph-mode Compiler 

76 

77 Users provide model code and parallel configuration. 

78 The compiler handles graph capture and all parallel logic 

79 (FSDP / PP / overlap passes), then runs forward+backward per step. 

80 """ 

81 

82 def __init__( 

83 self, 

84 model: torch.nn.Module, 

85 train_fn: Callable, 

86 pass_config: Optional[PassConfig] = None, 

87 parallel_plan: Optional[GraphParallelPlan] = None, 

88 trainer_config: Optional[Any] = None, 

89 device: Optional[torch.device] = None, 

90 mesh_context: Optional[Any] = None, 

91 dynamic: Optional[bool] = None, 

92 dynamic_arg_dims: dict[str, int | list[int]] | None = None, 

93 source_shard_info: Optional[dict] = None, 

94 ) -> None: 

95 """ 

96 Args: 

97 model: Model to compile 

98 train_fn: Training function signature: (model, input, label) -> loss 

99 pass_config: Parallel configuration. When omitted, the compiler 

100 projects ``trainer_config`` onto a graph-mode ``PassConfig``; 

101 if both are omitted, it uses ``PassConfig()``. 

102 parallel_plan: GraphParallelPlan declaring which modules to shard 

103 (optional; enables declarative sharding) 

104 trainer_config: Optional trainer topology used only to infer a 

105 default ``PassConfig`` when ``pass_config`` is omitted. 

106 device: Device to place the model and run the graph on. Defaults 

107 to the available accelerator (CUDA/NPU), otherwise CPU. 

108 mesh_context: Optional automodel ``MeshContext`` carrying the 

109 pre-built parallel meshes. Model forwards retain their TP/EP 

110 groups; the compiler registers the dense shard sub-mesh under 

111 ``"fsdp"``, the expert EDP shard sub-mesh under 

112 ``"fsdp_expert"``, and (when the expert mesh replicates) the 

113 expert EDP replicate sub-mesh under ``"fsdp_expert_replicate"``. 

114 dynamic: Symbolize user input dimensions; inherits trainer_config.compile.dynamic when omitted. 

115 dynamic_arg_dims: Optional dotted input paths to dynamic dimensions, e.g. {"x": [0, 1]}. 

116 Overrides automatic dimension selection and inherits trainer configuration when omitted. 

117 source_shard_info: Source placements and meshes returned by apply_sharding_plan, 

118 before FSDP cuts the localized parameters. 

119 """ 

120 compile_config = getattr(trainer_config, "compile", None) 

121 self.dynamic = ( 

122 getattr(compile_config, "dynamic", False) if dynamic is None else dynamic 

123 ) 

124 if not isinstance(self.dynamic, bool): 

125 raise ValueError("dynamic must be a bool") 

126 if dynamic_arg_dims is None: 

127 dynamic_arg_dims = getattr(compile_config, "dynamic_arg_dims", None) 

128 self.dynamic_arg_dims = normalize_dynamic_arg_dims(dynamic_arg_dims) 

129 self.model = model 

130 self.train_fn = train_fn 

131 self.parallel_plan = parallel_plan 

132 self._explicit_pass_config = pass_config is not None 

133 self.pass_config = self._resolve_pass_config( 

134 pass_config=pass_config, 

135 trainer_config=trainer_config, 

136 ) 

137 self._mesh_context = mesh_context 

138 self.source_shard_info = source_shard_info 

139 self._fsdp_mesh = None 

140 self._expert_fsdp_mesh = None 

141 self._expert_shard_degree: Optional[int] = None 

142 self._expert_replicate_group_name: Optional[str] = None 

143 self._expert_replicate_degree: int = 1 

144 self._fsdp_config = getattr(trainer_config, 'fsdp_config', None) 

145 self._fp32_main_params = getattr(getattr(trainer_config, "optimizer", None), "fp32_main_params", False) 

146 self._mixed_precision: Optional[GraphMixedPrecision] = None 

147 self._parameter_meshes = {} 

148 self._parameter_groups = {} 

149 self._parameter_shapes = {} 

150 self._parameter_layouts = None 

151 self._optimizer_layout_source = None 

152 self._optimizer_parameter_layouts = None 

153 self._layout_signature = None 

154 self._source_parameter_layouts = None 

155 self._source_layout_signature = None 

156 self._post_compile_hooks: List[Callable[[], None]] = [] 

157 self._compile_started = False 

158 self.device = device or torch.device(get_device_type()) 

159 

160 self.pass_config.validate() 

161 

162 self._joint_graph = None 

163 self._expert_param_names: set[str] = set() 

164 self._pytree_pre_hook: Optional[Callable[[], None]] = None 

165 # Set when the PP hybrid mesh registered a "pp" process group; makes 

166 # ``_build_pass_kwargs`` hand the group name to ``PpPass``. 

167 self._pp_group_name: Optional[str] = None 

168 

169 @staticmethod 

170 def _resolve_pass_config( 

171 *, 

172 pass_config: Optional[PassConfig], 

173 trainer_config: Optional[Any], 

174 ) -> PassConfig: 

175 """Resolve pass configuration from explicit or trainer-level input.""" 

176 if pass_config is not None: 

177 return pass_config 

178 if trainer_config is not None: 

179 return build_pass_config_from_trainer_config(trainer_config) 

180 return PassConfig() 

181 

182 @property 

183 def is_compiled(self) -> bool: 

184 """Whether a joint graph has already been compiled.""" 

185 return self._joint_graph is not None 

186 

187 @property 

188 def parameter_layouts(self) -> Optional[dict]: 

189 """Final parameter-identity layouts, available after lazy compilation. 

190 

191 Cache metadata only: gradients may be replaced on every optimizer step. 

192 Replacing a parameter invalidates the mapping, as does compiling again. 

193 """ 

194 if self._joint_graph is None: 

195 return None 

196 parameters = dict(self.model.named_parameters()) 

197 signature = tuple((id(param), tuple(param.shape), param.dtype, param.device) for param in parameters.values()) 

198 if signature != self._layout_signature: 

199 self._parameter_layouts = self._build_parameter_layouts(parameters) 

200 self._layout_signature = signature 

201 self._joint_graph.graph_module.parameter_layouts = self._parameter_layouts 

202 return self._parameter_layouts 

203 

204 @property 

205 def optimizer_parameter_layouts(self) -> Optional[dict]: 

206 """Return logical layouts and valid local shapes after physical sharding. 

207 

208 Gradient clipping describes padded storage, whereas matrix optimizers 

209 must exclude padding from their logical matrices. The valid local shape 

210 follows the pass's ceil-chunk sharding, including empty trailing shards. 

211 """ 

212 layouts = self.parameter_layouts 

213 if layouts is None: 

214 return None 

215 if layouts is self._optimizer_layout_source: 

216 return self._optimizer_parameter_layouts 

217 sharded = getattr(self._joint_graph.graph_module, "fsdp_sharded_param_names", frozenset()) 

218 result = {} 

219 for name, parameter in self.model.named_parameters(): 

220 if parameter not in layouts: 

221 continue 

222 shape = self._parameter_shapes.get(name) 

223 if shape is None: 

224 raise ValueError(f"Missing pre-shard shape for graph optimizer parameter {name!r}") 

225 local_shape = tuple(parameter.shape) 

226 if name in sharded: 

227 mesh = self._parameter_fsdp_mesh(name) 

228 axis = self._fsdp_shard_axis(mesh) 

229 coordinate = mesh.get_coordinate() 

230 if coordinate is None: 

231 raise ValueError(f"Current rank is outside the FSDP mesh for graph optimizer parameter {name!r}") 

232 rank = coordinate[axis] 

233 valid_rows = min(local_shape[0], max(shape[0] - rank * local_shape[0], 0)) 

234 local_shape = (valid_rows, *local_shape[1:]) 

235 source_layout = self.source_global_layout(name, len(shape)) 

236 if source_layout is not None: 

237 shape = source_layout.get_global_shape(shape) 

238 layout = layouts[parameter] 

239 if tuple(shape) != tuple(layout.tensor_shape): 

240 layout = copy(layout) 

241 layout.set_tensor_meta(tuple(shape), make_contiguous_strides_for(shape), parameter.dtype) 

242 result[parameter] = (layout, local_shape) 

243 self._optimizer_layout_source = layouts 

244 self._optimizer_parameter_layouts = result 

245 return result 

246 

247 @property 

248 def source_parameter_layouts(self) -> Optional[dict]: 

249 """Pre-FSDP layouts for source-local parameters, available before compile. 

250 

251 A restored checkpoint is loaded before the lazy compile, when TP/EP 

252 parameters are source-local plain tensors rather than sharded storage. 

253 Describing that state lets DCP map a global checkpoint onto the correct 

254 local slice instead of treating every rank as the first shard. 

255 """ 

256 if self._joint_graph is not None: 

257 return None 

258 parameters = dict(self.model.named_parameters()) 

259 signature = tuple((id(param), tuple(param.shape), param.dtype, param.device) for param in parameters.values()) 

260 if signature != self._source_layout_signature: 

261 self._source_parameter_layouts = ( 

262 checkpoint_metadata.build_source_parameter_layouts(self, parameters) 

263 ) 

264 self._source_layout_signature = signature 

265 return self._source_parameter_layouts 

266 

267 @property 

268 def joint_graph(self) -> Optional[Any]: 

269 """The compiled joint graph, or ``None`` before lazy compilation.""" 

270 return self._joint_graph 

271 

272 @property 

273 def mesh_context(self) -> Optional[Any]: 

274 """The automodel mesh context attached at construction, if any.""" 

275 return self._mesh_context 

276 

277 @property 

278 def parameter_shapes(self) -> Dict[str, Tuple[int, ...]]: 

279 """Pre-shard parameter shapes captured at compile time (name -> shape).""" 

280 return self._parameter_shapes 

281 

282 def ensure_expert_param_names(self) -> None: 

283 """Populate expert FQNs from the model when no plan already provides them. 

284 

285 Checkpoint metadata can be requested before the lazy compile, so this 

286 mirrors the expert discovery ``_init_expert_dp`` performs during mesh 

287 setup. 

288 """ 

289 if self._expert_param_names or self._mesh_context is None: 

290 return 

291 if getattr(self._mesh_context, "ep_size", 1) <= 1: 

292 return 

293 self._expert_param_names = self._discover_expert_param_names() 

294 

295 def _discover_expert_param_names(self) -> set[str]: 

296 """Resolve EP parameter owners and their aliases from source layouts or bound local experts.""" 

297 parameters = { 

298 id(parameter) 

299 for module in self.model.modules() 

300 if hasattr(module, "local_expert_count") 

301 for parameter in module.parameters(recurse=False) 

302 } 

303 named = dict(self.model.named_parameters(remove_duplicate=False)) 

304 # EP ownership also covers public module families and row-sharded Engram tables. 

305 for name, (_, mesh) in (self.source_shard_info or {}).items(): 

306 if name in named and "ep" in (getattr(mesh, "mesh_dim_names", None) or ()): 

307 parameters.add(id(named[name])) 

308 return {name for name, parameter in named.items() if id(parameter) in parameters} 

309 

310 def _validate_compile_mode(self) -> None: 

311 """Reject unsupported ownership and dynamic pipeline combinations.""" 

312 external = get_model_external_state(self.model) 

313 if external is not None and external.parameters: 

314 raise ValueError("GraphCompiler does not support externally managed parameters yet") 

315 

316 # Validate the terminal backend before tracing / partitioning mutates 

317 # the live model, so a missing DVM backend fails on a retry-safe state. 

318 validate_inductor_backend(self.pass_config) 

319 

320 if ( 

321 self.dynamic or self.dynamic_arg_dims is not None 

322 ) and self.pass_config.pp_enabled: 

323 raise ValueError( 

324 "Dynamic shapes with pipeline parallel are not supported yet; disable PP or dynamic shapes" 

325 ) 

326 

327 def _build_mixed_precision(self) -> Optional[GraphMixedPrecision]: 

328 """Reuse eager precision and reject combinations requiring a different sync schedule.""" 

329 config = self._fsdp_config 

330 if not isinstance(config, FSDP2Config): 

331 return None 

332 precision = config.mix_precision 

333 if not any((precision.param_dtype, precision.reduce_dtype, precision.output_dtype, precision.custom_params)): 

334 return None 

335 if not self.pass_config.fsdp_enabled: 

336 # A one-rank trainer can apply the dtype policy without enabling FSDP passes. 

337 if self._explicit_pass_config or (dist.is_initialized() and dist.get_world_size() > 1): 

338 return None 

339 mesh = self._mesh_context or MeshContext() 

340 manager = FSDP2Manager(config, mesh, self._fp32_main_params) 

341 policy, modules = manager.mixed_precision_bindings(self.model, self.source_shard_info) 

342 mixed_precision = GraphMixedPrecision(self.model, policy, modules) 

343 # Module I/O casts can still apply with the existing communication schedule. 

344 if not mixed_precision.has_param_or_grad_casts: 

345 return mixed_precision 

346 replicate_degree = self.pass_config.dp_replicate_degree or mesh.dp_replicate_size 

347 if max(replicate_degree, self._expert_replicate_degree, mesh.cp_size) > 1: 

348 raise ValueError("Graph FSDP mixed precision requires one DP/EDP replica and CP=1") 

349 if self.pass_config.pp_enabled or not config.requires_grad_sync or config.replicate_params: 

350 raise ValueError( 

351 "Graph FSDP mixed precision does not support PP, deferred gradient sync or replicate_params" 

352 ) 

353 return mixed_precision 

354 

355 def compile(self, **inputs: Any) -> None: 

356 """ 

357 Compile model into parallel graph 

358 

359 Users can explicitly call this, or it will be automatically compiled 

360 at first forward_backward 

361 

362 Args: 

363 **inputs: Model inputs, forwarded to ``train_fn`` as keyword 

364 arguments and used to trace the joint graph 

365 """ 

366 if self._compile_started: 

367 raise RuntimeError( 

368 "GraphCompiler.compile() may only be called once: the " 

369 "partitioning passes mutate the live model in place, so " 

370 "re-compiling (even after a failed attempt) would trace an " 

371 "already-partitioned model" 

372 ) 

373 self._validate_compile_mode() 

374 if self._pytree_pre_hook is not None: 

375 self._pytree_pre_hook() 

376 

377 self._validate_ep_topology() 

378 if ( 

379 isinstance(getattr(self._mesh_context, "tp_size", None), int) 

380 and self._mesh_context.tp_size > 1 

381 and not self.source_shard_info 

382 ): 

383 raise ValueError("Graph TP requires source_shard_info from the sharding plan") 

384 

385 if self.pass_config.fsdp_enabled and dist.is_initialized() and dist.get_world_size() > 1: 

386 self._init_device_mesh(self._mesh_context) 

387 

388 # Activation checkpointing must resolve its scope BEFORE tracing so 

389 # block discovery happens once. The pass receives the same scope; a 

390 # directly injected scope's optional runtime hook also runs here, before 

391 # the model's forward reads the state it configures. 

392 ac_scope = None 

393 if self.pass_config.ac_mode != "off": 

394 ac_scope = prepare_activation_checkpoint(self.model, self.pass_config) 

395 

396 self._bind_parameter_meshes() 

397 self._parameter_shapes = {name: tuple(param.shape) for name, param in self.model.named_parameters()} 

398 self._layout_signature = None 

399 

400 self._mixed_precision = self._build_mixed_precision() 

401 trace_kwargs = {} 

402 if self._mixed_precision is not None: 

403 trace_kwargs["mixed_precision"] = self._mixed_precision 

404 if self.dynamic or self.dynamic_arg_dims is not None: 

405 trace_kwargs.update({ 

406 "dynamic": self.dynamic, 

407 "dynamic_arg_dims": self.dynamic_arg_dims, 

408 }) 

409 joint_graph = trace_model_graph( 

410 self.model, self.train_fn, inputs, **trace_kwargs 

411 ) 

412 

413 pipeline = PassPipeline.from_config(self.pass_config, self.parallel_plan) 

414 

415 pass_kwargs = self._build_pass_kwargs() 

416 # Backend compilation and capture passes use fake inputs to refresh 

417 # metadata on regions transformed by earlier passes. 

418 pass_kwargs["example_inputs"] = joint_graph.example_inputs 

419 if ac_scope is not None: 

420 pass_kwargs["ac_scope"] = ac_scope 

421 

422 # Mutating passes make retries unsafe even if a later backend fails. 

423 self._compile_started = True 

424 # Partitioning passes may return a new GraphModule. 

425 joint_graph.graph_module = pipeline.run(joint_graph.graph_module, **pass_kwargs) 

426 

427 if joint_graph.input_guards is not None: 

428 joint_graph.input_guards.refresh() 

429 self._joint_graph = joint_graph 

430 hooks, self._post_compile_hooks = self._post_compile_hooks, [] 

431 for hook in hooks: 

432 hook() 

433 

434 def add_post_compile_hook(self, hook: Callable[[], None]) -> None: 

435 """Run ``hook`` once the next lazy compile has sharded the live model. 

436 

437 Args: 

438 hook: No-argument callable invoked after the passes mutate the live 

439 model; if compilation already happened it runs immediately. 

440 """ 

441 if self.is_compiled: 

442 hook() 

443 return 

444 self._post_compile_hooks.append(hook) 

445 

446 def reshard_optimizer_state(self, optimizers: Any) -> None: 

447 """Re-shard pre-compile optimizer state onto the live FSDP shards. 

448 

449 Restored moments are dense at the pre-compile parameter shapes; once the 

450 passes shard the model they must follow the same padded chunk geometry 

451 or the first optimizer step sees a shape mismatch. See 

452 :func:`~hyper_parallel.compile.optimizer_state.reshard_optimizer_state`. 

453 

454 Args: 

455 optimizers: One optimizer or a list of optimizers whose leaf 

456 ``state`` tensors should be re-sharded in place. 

457 """ 

458 optimizer_state.reshard_optimizer_state(self, optimizers) 

459 

460 def attach_shard_metadata(self, *, strict_strided: bool = True) -> None: 

461 """Annotate graph-sharded parameters for HF export and DCP consumers. 

462 

463 Args: 

464 strict_strided: Raise on a strided FSDP shard (export cannot describe 

465 it). Optimizer resharding passes False so an unrelated strided 

466 parameter does not block resharding of parameters that do have 

467 optimizer state. 

468 """ 

469 checkpoint_metadata.attach_shard_metadata(self, strict_strided=strict_strided) 

470 

471 def attach_source_shard_metadata(self) -> None: 

472 """Annotate source-local parameters for pre-compile checkpoint load/save.""" 

473 checkpoint_metadata.attach_source_shard_metadata(self) 

474 

475 def forward_backward(self, **inputs: Any) -> Any: 

476 """ 

477 Execute one compiled forward+backward step. 

478 

479 Compiles lazily on the first call. Gradients are ACCUMULATED into 

480 ``param.grad`` (not overwritten), so several micro-batch calls may 

481 run before the caller's optimizer step / zero_grad. 

482 

483 Args: 

484 **inputs: Model inputs, forwarded to ``train_fn`` as keyword 

485 arguments (must live on the compiler's device) 

486 

487 Returns: 

488 tuple: ``(loss, loss_dict)`` — the backward loss and the named 

489 loss values emitted by ``train_fn`` as extra graph outputs after 

490 the gradients (empty when ``train_fn`` returned a bare loss 

491 tensor). 

492 """ 

493 if self._joint_graph is None: 

494 self.compile(**inputs) 

495 

496 loss, grads, loss_dict = self._run_graph(**inputs) 

497 

498 self._accumulate_grads(grads) 

499 

500 return loss, loss_dict 

501 

502 def set_pytree_pre_hook(self, hook: Callable[[], None]) -> "GraphCompiler": 

503 """Register a no-arg hook run immediately before first compilation. 

504 

505 Args: 

506 hook: Callback that prepares model state before tracing. 

507 """ 

508 self._pytree_pre_hook = hook 

509 return self 

510 

511 def close(self) -> None: 

512 """Release captured graphs before distributed process-group teardown.""" 

513 if self._joint_graph is not None: 

514 teardown_aclgraph(self._joint_graph.graph_module) 

515 

516 def to(self, device: torch.device) -> "GraphCompiler": 

517 """Move the model to ``device`` and remember it for graph execution. 

518 

519 Args: 

520 device: Target device for the model and graph inputs. 

521 """ 

522 self.device = torch.device(device) 

523 self.model = self.model.to(self.device) 

524 return self 

525 

526 def source_layout_for_parameter(self, name: str) -> Optional[tuple]: 

527 """Resolve pre-FSDP placement, including tied and replicated parameters. 

528 

529 Args: 

530 name: Parameter FQN in the live model. 

531 

532 Returns: 

533 The source ``(placements, mesh)`` pair, or None for a plain local model. 

534 """ 

535 if self.source_shard_info is not None: 

536 if name in self.source_shard_info: 

537 return self.source_shard_info[name] 

538 parameters = dict(self.model.named_parameters(remove_duplicate=False)) 

539 for alias, layout in self.source_shard_info.items(): 

540 if parameters.get(alias) is parameters.get(name): 

541 return layout 

542 context = self._mesh_context 

543 if context is None: 

544 return None 

545 if name in self._expert_param_names: 

546 return ((Shard(0),), context.fsdp_moe_mesh["ep"]) 

547 mesh = context.fsdp_non_moe_mesh 

548 if mesh is not None and "tp" in mesh.mesh_dim_names: 

549 return ((Replicate(),), mesh["tp"]) 

550 return None 

551 

552 def source_global_layout(self, name: str, ndim: int) -> Optional[Layout]: 

553 """Build the pre-FSDP source layout for one parameter, if sharded. 

554 

555 Args: 

556 name: Parameter FQN in the live model. 

557 ndim: Number of tensor dims the source placements map onto. 

558 

559 Returns: 

560 The source layout, or None when the parameter has no source shard. 

561 """ 

562 source = self.source_layout_for_parameter(name) 

563 if source is None or source[1] is None: 

564 return None 

565 layout = Layout.from_device_mesh(source[1]) 

566 layout.set_placements(tuple(source[0] or ())) 

567 layout.placement_to_tensor_map(ndim) 

568 return layout 

569 

570 def _build_parameter_layouts(self, parameters: dict) -> Optional[dict]: 

571 """Describe actual local storage using common FSDP layout construction.""" 

572 context = self._mesh_context 

573 sharded = getattr(self._joint_graph.graph_module, "fsdp_sharded_param_names", frozenset()) 

574 if context is None and self._fsdp_mesh is None and not self._parameter_meshes and not sharded: 

575 return None 

576 if self._fsdp_mesh is None and context is not None: 

577 # Plain graph mode still needs metadata, without creating collectives. 

578 self._init_mesh_from_context(context, self.pass_config.dp_mode, register_groups=False) 

579 layouts = {} 

580 for name, parameter in parameters.items(): 

581 # Frozen parameters still need a layout: they carry no gradient, but 

582 # checkpoint export/DCP still gather and chop their weights, so they 

583 # cannot be skipped here (grad clipping filters them separately). 

584 mesh = self._parameter_fsdp_mesh(name) 

585 layouts[parameter] = self._build_parameter_layout( 

586 parameter, mesh, self.source_layout_for_parameter(name), sharded=name in sharded, 

587 unsharded_shape=self._parameter_shapes.get(name, tuple(parameter.shape)), 

588 ) 

589 return layouts 

590 

591 def _parameter_fsdp_mesh(self, name: str) -> DeviceMesh: 

592 """Return the mesh used to shard the named live parameter.""" 

593 mesh = self._parameter_meshes.get(name) 

594 if mesh is None: 

595 mesh = self._expert_fsdp_mesh if name in self._expert_param_names else self._fsdp_mesh 

596 if mesh is None: 

597 raise ValueError(f"Graph parameter {name!r} requires an initialized FSDP mesh or parameter binding") 

598 return mesh 

599 

600 @staticmethod 

601 def _fsdp_shard_axis(mesh: DeviceMesh) -> int: 

602 """Resolve the axis used for physical FSDP or EDP row sharding.""" 

603 for index, name in enumerate(mesh.mesh_dim_names or ()): 

604 if name in ("fsdp_shard", "edp_shard", "fsdp", "dp", "dp_shard"): 

605 return index 

606 raise ValueError(f"A physically sharded parameter requires a shard mesh axis; got {mesh.mesh_dim_names}") 

607 

608 @staticmethod 

609 def _build_parameter_layout( 

610 parameter: torch.nn.Parameter, fsdp_mesh: DeviceMesh, source: Optional[tuple], *, 

611 sharded: bool, unsharded_shape: Tuple[int, ...], 

612 ) -> Layout: 

613 """Describe actual local storage without changing parameters or source metadata. 

614 

615 Args: 

616 parameter: Live parameter after physical FSDP slicing. 

617 fsdp_mesh: Selected data-parallel child mesh. 

618 source: Source TP/EP placements and mesh before FSDP. 

619 sharded: Whether the pass physically sliced this parameter. 

620 unsharded_shape: Local shape before FSDP padding and slicing. 

621 """ 

622 mesh = fsdp_mesh 

623 placements = [Replicate() for _ in range(mesh.ndim)] 

624 shape = tuple(unsharded_shape) 

625 axis = None 

626 if sharded: 

627 axis = GraphCompiler._fsdp_shard_axis(mesh) 

628 if parameter.ndim == 0: 

629 raise ValueError("A physically sharded parameter requires a non-scalar shape") 

630 shape = (parameter.shape[0] * mesh.size(axis), *shape[1:]) 

631 if source is not None and source[1] is not None: 

632 source_placements, source_mesh = source 

633 source_layout = Layout.from_device_mesh(source_mesh) 

634 source_layout.set_placements(tuple(source_placements)) 

635 source_layout.placement_to_tensor_map(len(shape)) 

636 shape = source_layout.get_global_shape(shape) 

637 mesh = DeviceMesh.concatenate([fsdp_mesh, source_mesh]) 

638 placements.extend(source_placements) 

639 if axis is not None: 

640 split_factor = math.prod(mesh.mesh_shape[index] for index, value in enumerate(placements) 

641 if index != axis and value.is_shard(0)) 

642 placements[axis] = StridedShard(0, split_factor) if split_factor > 1 else Shard(0) 

643 layout = Layout.from_device_mesh(mesh) 

644 layout.set_placements(tuple(placements)) 

645 layout.placement_to_tensor_map(len(shape)) 

646 layout.set_tensor_meta(tuple(shape), make_contiguous_strides_for(shape), parameter.dtype) 

647 return layout 

648 

649 def _bind_parameter_meshes(self) -> None: 

650 """Reuse eager unit discovery and managed identities without eager hooks.""" 

651 self._parameter_meshes = {} 

652 self._parameter_groups = {} 

653 if not isinstance(self._fsdp_config, FSDP2Config) or self._mesh_context is None: 

654 return 

655 manager = FSDP2Manager(self._fsdp_config, self._mesh_context) 

656 bindings = manager.parameter_mesh_bindings(self.model, self.source_shard_info) 

657 registered = {} 

658 for name, parameter in self.model.named_parameters(remove_duplicate=False): 

659 mesh = bindings.get(parameter) 

660 if mesh is None: 

661 continue 

662 self._parameter_meshes[name] = mesh 

663 shard = mesh[mesh.mesh_dim_names[-1]] 

664 ranks = tuple(shard.rank_list) 

665 if ranks not in registered: 

666 group = f"fsdp_unit_{len(registered)}" 

667 self._register_mesh_group(group, shard) 

668 registered[ranks] = group 

669 self._parameter_groups[name] = (registered[ranks], shard.size()) 

670 

671 def _mesh_device_type(self) -> str: 

672 """Return the backend of the self-built mesh, honoring ``device``.""" 

673 return torch.device(self.device).type 

674 

675 def _init_device_mesh(self, mesh_context: Optional[Any] = None): 

676 """Initialize the DP process group(s) for the configured ``dp_mode``. 

677 

678 Four modes (see ``PassConfig.dp_mode``), matching simplefsdp's 

679 ``data_parallel`` and the eager ``fully_shard`` conventions: 

680 

681 * ``"fsdp"`` (default): a 1-D ``("fsdp_shard",)`` mesh; the group is 

682 registered under the graph-mode name ``"fsdp"``. 

683 * ``"ddp"``: a 1-D ``("fsdp_replicate",)`` mesh; registered under 

684 ``"dp_replicate"`` (no parameter sharding, grads all-reduced). 

685 * ``"hsdp"``: a 2-D ``("fsdp_replicate", "fsdp_shard")`` mesh 

686 (replicate, shard); both groups registered. 

687 * PP hybrid (``pp_enabled``): a 2-D ``(pp, DP)`` mesh — see 

688 ``_init_pp_dp_mesh``; the intra-stage DP group and the cross-stage 

689 ``"pp"`` group are both registered. 

690 

691 An external automodel ``MeshContext`` is reused when provided — its 

692 ``fsdp_replicate`` / ``fsdp_shard`` sub-meshes are registered under the 

693 graph-mode names, mirroring the eager ``FSDP2Manager``. The fallback 

694 builds the mesh with the repo ``init_device_mesh`` (the same builder the 

695 eager stack uses) and only supports pure DP (``tp_size == 1``) plus the 

696 PP hybrid; TP topologies must supply a ``MeshContext``. 

697 """ 

698 dp_mode = normalize_dp_mode(self.pass_config.dp_mode) 

699 if self.pass_config.pp_enabled: 

700 self._init_pp_dp_mesh(dp_mode, mesh_context) 

701 return 

702 

703 if mesh_context is not None: 

704 self._init_mesh_from_context(mesh_context, dp_mode) 

705 self._init_expert_dp(mesh_context) 

706 return 

707 

708 device_type = self._mesh_device_type() 

709 world_size = dist.get_world_size() 

710 rank_list = tuple(range(world_size)) 

711 

712 if dp_mode == "ddp": 

713 mesh = init_device_mesh( 

714 device_type, 

715 (world_size,), 

716 mesh_dim_names=("fsdp_replicate",), 

717 rank_list=rank_list, 

718 init_backend=True, 

719 ) 

720 self._fsdp_mesh = mesh 

721 self._register_mesh_group("dp_replicate", mesh["fsdp_replicate"]) 

722 self.pass_config.dp_replicate_degree = mesh["fsdp_replicate"].size() 

723 return 

724 

725 if dp_mode == "hsdp": 

726 shard, replicate = self._resolve_hsdp_degrees(world_size) 

727 mesh = init_device_mesh( 

728 device_type, 

729 (replicate, shard), 

730 mesh_dim_names=("fsdp_replicate", "fsdp_shard"), 

731 rank_list=rank_list, 

732 init_backend=True, 

733 ) 

734 self._fsdp_mesh = mesh 

735 self._register_mesh_group("dp_replicate", mesh["fsdp_replicate"]) 

736 self._register_mesh_group("fsdp", mesh["fsdp_shard"]) 

737 self.pass_config.dp_replicate_degree = mesh["fsdp_replicate"].size() 

738 self.pass_config.fsdp_degree = mesh["fsdp_shard"].size() 

739 return 

740 

741 # dp_mode == "fsdp" (default): 1-D shard mesh over the whole world. 

742 mesh = init_device_mesh( 

743 device_type, 

744 (world_size,), 

745 mesh_dim_names=("fsdp_shard",), 

746 rank_list=rank_list, 

747 init_backend=True, 

748 ) 

749 self._fsdp_mesh = mesh 

750 self._register_mesh_group("fsdp", mesh["fsdp_shard"]) 

751 # Back-fill, mirroring the external-mesh branch: FSDPPass resolves the 

752 # group size from ``fsdp_degree`` (falling back to world_size when 

753 # ``None``), so setting it here keeps the two paths consistent. 

754 self.pass_config.fsdp_degree = world_size 

755 

756 def _validate_ep_topology(self) -> None: 

757 """Allow graph EP with CP, but not with pipeline parallelism.""" 

758 context = self._mesh_context 

759 if context is None or getattr(context, "ep_size", 1) <= 1: 

760 return 

761 if not self.pass_config.fsdp_enabled: 

762 raise ValueError( 

763 "Graph EP requires fsdp_enabled=True so expert parameters can " 

764 "be sharded over the EDP mesh" 

765 ) 

766 if getattr(context, "pp_size", 1) != 1: 

767 raise ValueError("Graph EP currently requires PP=1") 

768 

769 def _init_expert_dp(self, context: Any) -> None: 

770 """Bind expert parameters to their EDP shard and replicate groups.""" 

771 if getattr(context, "ep_size", 1) <= 1: 

772 return 

773 mesh = context.fsdp_moe_mesh 

774 if mesh is None or "edp_shard" not in mesh.mesh_dim_names: 

775 raise ValueError("Graph EP requires the expert data-parallel shard mesh") 

776 self._expert_param_names = self._discover_expert_param_names() 

777 if not self._expert_param_names: 

778 raise ValueError("Graph EP requires bound local expert parameters") 

779 names = tuple(mesh.mesh_dim_names) 

780 shard_mesh = mesh["edp_shard"] 

781 self._expert_shard_degree = shard_mesh.size() 

782 self._register_mesh_group("fsdp_expert", shard_mesh) 

783 if "edp_replicate" in names: 

784 replicate_mesh = mesh["edp_replicate"] 

785 self._expert_replicate_group_name = "fsdp_expert_replicate" 

786 self._expert_replicate_degree = replicate_mesh.size() 

787 self._register_mesh_group(self._expert_replicate_group_name, replicate_mesh) 

788 expert_dims = tuple( 

789 name for name in names if name in ("edp_replicate", "edp_shard") 

790 ) 

791 self._expert_fsdp_mesh = mesh[expert_dims] 

792 else: 

793 self._expert_replicate_group_name = None 

794 self._expert_replicate_degree = 1 

795 self._expert_fsdp_mesh = shard_mesh 

796 

797 def _init_pp_dp_mesh( 

798 self, dp_mode: str, mesh_context: Optional[Any] = None 

799 ) -> None: 

800 """Initialize the 2-D ``(pp, DP)`` mesh for the PP+FSDP/DDP hybrid. 

801 

802 Builds the mesh over the identity rank list (``rank = pp_idx * 

803 dp_size + dp_idx``, PP-outer) and registers the intra-stage DP group 

804 plus the cross-stage ``"pp"`` group that ``PpPass`` pipelines over. 

805 

806 Args: 

807 dp_mode: Normalized DP mode (``"fsdp"`` or ``"ddp"``). 

808 mesh_context: Must be ``None``; an external automodel 

809 ``MeshContext`` composed with PP is not supported yet. 

810 

811 Raises: 

812 ValueError: On a ``mesh_context``, ``"hsdp"``, missing degrees, or 

813 degrees that do not tile the world. 

814 """ 

815 if mesh_context is not None: 

816 raise ValueError( 

817 "PP composed with an external automodel MeshContext is not " 

818 "supported yet; run the PP hybrid with the self-built mesh " 

819 "(omit mesh_context and set pp_degree plus fsdp_degree / " 

820 "dp_replicate_degree)" 

821 ) 

822 if dp_mode == "hsdp": 

823 raise ValueError( 

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

825 "mesh, which is not supported yet; run PP with dp_mode='fsdp' " 

826 "or 'ddp'" 

827 ) 

828 pp_degree, dp_degree, dp_mesh_name = self._resolve_pp_dp_degrees(dp_mode) 

829 world_size = dist.get_world_size() 

830 mesh = init_device_mesh( 

831 self._mesh_device_type(), 

832 (pp_degree, dp_degree), 

833 mesh_dim_names=("pp", dp_mesh_name), 

834 rank_list=tuple(range(world_size)), 

835 init_backend=True, 

836 ) 

837 self._register_pp_dp_groups(mesh, dp_mode, dp_mesh_name, pp_degree, dp_degree) 

838 _LOG.info( 

839 "PP+DP mesh: pp_degree=%s dp_mode=%s dp_degree=%s world_size=%s", 

840 pp_degree, 

841 dp_mode, 

842 dp_degree, 

843 world_size, 

844 ) 

845 

846 def _resolve_pp_dp_degrees(self, dp_mode: str) -> Tuple[int, int, str]: 

847 """Resolve and validate the ``(pp, DP)`` degrees and DP dim name.""" 

848 world_size = dist.get_world_size() 

849 pp_degree = self.pass_config.pp_degree 

850 if dp_mode == "ddp": 

851 dp_degree = self.pass_config.dp_replicate_degree 

852 dp_mesh_name = "dp_replicate" 

853 else: 

854 dp_degree = self.pass_config.fsdp_degree 

855 dp_mesh_name = "fsdp_shard" 

856 if pp_degree is None and dp_degree is None: 

857 raise ValueError( 

858 "PP + DP hybrid requires pp_degree together with (or instead " 

859 "of) fsdp_degree / dp_replicate_degree so the 2-D mesh can be " 

860 "sized; got both None" 

861 ) 

862 if pp_degree is None: 

863 if world_size % dp_degree != 0: 

864 raise ValueError( 

865 f"world_size ({world_size}) not divisible by the DP degree " 

866 f"({dp_degree}); cannot derive pp_degree" 

867 ) 

868 pp_degree = world_size // dp_degree 

869 if dp_degree is None: 

870 if world_size % pp_degree != 0: 

871 raise ValueError( 

872 f"world_size ({world_size}) not divisible by pp_degree " 

873 f"({pp_degree}); cannot derive the DP degree" 

874 ) 

875 dp_degree = world_size // pp_degree 

876 if pp_degree * dp_degree != world_size: 

877 raise ValueError( 

878 f"PP+DP degrees must tile the world: pp_degree ({pp_degree}) " 

879 f"x dp_degree ({dp_degree}) != world_size ({world_size})" 

880 ) 

881 return pp_degree, dp_degree, dp_mesh_name 

882 

883 def _register_pp_dp_groups( 

884 self, mesh: Any, dp_mode: str, dp_mesh_name: str, pp_degree: int, dp_degree: int 

885 ) -> None: 

886 """Register both hybrid groups and back-fill the pass-config degrees.""" 

887 self._fsdp_mesh = mesh[dp_mesh_name] 

888 self._register_mesh_group("pp", mesh["pp"]) 

889 self._register_mesh_group( 

890 "fsdp" if dp_mesh_name == "fsdp_shard" else "dp_replicate", 

891 mesh[dp_mesh_name], 

892 ) 

893 self._pp_group_name = "pp" 

894 self.pass_config.pp_degree = pp_degree 

895 if dp_mode == "ddp": 

896 self.pass_config.dp_replicate_degree = dp_degree 

897 else: 

898 self.pass_config.fsdp_degree = dp_degree 

899 

900 def _init_mesh_from_context(self, mesh_context: Any, dp_mode: str, *, register_groups: bool = True) -> None: 

901 """Resolve and register the DP group(s) from an automodel ``MeshContext``. 

902 

903 Reuses automodel's already-built mesh (boundary forwards hold the TP 

904 group object directly) and registers the ``fsdp_replicate`` / 

905 ``fsdp_shard`` sub-meshes under the graph-mode names ``"dp_replicate"`` 

906 / ``"fsdp"``. The effective mode is first reconciled with the mesh 

907 topology (see ``_reconcile_mode_with_context``), mirroring the eager 

908 ``FSDP2Manager`` which picks HSDP from ``dp_replicate_size > 1``. 

909 

910 Args: 

911 mesh_context: Existing data/model parallel topology. 

912 dp_mode: Requested data-parallel mode. 

913 register_groups: False for metadata-only access in plain graph mode. 

914 """ 

915 fsdp_mesh = ( 

916 getattr(mesh_context, "fsdp_non_moe_mesh", None) or mesh_context.device_mesh 

917 ) 

918 names = tuple(getattr(fsdp_mesh, "mesh_dim_names", ()) or ()) 

919 dp_mode = self._reconcile_mode_with_context(mesh_context, dp_mode) 

920 self.pass_config.dp_mode = dp_mode 

921 

922 if dp_mode == "ddp": 

923 dim = self._first_dim(names, ("fsdp_replicate", "dp_replicate", "dp")) 

924 if dim is None: 

925 raise ValueError( 

926 "dp_mode='ddp' needs a replicate axis among " 

927 "('fsdp_replicate', 'dp_replicate', 'dp') in the mesh " 

928 f"dims {names}" 

929 ) 

930 sub = fsdp_mesh[dim] 

931 self._fsdp_mesh = sub 

932 if register_groups: 

933 self._register_mesh_group("dp_replicate", sub) 

934 self.pass_config.dp_replicate_degree = sub.size() 

935 return 

936 

937 if dp_mode == "hsdp": 

938 rep_dim = self._first_dim(names, ("fsdp_replicate", "dp_replicate")) 

939 shard_dim = self._first_dim(names, ("fsdp_shard", "fsdp", "dp_shard", "dp")) 

940 if rep_dim is None or shard_dim is None: 

941 raise ValueError( 

942 "dp_mode='hsdp' needs both a replicate axis " 

943 "('fsdp_replicate'/'dp_replicate') and a shard axis " 

944 f"('fsdp_shard'/'fsdp'/'dp') in the mesh dims {names}" 

945 ) 

946 rep_sub = fsdp_mesh[rep_dim] 

947 shard_sub = fsdp_mesh[shard_dim] 

948 if shard_dim == "dp_shard" and "cp" in names: 

949 shard_sub = fsdp_mesh[(shard_dim, "cp")].flatten("fsdp_shard") 

950 self._fsdp_mesh = DeviceMesh.concatenate([rep_sub, shard_sub]) 

951 else: 

952 self._fsdp_mesh = fsdp_mesh[(rep_dim, shard_dim)] 

953 if register_groups: 

954 self._register_mesh_group("dp_replicate", rep_sub) 

955 self._register_mesh_group("fsdp", shard_sub) 

956 self.pass_config.dp_replicate_degree = rep_sub.size() 

957 self.pass_config.fsdp_degree = shard_sub.size() 

958 return 

959 

960 # dp_mode == "fsdp": automodel's fsdp_non_moe_mesh is 

961 # ("fsdp_replicate","fsdp_shard","tp"); device_mesh (cp=1) is 

962 # ("dp","cp","tp") and "dp" is the FSDP axis. 

963 dim = self._first_dim(names, ("fsdp_shard", "dp_shard", "dp")) 

964 sub = fsdp_mesh[dim] 

965 if dim == "dp_shard" and "cp" in names: 

966 sub = fsdp_mesh[(dim, "cp")].flatten("fsdp_shard") 

967 self._fsdp_mesh = sub 

968 if register_groups: 

969 self._register_mesh_group("fsdp", sub) 

970 self.pass_config.fsdp_degree = sub.size() 

971 

972 def _reconcile_mode_with_context(self, mesh_context: Any, dp_mode: str) -> str: 

973 """Align ``dp_mode`` with the ``MeshContext`` topology (eager parity). 

974 

975 The eager ``fully_shard`` path chooses FSDP vs HSDP from the mesh 

976 (``dp_replicate_size > 1`` means HSDP), not from a config flag. Mirror 

977 that so a mesh carrying a replicate axis is never silently treated as 

978 plain FSDP, and a 1-wide replicate axis is treated as FSDP. 

979 

980 Raises: 

981 ValueError: When ``dp_mode='ddp'`` but the mesh shards 

982 (``dp_shard_size > 1``). 

983 """ 

984 rep = getattr(mesh_context, "dp_replicate_size", None) 

985 shard = getattr(mesh_context, "dp_shard_size", None) 

986 if not isinstance(rep, int): 

987 # Not a real MeshContext (e.g. a test stub): leave the mode as-is. 

988 return dp_mode 

989 if dp_mode == "fsdp" and rep > 1: 

990 _LOG.warning( 

991 "dp_mode='fsdp' but MeshContext.dp_replicate_size=%d > 1; " 

992 "using 'hsdp' to match the mesh", 

993 rep, 

994 ) 

995 return "hsdp" 

996 if dp_mode == "hsdp" and rep <= 1: 

997 _LOG.warning( 

998 "dp_mode='hsdp' but MeshContext.dp_replicate_size=%d <= 1; " 

999 "using 'fsdp'", 

1000 rep, 

1001 ) 

1002 return "fsdp" 

1003 if dp_mode == "ddp" and isinstance(shard, int) and shard > 1: 

1004 raise ValueError( 

1005 "dp_mode='ddp' requires a non-sharding mesh " 

1006 f"(dp_shard_size=1), got dp_shard_size={shard}; use 'hsdp'" 

1007 ) 

1008 return dp_mode 

1009 

1010 @staticmethod 

1011 def _first_dim(names: tuple, candidates: tuple) -> Optional[str]: 

1012 """Return the first candidate axis present in ``names`` (or None).""" 

1013 for cand in candidates: 

1014 if cand in names: 

1015 return cand 

1016 return None 

1017 

1018 @staticmethod 

1019 def _register_mesh_group(name: str, sub_mesh: Any) -> None: 

1020 """Register ``sub_mesh``'s process group under ``name``.""" 

1021 _register_process_group(name, sub_mesh.get_group()) 

1022 

1023 def _resolve_hsdp_degrees(self, world_size: int) -> Tuple[int, int]: 

1024 """Resolve ``(shard, replicate)`` for a fallback 2-D HSDP mesh. 

1025 

1026 Either degree may be left ``None`` and is derived from ``world_size`` 

1027 and the other; both must be consistent with ``world_size``. 

1028 

1029 Raises: 

1030 ValueError: When both are ``None``, a degree does not divide 

1031 ``world_size``, or the product does not equal ``world_size``. 

1032 """ 

1033 shard = self.pass_config.fsdp_degree 

1034 replicate = self.pass_config.dp_replicate_degree 

1035 if shard is None and replicate is None: 

1036 raise ValueError( 

1037 "dp_mode='hsdp' requires fsdp_degree and/or " 

1038 "dp_replicate_degree to build the 2-D (dp_replicate, fsdp) mesh" 

1039 ) 

1040 if shard is None: 

1041 if world_size % replicate != 0: 

1042 raise ValueError( 

1043 f"world_size ({world_size}) not divisible by " 

1044 f"dp_replicate_degree ({replicate})" 

1045 ) 

1046 shard = world_size // replicate 

1047 if replicate is None: 

1048 if world_size % shard != 0: 

1049 raise ValueError( 

1050 f"world_size ({world_size}) not divisible by fsdp_degree ({shard})" 

1051 ) 

1052 replicate = world_size // shard 

1053 if shard * replicate != world_size: 

1054 raise ValueError( 

1055 f"hsdp degrees fsdp_degree={shard} x " 

1056 f"dp_replicate_degree={replicate} != world_size={world_size}" 

1057 ) 

1058 return shard, replicate 

1059 

1060 def _build_fsdp_plan(self) -> Optional[FsdpPlan]: 

1061 """Build per-parameter shard policies for the FSDP pass.""" 

1062 specs = { 

1063 name: FsdpParamSpec(group, degree) 

1064 for name, (group, degree) in self._parameter_groups.items() 

1065 } 

1066 if self._expert_param_names: 

1067 if self._expert_fsdp_mesh is None or self._expert_shard_degree is None: 

1068 raise ValueError("Expert parameters require fsdp_moe_mesh['edp_shard']") 

1069 for name in self._expert_param_names: 

1070 bound = specs.get(name) 

1071 group = bound.group_name if bound is not None else "fsdp_expert" 

1072 degree = bound.degree if bound is not None else self._expert_shard_degree 

1073 specs[name] = FsdpParamSpec( 

1074 group, 

1075 degree, 

1076 mode="replicate" if degree == 1 else "shard", 

1077 pad_policy="pad", 

1078 replicate_group_name=self._expert_replicate_group_name, 

1079 replicate_degree=self._expert_replicate_degree, 

1080 ) 

1081 return FsdpPlan(specs) if specs else None 

1082 

1083 def _build_pass_kwargs(self) -> dict: 

1084 """ 

1085 Build kwargs to pass to passes. 

1086 """ 

1087 kwargs = {} 

1088 

1089 # Live model: partitioning passes (FSDPPass) physically shard 

1090 # parameters in place, keeping the compiler FSDP-agnostic. 

1091 kwargs["model"] = self.model 

1092 

1093 if self.pass_config.fsdp_enabled: 

1094 kwargs["fsdp_group_name"] = "fsdp" 

1095 fsdp_plan = self._build_fsdp_plan() 

1096 if fsdp_plan is not None: 

1097 kwargs["fsdp_plan"] = fsdp_plan 

1098 kwargs.update(self._source_reduction_kwargs()) 

1099 # DDP / HSDP also reduce gradients on the replicate axis. 

1100 if normalize_dp_mode(self.pass_config.dp_mode) in ("ddp", "hsdp"): 

1101 kwargs["dp_replicate_group_name"] = "dp_replicate" 

1102 

1103 # The PP hybrid mesh registered the cross-stage "pp" group; PpPass 

1104 # resolves its stage index from it and runs boundary P2P over it. 

1105 # Pure PP (fsdp_enabled=False) leaves it unset — PpPass then builds 

1106 # its world-sized group itself. 

1107 if self.pass_config.pp_enabled and self._pp_group_name is not None: 

1108 kwargs["pp_group_name"] = self._pp_group_name 

1109 

1110 return kwargs 

1111 

1112 def _source_reduction_kwargs(self) -> dict: 

1113 """Lower eager source-layout normalization and replicated-axis synchronization.""" 

1114 names = ( 

1115 dict(self.model.named_parameters(remove_duplicate=False)) 

1116 if self.source_shard_info is not None else self._expert_param_names 

1117 ) 

1118 if not names: 

1119 return {} 

1120 if self._mesh_context is None: 

1121 raise ValueError("Graph source-layout reduction requires MeshContext") 

1122 context = self._mesh_context 

1123 loss_replicas = 1 if context.loss_parallel else context.tp_size 

1124 reduction = GradientReduction("sum", context.dp_size * context.cp_size * loss_replicas) 

1125 result = {"gradient_reductions": dict.fromkeys(names, reduction)} 

1126 if self.source_shard_info is None: 

1127 return result 

1128 groups, registered = {}, {} 

1129 for name in names: 

1130 layout = self.source_layout_for_parameter(name) 

1131 if layout is None: 

1132 continue 

1133 placements, mesh = layout 

1134 if mesh is None or not placements: 

1135 continue 

1136 axes = tuple(axis for index, axis in enumerate(mesh.mesh_dim_names) 

1137 if placements[index].is_replicate() and mesh.size(index) > 1) 

1138 if not axes: 

1139 continue 

1140 replica_mesh = mesh[axes].flatten() 

1141 ranks = tuple(replica_mesh.rank_list) 

1142 if ranks not in registered: 

1143 group_name = f"fsdp_source_{len(registered)}" 

1144 self._register_mesh_group(group_name, replica_mesh) 

1145 registered[ranks] = group_name 

1146 groups[name] = registered[ranks] 

1147 result["source_gradient_groups"] = groups 

1148 return result 

1149 

1150 def _run_graph(self, **inputs): 

1151 """Execute compiled graph""" 

1152 if self._joint_graph is None: 

1153 raise RuntimeError( 

1154 "Graph not compiled. Call compiler.compile() or " 

1155 "compiler.forward_backward() first." 

1156 ) 

1157 

1158 # The joint graph's parameters/buffers are static inputs: feed the 

1159 # live (FSDP-sharded) model state in FQN order each step. 

1160 return run_traced_graph( 

1161 self._joint_graph, 

1162 self.model, 

1163 inputs, 

1164 ) 

1165 

1166 def _accumulate_grads(self, grads: List[torch.Tensor]) -> None: 

1167 """Accumulate graph-computed gradients into the live model's parameters. 

1168 

1169 The graph emits gradients in ``state_fqns`` order (trainable 

1170 parameters only, shared parameters included once per FQN), which 

1171 diverges from ``model.parameters()`` (deduplicated) when the model 

1172 ties weights. Mapping by FQN keeps every gradient on the right 

1173 parameter; the count check refuses to assign on mismatch instead of 

1174 letting ``zip`` silently truncate. 

1175 

1176 Accumulation (not overwrite) keeps ``forward_backward`` composable: 

1177 several micro-batch steps may run before the caller's optimizer step 

1178 (which ends with ``zero_grad``), so per-step grads must sum into 

1179 ``param.grad``. 

1180 """ 

1181 # ``state_is_param`` is attached to the traced GraphModule by 

1182 # ``trace_model_graph``, not to the JointGraph dataclass itself. 

1183 state_is_param = getattr(self._joint_graph.graph_module, "state_is_param", None) 

1184 fqn_to_param = dict(self.model.named_parameters(remove_duplicate=False)) 

1185 trainable = self._trainable_params_in_state_order( 

1186 self._joint_graph.state_fqns, state_is_param, fqn_to_param 

1187 ) 

1188 if len(trainable) != len(grads): 

1189 raise ValueError( 

1190 f"Gradient count ({len(grads)}) does not match trainable " 

1191 f"parameter count ({len(trainable)}). The traced graph and " 

1192 f"the live model disagree on which parameters are trainable; " 

1193 f"refusing to assign gradients to avoid silent misalignment." 

1194 ) 

1195 

1196 precision = self._mixed_precision 

1197 use_main = precision is not None and precision.policy.apply_grad_on_fp32_main_grad 

1198 attribute = "main_grad" if use_main else "grad" 

1199 for param, grad in zip(trainable, grads): 

1200 if precision is not None and not use_main: 

1201 # Eager rounds each reduced microbatch before adding to storage-dtype .grad. 

1202 grad = grad.to(param.dtype) 

1203 accumulated = getattr(param, attribute, None) 

1204 if accumulated is None: 

1205 # Match eager's gradient layout so optimizer kernels see the 

1206 # parameter's strides rather than a backward matmul's view. 

1207 accumulated = torch.empty_like(param, dtype=grad.dtype if use_main else param.dtype) 

1208 accumulated.copy_(grad) 

1209 setattr(param, attribute, accumulated) 

1210 else: 

1211 accumulated.add_(grad) 

1212 

1213 @staticmethod 

1214 def _trainable_params_in_state_order( 

1215 state_fqns: List[str], 

1216 state_is_param: Optional[List[bool]], 

1217 fqn_to_param: Dict[str, torch.nn.Parameter], 

1218 ) -> List[torch.nn.Parameter]: 

1219 """Return the live trainable parameters in the graph's state order. 

1220 

1221 Mirrors the tracer's gradient emission order (``state_fqns`` order, 

1222 parameters only, trainable only, shared parameters kept per FQN), so 

1223 gradient ``i`` belongs to the returned parameter ``i``. Buffers share 

1224 ``state_fqns`` but are absent from the parameter lookup; they are 

1225 skipped explicitly so a missing ``state_is_param`` flag (old traces) 

1226 degrades to parameter-only instead of raising KeyError. 

1227 """ 

1228 trainable: List[torch.nn.Parameter] = [] 

1229 for idx, fqn in enumerate(state_fqns): 

1230 if state_is_param is not None and not state_is_param[idx]: 

1231 continue 

1232 param = fqn_to_param.get(fqn) 

1233 if param is not None and param.requires_grad: 

1234 trainable.append(param) 

1235 return trainable