Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / distributed / _builder / planner.py: 94%

619 statements  

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

1# Copyright 2025-2026 Huawei Technologies Co., Ltd 

2# 

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

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

5# You may obtain a copy of the License at 

6# 

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

8# 

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

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

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

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

13# limitations under the License. 

14# ============================================================================ 

15# pylint: disable=missing-apache-license-header 

16"""planner: ShardingPlanner 6-phase derivation pipeline (05 §3.6 canonical). 

17 

18Phase 1 parameter role classification (ParameterClassifier + the family's 

19 ModelAdapterSpec.sharding_rules from models/registry.py) 

20Phase 2 communication boundary grouping (two passes: first group by owning 

21 module, then merge upward depth-first — fixes the flaw in the 

22 05 §3.6.6 pseudocode where "single-parameter group inference" 

23 misjudges a q_proj leaf module as an mlp boundary) 

24Phase 3 semantic role inference (explicit FQN patterns > structural guards 

25 > parameter role combinations) 

26Phase 4 template lookup to generate spec (_build_spec_from_template) 

27Phase 4.5 user plan_overrides merge/insert (_merge_plan_overrides, 05 §3.6.7) 

28Phase 5 _is_terminal marking only (D-14, 05 §13: compile-time chain 

29 propagation/validation removed — specs are fully self-declared and 

30 each module vouches for its own propagation in validate mode) 

31Phase 6 special parameter handler collection (SPECIAL_HANDLERS) 

32 

33Registries: 

34- family sharding rules: ``ModelAdapterSpec.sharding_rules`` providers in 

35 ``models/<family>/adapter/registration.py``, resolved lazily through 

36 ``models/registry.py::get_model_adapter`` (any spelling — model_type, 

37 HF architecture or canonical arch name); 

38- ``SPECIAL_HANDLERS``: {handler_name: callable(module, param_name, mesh)} — 

39 lives in ``_builder/special_handlers.py``. 

40""" 

41 

42import copy 

43import logging 

44import re 

45from typing import Any, Dict, List, Optional, Tuple 

46 

47from torch import nn 

48 

49from hyper_parallel.components.modules.module_family import FamilyShardingContext, _family_parameter_shapes 

50from hyper_parallel.distributed._builder.family_layout import collect_owned_layouts, validate_owned_layouts 

51from hyper_parallel.models.registry import resolve_model_adapter 

52from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

53from hyper_parallel.core.dtensor.placement_types import ( 

54 Partial, 

55 Replicate, 

56 Shard, 

57) 

58from hyper_parallel.distributed.plan import ShardingPlan 

59from hyper_parallel.distributed.recipe_spec import ( 

60 DP, 

61 EP, 

62 TP, 

63 ModuleShardingSpec, 

64) 

65from hyper_parallel.distributed.tensor_parallel.param_role import ( 

66 ParameterClassifier, 

67 ParamRole, 

68 _match_any, 

69) 

70from hyper_parallel.distributed._builder.default_templates import ( 

71 ShardingTemplate, 

72 TEMPLATES, 

73 _build_spec_from_template, 

74 _finalize_tp_local_attr_plans, 

75 _moe_expert_tp_placement, 

76 _multi_dim, 

77) 

78from hyper_parallel.distributed._builder.function_module import FunctionModule 

79from hyper_parallel.distributed._builder.rule_resolver import ( 

80 _last_segment, 

81 _merge_plan_overrides, 

82 _normalize_contract_fields, 

83) 

84from hyper_parallel.distributed._builder.special_handlers import ( 

85 _SPECIAL_HANDLER_PATTERNS, 

86 _collect_special_handlers, 

87) 

88 

89logger = logging.getLogger(__name__) 

90 

91# Per-family naming-rule overrides no longer live here: each family declares 

92# them via ``ModelAdapterSpec.sharding_rules`` in 

93# ``models/<family>/adapter/registration.py`` (DeepSeek MLA, Qwen2-MoE 

94# shared_expert_gate), discovered through ``models/registry.py``. The 

95# planner core stays family-agnostic (05 §15.9 step 1). 

96 

97 

98# Leaf-segment guard for projection/container segment names: these segment 

99# names are not boundary containers themselves; inference returns unknown 

100# and continues upward. 

101# NOTE (accuracy fix F3): "shared_experts" was REMOVED from this guard — 

102# the shared expert (singular or plural spelling) must surface as its own 

103# nested "mlp" boundary (its boundary exit owns the RowWise Partial TP 

104# reduction, accuracy_problem.md 10.3 Option A); keeping it in the guard would 

105# merge it into the parent MoE boundary and silently leave the TP reduction 

106# without an owner. 

107_LEAF_SEGMENT_GUARD = frozenset({ 

108 "q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj", 

109 "qkv_proj", "fused_qkv", "linear_qkv", "gate_up_proj", "query_key_value", 

110 "experts", "gate", "linear", "proj", 

111 "fc1", "fc2", "w1", "w2", "w3", "w13", "dense", "dense_h_to_4h", "dense_4h_to_h", 

112}) 

113 

114_ATTN_PATTERNS = ("attn", "attention") 

115_MLP_PATTERNS = ("mlp", "ffn", "feed_forward") 

116_MOE_CONTAINER_PATTERNS = ("mlp", "moe", "moe_block", "moe_layer") 

117 

118 

119def _get_architecture(model) -> str: 

120 """Detect the canonical architecture name: 

121 config.architectures[0] > config.model_type > class name; 

122 lowercased with ForCausalLM-style suffixes stripped.""" 

123 cfg = getattr(model, "config", None) 

124 arch_str = None 

125 archs = getattr(cfg, "architectures", None) 

126 if archs: 

127 arch_str = archs[0] 

128 if not arch_str: 

129 arch_str = getattr(cfg, "model_type", None) 

130 if not arch_str: 

131 arch_str = type(model).__name__ 

132 

133 s = arch_str.lower() 

134 for suffix in ("forcausallm", "forconditionalgeneration", 

135 "forsequenceclassification", "forimagetexttotext"): 

136 if s.endswith(suffix): 

137 s = s[: -len(suffix)] 

138 return s 

139 

140 

141class ShardingPlanner: 

142 """Automatically derive a ShardingPlan from any HF-style model (05 §3.6.6). 

143 

144 ``plan_overrides``: {module_fqn | fqn_glob: ModuleShardingSpec} — the 

145 SINGLE injection/override interface (05 §3.6.7 + the unification rework): 

146 

147 - **merge mode** (key hits a planner-derived boundary): empty contract 

148 fields (``params``/``in_src``/``in_dst``/``out_src``/``out_dst``/ 

149 ``out_names``) INHERIT the derived values, non-empty ones replace 

150 (field granularity); the string sentinels ``"auto"`` (explicit 

151 inherit — self-documenting "derive per template") and ``"none"`` 

152 (explicit clear) are resolved at merge time and never reach the plan 

153 output; the injection fields (``local_compute_fn`` / 

154 ``inner_target`` / ``inner_wrapper`` non-None, ``region_dispatch=False``) 

155 always win; internal flags (``_ep_size`` / ``_ep_stack`` / 

156 ``_needs_cp_attn``) always inherit. This is how 

157 CP/EP compute injection is declared — no need to re-declare contracts; 

158 - **insert mode** (exact key misses every derived boundary): the spec is 

159 inserted as-is and must be fully self-declared — an override with 

160 empty params AND empty contracts fails fast ("no template matched"); 

161 - **glob keys** (containing ``*``/``?``/``[``): merge-applied to every 

162 matching boundary. A glob with a concrete parameter or I/O contract 

163 also expands against the final model tree and inserts unmatched modules 

164 with the same validation as exact insert mode. Partial globs carrying 

165 only injection/attribute changes remain merge-only and fail if they 

166 target a model module for which no boundary was derived. 

167 

168 The YAML transport (``hyper_parallel.trainer.config.PlanOverride``) is 

169 converted to this dict by ``entries_to_plan_overrides()`` on the trainer 

170 side BEFORE the 

171 planner is constructed — the planner itself has exactly one override 

172 interface. 

173 

174 ``derive=False`` turns the planner into a pure declaration assembler: 

175 template derivation (Phases 2-4) is skipped and the plan contains ONLY 

176 the ``plan_overrides`` specs — every key is insert mode and must be 

177 fully self-declared. Use it for subtrees where automatic derivation is 

178 semantically wrong, e.g. the multimodal encoder_dp ViT bridge (each 

179 rank encodes a different image shard, so any derived TP collective 

180 inside the ViT would silently mix samples). This replaces the error- 

181 prone post-hoc pruning idiom ``plan.modules = {"": plan.modules[""]}``. 

182 """ 

183 

184 def __init__( 

185 self, 

186 plan_overrides: Optional[Dict[str, ModuleShardingSpec]] = None, 

187 *, 

188 derive: bool = True, 

189 allow_uncovered_params: bool = False, 

190 ) -> None: 

191 """Create a ShardingPlanner. 

192 

193 Args: 

194 plan_overrides: ``{module_fqn | fqn_glob: ModuleShardingSpec}`` — 

195 the single injection/override interface (05 §3.6.7); see the 

196 class docstring for merge/insert/glob semantics. 

197 derive: When ``False``, template derivation (Phases 2-4) is 

198 skipped and the plan contains ONLY the ``plan_overrides`` 

199 specs (every key is insert mode, fully self-declared). 

200 allow_uncovered_params: When ``True``, downgrade the F4b 

201 "every trainable parameter must be covered by the plan" 

202 hard error to a warning (exploratory debugging only). 

203 """ 

204 self._classifier = ParameterClassifier() 

205 self._templates = TEMPLATES 

206 self._special_handler_patterns = dict(_SPECIAL_HANDLER_PATTERNS) 

207 self._plan_overrides = dict(plan_overrides or {}) 

208 # derive=False: skip template derivation entirely — the plan contains 

209 # ONLY the plan_overrides specs (every key is insert mode and must be 

210 # fully self-declared). This replaces post-hoc pruning of 

211 # ``plan.modules`` (e.g. the multimodal encoder_dp ViT bridge, where 

212 # each rank encodes different images and ANY derived TP collective 

213 # inside the ViT subtree would be a math error). 

214 self._derive = derive 

215 # F4b (accuracy_fix_plan.md §2): by default every trainable parameter 

216 # must be covered by the plan (fail-fast). Set True ONLY for 

217 # exploratory debugging to downgrade the hard error to a warning. 

218 self._allow_uncovered_params = allow_uncovered_params 

219 

220 # ── Main entry point ──────────────────────────────────────────────── 

221 

222 def _derive_boundary_specs( 

223 self, 

224 plan: ShardingPlan, 

225 boundary_groups, 

226 *, 

227 sequence_parallel: bool, 

228 loss_parallel: bool, 

229 mesh_dim_names: Tuple[str, ...], 

230 arch: str, 

231 ep_extend: int, 

232 mesh: DeviceMesh, 

233 model: Any, 

234 param_ndims: Dict[str, int], 

235 boundary_types: Optional[Dict[str, str]] = None, 

236 ) -> None: 

237 """Materialize template-derived boundary specs into a plan.""" 

238 if not self._derive: 

239 logger.info( 

240 "derive=False: template derivation skipped — the plan will contain only plan_overrides " 

241 "specs (all insert mode, fully self-declared)" 

242 ) 

243 return 

244 for boundary_fqn, group in boundary_groups.items(): 

245 boundary_type = (boundary_types or {}).get(boundary_fqn) or self._infer_boundary_type(boundary_fqn, group) 

246 if self._templates.get(boundary_type) is None: 

247 logger.warning("No template for boundary_type=%s at %s", boundary_type, boundary_fqn) 

248 continue 

249 spec = _build_spec_from_template( 

250 self._templates, 

251 boundary_fqn, 

252 group, 

253 self._templates.get(boundary_type), 

254 sequence_parallel, 

255 loss_parallel, 

256 mesh_dim_names, 

257 param_ndims=param_ndims, 

258 ep_size=ep_extend or 1, 

259 ) 

260 if spec is None: 

261 continue 

262 if boundary_type == "moe_mlp": 

263 self._mark_hf_native_moe( 

264 spec, group, boundary_fqn, self._templates.get(boundary_type), mesh_dim_names, arch, 

265 ep_extend=ep_extend, mesh=mesh, model=model, param_ndims=param_ndims, 

266 ) 

267 plan.modules[boundary_fqn] = spec 

268 

269 def _finalize_boundary_specs( 

270 self, 

271 plan: ShardingPlan, 

272 model: Any, 

273 *, 

274 tp_size: int, 

275 ep_size: int, 

276 mesh: DeviceMesh, 

277 mesh_dim_names: Tuple[str, ...], 

278 ) -> None: 

279 """Normalize overrides and finish placement-dependent boundary metadata.""" 

280 _merge_plan_overrides(self._plan_overrides, plan, model, derive=self._derive) 

281 _normalize_contract_fields(plan) 

282 self._mark_virtual_ep_parameters(plan, ep_size, mesh) 

283 _finalize_tp_local_attr_plans(plan, model, tp_size=tp_size, mesh_dim_names=mesh_dim_names) 

284 self._finalize_deferred_biases(plan, model, mesh_dim_names) 

285 self._finalize_fused_expert_tp_guard(plan, tp_size=tp_size) 

286 

287 @staticmethod 

288 def _log_explanation(plan: ShardingPlan, enabled: bool) -> None: 

289 """Log the plan explanation when requested.""" 

290 if enabled: 

291 logger.info("ShardingPlan explain:\n%s", plan.explain()) 

292 

293 @staticmethod 

294 def _resolve_isolated_roots(model: Any, arch: str) -> tuple[str, ...]: 

295 """Find subtrees whose activation layout is owned by a separate runtime.""" 

296 from hyper_parallel.models.registry import get_model_adapter # pylint: disable=C0415 

297 

298 adapter = (model._hp_model_adapter_spec if hasattr(model, "_hp_model_adapter_spec") # pylint: disable=protected-access 

299 else get_model_adapter(arch)) 

300 if adapter is None or adapter.encoder_parallel is None: 

301 return () 

302 spec = adapter.encoder_parallel() 

303 names = {name for name, _ in model.named_modules()} 

304 return tuple(root for root in spec.isolated_subtrees if root in names) 

305 

306 @staticmethod 

307 def _manages_expert_transport(spec, protocol) -> bool: 

308 """Recognize complete matrices and stage-owned transport from existing declarations.""" 

309 if spec.is_boundary or any((spec.in_src, spec.in_dst, spec.out_src, spec.out_dst)): 

310 return False 

311 for axes in spec.params.values(): 

312 for axis, placement in axes.items(): 

313 if placement == Replicate(): 

314 continue 

315 if axis != EP or placement != Shard(0): 

316 return False 

317 if protocol is None or protocol.binding_kind not in ("ep", "mesh"): 

318 return False 

319 return True 

320 

321 def _routed_moe_boundaries(self, roles, owned) -> dict[str, str]: 

322 """Select parent templates before expert ownership hides the MoE structure.""" 

323 managed = set() 

324 for fqn, spec in owned.specs.items(): 

325 if self._manages_expert_transport(spec, owned.parallel.get(fqn)): 

326 managed.update(f"{fqn}.{name}" if fqn else name for name in spec.params) 

327 if not managed: 

328 return {} 

329 result = {} 

330 for fqn, group in self._group_by_boundary(roles).items(): 

331 experts = {name for name, role in group if role == ParamRole.MOE_EXPERT} 

332 if (fqn not in owned.specs and experts and experts <= managed 

333 and self._infer_boundary_type(fqn, group) == "moe_mlp"): 

334 result[fqn] = "moe_mlp_routed" 

335 return result 

336 

337 def _classify_boundary_groups(self, model: Any, arch: str, isolated_roots=(), *, owned): 

338 """Keep MoE structure visible while assigning each parameter to one layout owner.""" 

339 all_roles = self._classify_all_params(model, arch) 

340 isolated_prefixes = tuple(root + "." for root in isolated_roots) 

341 regular_roles = {name: role for name, role in all_roles.items() if not name.startswith(isolated_prefixes)} 

342 boundary_types = self._routed_moe_boundaries(regular_roles, owned) 

343 routed_prefixes = tuple(root + "." for root in boundary_types) 

344 param_roles = {name: role for name, role in all_roles.items() if name not in owned.owned_names} 

345 remaining = {name: role for name, role in param_roles.items() 

346 if not name.startswith(isolated_prefixes + routed_prefixes)} 

347 groups = self._group_by_boundary(remaining) 

348 for root in boundary_types: 

349 groups[root] = [(name, role) for name, role in regular_roles.items() 

350 if name.startswith(root + ".") and name not in owned.owned_names] 

351 # The parent template owns complete replicated math, including otherwise-special parameters. 

352 for name, role in groups[root]: 

353 if role == ParamRole.SPECIAL: 

354 param_roles[name] = ParamRole.REPLICATED 

355 return param_roles, groups, boundary_types 

356 

357 def plan( 

358 self, 

359 model: Any, 

360 mesh: DeviceMesh, 

361 *, 

362 tp_size: int = 1, 

363 cp_size: int = 1, 

364 ep_size: int = 1, 

365 sequence_parallel: bool = True, 

366 loss_parallel: bool = False, 

367 explain: bool = False, 

368 ) -> ShardingPlan: 

369 """Derive a ShardingPlan from *model* and *mesh* (6-phase pipeline). 

370 

371 Args: 

372 model: Any HuggingFace ``PreTrainedModel``. 

373 mesh: A :class:`~hyper_parallel.core.dtensor.device_mesh.DeviceMesh` 

374 whose ``mesh_dim_names`` declare the physical topology axes (e.g. 

375 ``("dp", "tp")`` or ``("dp_replicate", "tp", "cp")``). The 

376 ``tp`` / ``cp`` axes are managed by DTensor; ``dp*`` / ``pp`` 

377 axes belong to FSDP2 / pipeline-parallel runtimes and are 

378 filtered out. 

379 tp_size: Tensor-parallel group size. Must be **equal** to 

380 ``mesh[\"tp\"].size()`` when ``mesh_dim_names`` contains ``"tp"`` 

381 and tp_size > 1; a mismatch raises :class:`ValueError` 

382 immediately (fail-first). 

383 cp_size: Context-parallel group size. Same fail-first contract as 

384 *tp_size* with respect to ``mesh[\"cp\"]``. 

385 ep_size: Expert-parallel group size. 

386 

387 - **D-10 TP-extend-EP** (the default MoE path, 05 §6.4.8): the 

388 mesh does **not** have an ``"ep"`` axis; *ep_size* is the 

389 extended EP group size, and the expert mesh ``(edp, ep)`` is 

390 derived by flattening the full dense region 

391 (``dp × tp × cp``). *ep_size* is **not** validated against 

392 the mesh in this case. 

393 - **Old-style EP** (when ``mesh_dim_names`` contains ``"ep"``): 

394 *ep_size* must equal ``mesh[\"ep\"].size()``, validated 

395 fail-first. 

396 sequence_parallel: When ``True`` (default), sequence dimension is 

397 sharded across TP (Shard(1) on the ``tp`` axis of activations). 

398 loss_parallel: When ``True``, lm_head output stays Shard(-1); 

399 otherwise gathered to Replicate (cross-entropy compatibility). 

400 explain: When ``True``, log the plan introspection report 

401 (:meth:`ShardingPlan.explain`) at INFO level after planning — 

402 per-boundary param sharding, compiled communication plans, 

403 and injection resolutions. The same report is available 

404 standalone via ``plan.explain(fqn=None)``. 

405 

406 Returns: 

407 :class:`ShardingPlan`: module FQN → :class:`ModuleShardingSpec`. 

408 

409 Raises: 

410 ValueError: If *tp_size* / *cp_size* / *ep_size* do not match the 

411 corresponding mesh dimensions (fail-first), if model-level 

412 constraints are violated (head divisibility, expert count, etc.), 

413 or if any ``plan_overrides`` spec declares a DP placement 

414 (05 §3.1.1 coordinate-system convention: the plan is always a 

415 single dp slice). 

416 """ 

417 arch = _get_architecture(model) 

418 self._check_overrides_no_dp() # fail-first: the plan's coordinate system = a single dp slice 

419 mesh_dim_names = self._build_mesh_dim_names(mesh, tp_size, cp_size, ep_size) 

420 plan, param_roles, param_metadata = self._build_plan( 

421 model, 

422 mesh, 

423 mesh_dim_names, 

424 arch, 

425 tp_size=tp_size, 

426 cp_size=cp_size, 

427 ep_size=ep_size, 

428 sequence_parallel=sequence_parallel, 

429 loss_parallel=loss_parallel, 

430 ) 

431 

432 # D-14 invariants, Phase 5/6, F4 lints, DX guard, tied weights 

433 plan = self._finalize_plan( 

434 plan, 

435 model, 

436 param_roles, 

437 param_metadata, 

438 tp_size=tp_size, 

439 cp_size=cp_size, 

440 ep_size=ep_size, 

441 ) 

442 

443 self._log_explanation(plan, explain) 

444 

445 return plan 

446 

447 def _build_plan( 

448 self, 

449 model: Any, 

450 mesh: DeviceMesh, 

451 mesh_dim_names: Tuple[str, ...], 

452 arch: str, 

453 *, 

454 tp_size: int, 

455 cp_size: int, 

456 ep_size: int, 

457 sequence_parallel: bool, 

458 loss_parallel: bool, 

459 ) -> Tuple[ShardingPlan, Dict[str, ParamRole], Tuple[Dict[str, int], Dict[str, Tuple[int, ...]]]]: 

460 """Run Phases 1-4.5: classify, derive, and merge boundary specs.""" 

461 # D-10 TP-extend-EP (05 §6.4.8): ep_size is the extended EP group 

462 # size (the a2a communication domain, extended from the TP group to 

463 # neighboring dp/cp ranks; expert weights are sharded only along 

464 # the expert dim; no separate etp configuration). Validation 

465 # happens when _mark_hf_native_moe actually matches an HF-native 

466 # MoE (pre-stacked EP-aware modules use their own dispatcher and 

467 # are not subject to this constraint) 

468 # Phase 1: parameter role classification 

469 layout_context = FamilyShardingContext( 

470 mesh_dim_names, {"tp": tp_size, "cp": cp_size, "ep": ep_size}, 

471 _family_parameter_shapes(model), 

472 sequence_parallel, loss_parallel, 

473 ) 

474 owned = collect_owned_layouts(model, layout_context, resolve_model_adapter(model)) 

475 isolated_roots = self._resolve_isolated_roots(model, arch) if self._derive else () 

476 param_roles, boundary_groups, boundary_types = self._classify_boundary_groups( 

477 model, arch, isolated_roots, owned=owned, 

478 ) 

479 

480 # Phase 3+4: semantic inference + template-fills I/O 

481 # F4a/F4b: full shapes + requires_grad for the plan-time lints 

482 # (meta tensors carry shapes too — the zero-memory path is unaffected) 

483 param_metadata = ( 

484 {name: p.ndim for name, p in model.named_parameters()}, 

485 dict(layout_context.parameter_shapes), 

486 ) 

487 plan = ShardingPlan( 

488 mesh_dim_names=mesh_dim_names, 

489 sequence_parallel=sequence_parallel, 

490 loss_parallel=loss_parallel, 

491 ) 

492 self._derive_boundary_specs( 

493 plan, 

494 boundary_groups, 

495 sequence_parallel=sequence_parallel, 

496 loss_parallel=loss_parallel, 

497 mesh_dim_names=mesh_dim_names, 

498 arch=arch, 

499 ep_extend=ep_size if ep_size > 1 else 0, 

500 mesh=mesh, 

501 model=model, 

502 param_ndims=param_metadata[0], 

503 boundary_types=boundary_types, 

504 ) 

505 

506 for root in isolated_roots: 

507 module = model.get_submodule(root) 

508 params = {name: {TP: Replicate()} for name, parameter in module.named_parameters() 

509 if parameter.requires_grad} 

510 plan.modules[root] = ModuleShardingSpec(params=params, in_src={}, in_dst={}, is_boundary=False) 

511 

512 plan.modules.update(owned.specs) 

513 plan.parallel_modules.update(owned.parallel) 

514 plan.owned_parameter_names.update(owned.owned_names) 

515 plan.tied_pairs.extend(owned.aliases) 

516 plan.parameter_aliases.extend(owned.aliases) 

517 

518 # Phase 4.5: merge derived matches and expand fully declared globs 

519 # against the final model tree to insert new boundaries. 

520 self._finalize_boundary_specs( 

521 plan, 

522 model, 

523 tp_size=tp_size, 

524 ep_size=ep_size, 

525 mesh=mesh, 

526 mesh_dim_names=mesh_dim_names, 

527 ) 

528 validate_owned_layouts(model, plan, owned, layout_context) 

529 return plan, param_roles, param_metadata 

530 

531 def _finalize_plan( 

532 self, 

533 plan: ShardingPlan, 

534 model: Any, 

535 param_roles: Dict[str, ParamRole], 

536 param_metadata: Tuple[Dict[str, int], Dict[str, Tuple[int, ...]]], 

537 *, 

538 tp_size: int, 

539 cp_size: int, 

540 ep_size: int, 

541 ) -> ShardingPlan: 

542 """Run the D-14 invariants, Phase 5/6, the F4 lints, and tied pairs.""" 

543 # D-14 invariants (05 §13.2/§13.3): full self-declaration + param 

544 # uniqueness (the only nesting check that remains) 

545 self._check_full_declaration(plan) 

546 self._check_param_uniqueness(plan) 

547 

548 # Phase 5: _is_terminal marking (D-14: chain propagation removed) 

549 plan = self._mark_terminal(plan, model) 

550 

551 # Phase 6: special parameter handling 

552 plan.special_handlers = _collect_special_handlers(param_roles, self._special_handler_patterns) 

553 

554 # F4 plan-time lints (accuracy_fix_plan.md §2 — after Phase 4.5 

555 # overrides merge and Phase 6, so hand-written specs and special 

556 # handlers are all accounted for): 

557 # F4a: every Shard(dim) must divide the parameter shape — an empty 

558 # shard at apply time becomes a plan-time teaching error; 

559 # F4b: every trainable parameter must be covered by the plan. 

560 self._check_shard_divisibility( 

561 plan, param_metadata[1], tp_size=tp_size, cp_size=cp_size, 

562 ep_size=ep_size) 

563 self._check_all_trainable_params_covered(plan, model) 

564 

565 # DX guard: FunctionModule instances not covered by any spec run 

566 # without any boundary communication — warn instead of silently passing 

567 self._warn_uncovered_function_modules(model, plan) 

568 

569 # tied-weight detection (embed <-> lm_head sharing storage) 

570 plan.tied_pairs = list(dict.fromkeys([*plan.tied_pairs, *self._detect_tied_pairs(model)])) 

571 return plan 

572 

573 # ── Architecture detection ────────────────────────────────────────── 

574 

575 @staticmethod 

576 def _get_architecture(model) -> str: 

577 """Compatibility wrapper for the module-level architecture helper.""" 

578 return _get_architecture(model) 

579 

580 @staticmethod 

581 def _validate_dtensor_axes( 

582 mesh, tp_size: int, cp_size: int, ep_size: int, 

583 ) -> None: 

584 """Fail-first: validate passed tp/cp/ep sizes against the mesh dimensions. 

585 

586 The mesh *must* declare ``mesh_dim_names`` (and the corresponding 

587 ``mesh_shape``) for validation to proceed; a mesh without names skips 

588 validation (backward-compatible fallback). 

589 

590 Degenerate single-rank meshes (all dimensions size 1, common in 

591 compile-time unit tests) also skip validation — on a single rank every 

592 DTensor placement is a no-op. 

593 

594 Rules: 

595 - tp_size > 1 → mesh must contain a "tp" axis whose size equals tp_size. 

596 - cp_size > 1 → mesh must contain a "cp" axis whose size equals cp_size. 

597 - ep_size > 1 is validated only when the mesh has an explicit "ep" 

598 dimension (old-style EP). In D-10 TP-extend-EP the ep group is 

599 *derived* from the dense region, not a native mesh axis, so the 

600 absence of "ep" in mesh_dim_names is expected and not an error. 

601 """ 

602 mesh_names = tuple(getattr(mesh, "mesh_dim_names", ()) or ()) 

603 mesh_shape = tuple(getattr(mesh, "mesh_shape", ()) or ()) 

604 if not mesh_names or not mesh_shape: 

605 return # cannot validate without mesh metadata 

606 

607 # Degenerate single-rank mesh (compile-time test fixtures): skip 

608 if all(sz == 1 for sz in mesh_shape): 

609 return 

610 

611 name_to_size = dict(zip(mesh_names, mesh_shape)) 

612 

613 for ax, size in (("tp", tp_size), ("cp", cp_size)): 

614 if size > 1: 

615 if ax not in name_to_size: 

616 raise ValueError( 

617 f"{ax}_size={size} > 1, but the mesh has no '{ax}' dimension. " 

618 f"Mesh dimensions: {list(name_to_size.keys())}. " 

619 f"Either add '{ax}' to the mesh's mesh_dim_names, or set " 

620 f"{ax}_size=1." 

621 ) 

622 mesh_sz = name_to_size[ax] 

623 if size != mesh_sz: 

624 raise ValueError( 

625 f"{ax}_size ({size}) does not match mesh['{ax}'] size " 

626 f"({mesh_sz}). They must be equal." 

627 ) 

628 

629 # ep_size: only validate when "ep" is a declared mesh axis (old-style 

630 # EP). D-10 TP-extend-EP does not put "ep" in mesh_dim_names — the 

631 # ep group is derived from the dense region by _expert_mesh_layout. 

632 if ep_size > 1 and "ep" in name_to_size: 

633 mesh_sz = name_to_size["ep"] 

634 if ep_size != mesh_sz: 

635 raise ValueError( 

636 f"ep_size ({ep_size}) does not match mesh['ep'] size " 

637 f"({mesh_sz}). They must be equal." 

638 ) 

639 

640 def _build_mesh_dim_names( 

641 self, mesh, tp_size: int, cp_size: int, ep_size: int, 

642 ) -> Tuple[str, ...]: 

643 """Filter tp/cp/ep with mesh.mesh_dim_names as the authoritative 

644 order; fall back to (tp,cp,ep) when undeclared; drop size=1 axes. 

645 

646 dp* axes are ALWAYS stripped (05 §3 coordinate-system convention): the plan's 

647 coordinate system is a single dp slice — dp semantics live in the 

648 data pipeline (data assignment) and FSDP (weight/grad domain), 

649 never in placements. Overrides declaring DP placements are 

650 rejected fail-first by :meth:`_check_overrides_no_dp`. 

651 

652 Raises :class:`ValueError` when *tp_size* / *cp_size* do not match the 

653 corresponding mesh dimension sizes (fail-first before any planning work). 

654 """ 

655 self._validate_dtensor_axes(mesh, tp_size, cp_size, ep_size) 

656 mesh_names = tuple(getattr(mesh, "mesh_dim_names", ()) or ()) 

657 dtensor_axes = ("tp", "cp", "ep") 

658 active = {ax for ax, sz in (("tp", tp_size), ("cp", cp_size), ("ep", ep_size)) 

659 if sz and sz > 1} 

660 if mesh_names: 

661 return tuple(n for n in mesh_names if n in dtensor_axes and n in active) 

662 return tuple(ax for ax in dtensor_axes if ax in active) 

663 

664 def _check_overrides_no_dp(self) -> None: 

665 """Fail-first: plan_overrides must not declare DP placements. 

666 

667 The plan's coordinate system is a single dp slice (05 §3 coordinate-system convention): 

668 dp placements never drive boundary communication, and parameter dp 

669 layout is owned by FSDP *after* the plan — a DP key here would be 

670 silently dropped at resolve time, so reject it with a teaching 

671 message instead of letting the misreading happen. 

672 """ 

673 

674 def _declares_dp(node) -> bool: 

675 return isinstance(node, dict) and any( 

676 k == DP or _declares_dp(v) for k, v in node.items()) 

677 

678 for fqn, spec in self._plan_overrides.items(): 

679 if not isinstance(spec, ModuleShardingSpec): 

680 continue # wrong types are reported as TypeError by _merge_plan_overrides 

681 for field in ("params", "in_src", "in_dst", "out_src", "out_dst"): 

682 if _declares_dp(getattr(spec, field)): 

683 raise ValueError( 

684 f'plan_overrides["{fqn}"].{field}: declaring a DP ' 

685 "placement is not allowed. The plan's coordinate " 

686 "system is a single dp slice (tp/cp/ep, 05 §3 " 

687 "coordinate-system convention) — dp data sharding is " 

688 "expressed by the data pipeline, parameter/gradient " 

689 "sharding by FSDP; for scenarios such as multimodal " 

690 "encoder_dp the dp semantics live in vit_mesh + data " 

691 "assignment + fully_shard, and the I/O contract only " 

692 "needs to declare tp/cp/ep." 

693 ) 

694 

695 # ── Phase 1 ───────────────────────────────────────────────────────── 

696 

697 @staticmethod 

698 def _warn_uncovered_function_modules(model, plan) -> None: 

699 """DX guard: a FunctionModule without a boundary spec gets NO 

700 redistribution communication (it is invisible to the planner's 

701 derivation) — surface it instead of silently passing.""" 

702 uncovered = [fqn for fqn, m in model.named_modules() 

703 if isinstance(m, FunctionModule) and fqn not in plan.modules] 

704 if uncovered: 

705 logger.warning( 

706 "FunctionModule %s has no boundary spec — no communication " 

707 "will be inserted around it. Declare one via " 

708 "plan_overrides (params={}, region_dispatch=False).", 

709 uncovered, 

710 ) 

711 

712 def _classify_all_params(self, model, arch: str) -> Dict[str, ParamRole]: 

713 """Phase 1 entry: default naming rules plus the family's declared 

714 sharding rules (``ModelAdapterSpec.sharding_rules``, resolved through 

715 the models registry — the planner core carries no per-family 

716 knowledge).""" 

717 from hyper_parallel.models.registry import ( # pylint: disable=import-outside-toplevel 

718 get_model_adapter, 

719 ) 

720 spec = (model._hp_model_adapter_spec if hasattr(model, "_hp_model_adapter_spec") # pylint: disable=protected-access 

721 else get_model_adapter(arch)) 

722 rules = [] 

723 if spec is not None and spec.sharding_rules is not None: 

724 rules = list(spec.sharding_rules()) 

725 if not rules: 

726 return self._classifier.classify(model, arch) 

727 classifier = ParameterClassifier(arch_overrides={arch: rules}) 

728 return classifier.classify(model, arch) 

729 

730 # ── Phase 2 ───────────────────────────────────────────────────────── 

731 

732 def _group_by_boundary( 

733 self, param_roles: Dict[str, ParamRole], 

734 ) -> Dict[str, List[Tuple[str, ParamRole]]]: 

735 """Single deepest-first sweep over the module hierarchy: 

736 

737 Pass 1: group by owning module FQN (strip the leaf parameter name). 

738 Pass 2: materialize ALL ancestor modules upfront and sweep them in 

739 strictly decreasing depth — every shallower ancestor is 

740 therefore inferred only after ALL its descendants' parameters 

741 have merged into it. On ``unknown`` the whole group's 

742 parameters merge upward into the parent module. If still 

743 unknown after backtracking to the root, attribute the group 

744 to the parameter's own module (no template will match later 

745 → warning and skip). 

746 

747 (Fix for the merge-ordering hazard of the former tail-enqueue work 

748 queue: a parent enqueued by an early child — e.g. the MoE gate — 

749 was inferred before later descendants — e.g. the experts subtree — 

750 had merged into it, and the late parameters were then silently 

751 dropped into an already-consumed module. Accuracy fix F3 made this 

752 observable: a MOE_GATE-only ``mlp`` group must merge upward, which 

753 stranded the experts params entirely.) 

754 """ 

755 # Pass 1 

756 own: Dict[str, List[Tuple[str, ParamRole]]] = {} 

757 for fqn, role in param_roles.items(): 

758 module_fqn = ".".join(fqn.split(".")[:-1]) 

759 own.setdefault(module_fqn, []).append((fqn, role)) 

760 

761 # Pass 2 

762 all_modules = set(own) 

763 for mfqn in own: 

764 parts = mfqn.split(".") 

765 for i in range(1, len(parts)): 

766 all_modules.add(".".join(parts[:i])) 

767 merged: Dict[str, List[Tuple[str, ParamRole]]] = { 

768 mfqn: list(own.get(mfqn, [])) for mfqn in all_modules 

769 } 

770 groups: Dict[str, List[Tuple[str, ParamRole]]] = {} 

771 for mfqn in sorted(all_modules, key=lambda f: f.count("."), 

772 reverse=True): 

773 params = merged[mfqn] 

774 if not params: 

775 continue 

776 if self._infer_boundary_type(mfqn, params) != "unknown": 

777 groups[mfqn] = params 

778 else: 

779 parent = mfqn.rsplit(".", 1)[0] if "." in mfqn else "" 

780 if parent: 

781 merged[parent].extend(params) 

782 else: 

783 # Still unknown after backtracking to the root: 

784 # attribute each parameter to its own module (no template 

785 # will match later → skipped). Unrelated unknown 

786 # subtrees may have merged at the root, so anchoring the 

787 # whole group to the first parameter would produce invalid 

788 # relative names for the remaining parameters. 

789 for param_fqn, role in params: 

790 origin = param_fqn.rpartition(".")[0] 

791 groups.setdefault(origin, []).append((param_fqn, role)) 

792 return groups 

793 

794 # ── Phase 3 ───────────────────────────────────────────────────────── 

795 

796 @staticmethod 

797 def _explicit_boundary_type(fqn_lower: str, segment: str) -> Optional[str]: 

798 """Return an explicit FQN-based boundary type when one matches.""" 

799 if _match_any( 

800 fqn_lower, 

801 ["embed_tokens", "wte", ".embed.", "tok_embeddings", "embed_in", "word_embeddings"], 

802 ): 

803 return "embed" 

804 if _match_any(fqn_lower, ["lm_head", "embed_out", "output_layer"]): 

805 return "lm_head" 

806 if _match_any(fqn_lower, ["norm", "layernorm", "rmsnorm", "ln_"]): 

807 return "norm" 

808 if _match_any(segment, ["router"]): 

809 return "moe_gate" 

810 return None 

811 

812 @staticmethod 

813 def _moe_boundary_type(fqn: str, roles: set[ParamRole]) -> Optional[str]: 

814 """Return the boundary type implied by MoE-specific parameter roles.""" 

815 if ParamRole.MOE_EXPERT in roles: 

816 return "moe_mlp" if _match_any(_last_segment(fqn), list(_MOE_CONTAINER_PATTERNS)) else "unknown" 

817 if ParamRole.SHARED_EXPERT in roles: 

818 return "mlp" 

819 if ParamRole.MOE_GATE in roles: 

820 return "unknown" 

821 return None 

822 

823 @staticmethod 

824 def _dense_boundary_type(fqn_lower: str, group: List[Tuple[str, ParamRole]]) -> str: 

825 """Infer an attention or MLP boundary from dense parameter roles.""" 

826 has_colwise = any( 

827 role in (ParamRole.COLWISE, ParamRole.FUSED_QKV, ParamRole.FUSED_GATE_UP) 

828 for _, role in group 

829 ) 

830 has_rowwise = any(role == ParamRole.ROWWISE for _, role in group) 

831 if has_colwise and has_rowwise: 

832 if _match_any(fqn_lower, list(_ATTN_PATTERNS)): 

833 return "attention" 

834 if _match_any(fqn_lower, list(_MLP_PATTERNS)): 

835 return "mlp" 

836 return "attention" 

837 if has_colwise and _match_any(fqn_lower, list(_MLP_PATTERNS)): 

838 return "mlp" 

839 return "unknown" 

840 

841 def _infer_boundary_type(self, fqn: str, group: List[Tuple[str, ParamRole]]) -> str: 

842 """Identify the semantic role from the module FQN + the group's 

843 parameter roles. 

844 

845 Priority: explicit FQN patterns > leaf-segment guard > MoE roles > 

846 parameter role combinations > default. 

847 """ 

848 fqn_lower = fqn.lower() 

849 seg = _last_segment(fqn) 

850 

851 explicit_type = self._explicit_boundary_type(fqn_lower, seg) 

852 if explicit_type is not None: 

853 return explicit_type 

854 

855 # 2. Leaf-segment guard: projection/expert leaf modules are not 

856 # boundary containers themselves 

857 if seg in _LEAF_SEGMENT_GUARD: 

858 return "unknown" 

859 # Numeric-segment guard: HF per-expert containers (experts.0..N) are 

860 # not boundaries; parameters must aggregate upward into the moe 

861 # container (D-09, 05 §6.4.7) 

862 if seg.isdigit(): 

863 return "unknown" 

864 

865 # 3. MoE roles (accuracy fix F3, accuracy_fix_plan.md §2): 

866 # structural lint — a "moe_mlp" boundary must contain routed experts 

867 # (MOE_EXPERT); a MOE_GATE-only group (e.g. a scalar gate Linear 

868 # misclassified as router) must NOT anchor a MoE boundary. Container 

869 # identity is judged on the module's OWN last segment, not a 

870 # substring of the whole FQN (a parent path segment like "mlp" must 

871 # not qualify a leaf Linear such as shared_expert_gate). 

872 roles = {r for _, r in group} 

873 moe_type = self._moe_boundary_type(fqn, roles) 

874 return moe_type if moe_type is not None else self._dense_boundary_type(fqn_lower, group) 

875 

876 # ── Phase 4 post-processing: MoE EP marking (D-09/D-10, 05 §6.4.7/§6.4.8) ── 

877 

878 @staticmethod 

879 def _validate_ep_domain(ep_extend, mesh) -> None: 

880 """Validate that virtual EP evenly partitions the dense rank domain. 

881 

882 The dense region = all ranks of the non-pp mesh axes 

883 (dp_replicate × dp_cp × tp). 

884 """ 

885 names = tuple(getattr(mesh, "mesh_dim_names", ()) or ()) 

886 shape = tuple(getattr(mesh, "mesh_shape", ()) or ()) 

887 domain = 1 

888 for name, size in zip(names, shape): 

889 if name == "pp" and size > 1: 

890 raise NotImplementedError( 

891 "virtual EP v1 does not support pp>1 " 

892 "(split the mesh by stage before calling)" 

893 ) 

894 if name != "pp": 

895 domain *= size 

896 if ep_extend > domain or domain % ep_extend != 0: 

897 raise ValueError( 

898 f"ep_size ({ep_extend}) must not exceed and must divide " 

899 f"the dense region (dp_replicate × dp_cp × tp = {domain})" 

900 ) 

901 

902 @classmethod 

903 def _validate_ep_extend(cls, ep_extend, mesh, model) -> None: 

904 """Validate virtual EP plus the routed-expert count constraint.""" 

905 cls._validate_ep_domain(ep_extend, mesh) 

906 num_experts = (getattr(getattr(model, "config", None), "num_experts", None) 

907 or getattr(getattr(model, "config", None), "n_routed_experts", 0)) 

908 if num_experts and num_experts % ep_extend != 0: 

909 raise ValueError( 

910 f"num_experts ({num_experts}) must be divisible by ep_size ({ep_extend})" 

911 ) 

912 

913 @classmethod 

914 def _mark_virtual_ep_parameters( 

915 cls, 

916 plan: ShardingPlan, 

917 ep_size: int, 

918 mesh: DeviceMesh, 

919 ) -> None: 

920 """Map explicit virtual-EP parameters to the derived expert mesh. 

921 

922 This deliberately keys off placement semantics rather than parameter 

923 names, so routed experts and sparse lookup tables use one mechanism. 

924 The boundary still has to inject its matching all-to-all computation. 

925 """ 

926 if ep_size <= 1 or "ep" in tuple(getattr(mesh, "mesh_dim_names", ()) or ()): 

927 return 

928 marked = [] 

929 for fqn, spec in plan.modules.items(): 

930 if getattr(spec, "_ep_size", 0): # pylint: disable=protected-access 

931 continue 

932 ep_params = [ 

933 name 

934 for name, named in (spec.params or {}).items() 

935 if isinstance((named or {}).get(EP), Shard) 

936 ] 

937 if ep_params: 

938 spec._ep_size = ep_size # pylint: disable=protected-access 

939 marked.append((fqn, ep_params)) 

940 if not marked: 

941 return 

942 cls._validate_ep_domain(ep_size, mesh) 

943 logger.info( 

944 "virtual EP: mapped explicitly EP-sharded parameters to the " 

945 "derived expert mesh: %s", 

946 marked, 

947 ) 

948 

949 # per-expert parameter pattern: experts.<idx>.<proj>.weight (legacy HF / 

950 # in-house MoE layouts). 

951 _PER_EXPERT_RE = re.compile(r"^experts\.(\d+)\.([^.]+)\.weight$") 

952 # batched parameter pattern: experts.<attr> (a single attribute with no 

953 # numeric segment, the layout after the HF 2025 refactor — 

954 # gate_up_proj [E, 2I, H] / down_proj [E, H, I], natively stacked with 

955 # no stacking needed; the automodel names gate_and_up_projs/down_projs 

956 # are isomorphic). 

957 _BATCHED_EXPERT_RE = re.compile( 

958 r"^experts\.(gate_up_proj|gate_and_up_projs|down_proj|down_projs" 

959 r"|gate_proj|up_proj)$") 

960 # Fused (gate|up merged into ONE parameter, chunk-split inside forward) 

961 # expert weight pattern — covers both the batched 3D layout 

962 # (``experts.gate_up_proj [E, 2I, H]``) and the per-expert 2D layout 

963 # (``experts.<idx>.gate_up_proj.weight [2I, H]``). Such weights are 

964 # incompatible with contiguous-block TP Shard on the fused dim; see 

965 # _finalize_fused_expert_tp_guard. 

966 _FUSED_EXPERT_WEIGHT_RE = re.compile( 

967 r"^experts\.(?:\d+\.)?(?:gate_up_proj|gate_and_up_projs" 

968 r"|fused_gate_up|w13)(?:\.weight)?$") 

969 

970 def _detect_expert_layout(self, group, boundary_fqn: str, param_ndims): 

971 """Return expert parameters grouped by per-expert and batched layouts.""" 

972 expert_params = [fqn for fqn, role in group if role == ParamRole.MOE_EXPERT] 

973 if not expert_params: 

974 return None 

975 stacks: Dict[str, List[Tuple[int, str]]] = {} 

976 batched: List[str] = [] 

977 for param_fqn in expert_params: 

978 rel = param_fqn[len(boundary_fqn) + 1:] 

979 if "bias" in rel.lower(): 

980 logger.warning( 

981 "%s: MoE expert has bias (%s); not supported in v1, skipping EP marking", 

982 boundary_fqn, rel, 

983 ) 

984 return None 

985 match = self._PER_EXPERT_RE.match(rel) 

986 if match is not None: 

987 stacks.setdefault(match.group(2), []).append((int(match.group(1)), rel)) 

988 elif self._BATCHED_EXPERT_RE.match(rel) is not None and (param_ndims or {}).get(param_fqn, 2) >= 3: 

989 batched.append(rel) 

990 if stacks and batched: 

991 logger.warning( 

992 "%s: mixed per-expert and batched layouts (%s ...); skipping EP marking", 

993 boundary_fqn, batched[0], 

994 ) 

995 return None 

996 return expert_params, stacks, batched 

997 

998 @staticmethod 

999 def _mark_old_style_experts( 

1000 spec: ModuleShardingSpec, 

1001 stacks: Dict[str, List[Tuple[int, str]]], 

1002 template: ShardingTemplate, 

1003 ) -> None: 

1004 """Stack per-expert parameters while retaining explicit TP and EP axes.""" 

1005 for projection, items in stacks.items(): 

1006 items.sort() 

1007 sources = [rel for _, rel in items] 

1008 stacked = f"experts.{projection}" 

1009 tp_placement = _moe_expert_tp_placement(stacked, ndim=3, template=template) 

1010 for rel in sources: 

1011 spec.params.pop(rel, None) 

1012 spec.params[stacked] = _multi_dim( 

1013 tp=tp_placement, cp=Replicate(), ep=template.moe_expert_placement 

1014 ) 

1015 spec._ep_stack[stacked] = sources # pylint: disable=protected-access # planner owns the spec DSL internals 

1016 

1017 @staticmethod 

1018 def _mark_extended_expert_params( 

1019 spec: ModuleShardingSpec, 

1020 expert_params: List[str], 

1021 stacks: Dict[str, List[Tuple[int, str]]], 

1022 batched: List[str], 

1023 boundary_fqn: str, 

1024 template: ShardingTemplate, 

1025 ) -> None: 

1026 """Mark expert parameters for TP-extended EP sharding.""" 

1027 if stacks: 

1028 for projection, items in stacks.items(): 

1029 items.sort() 

1030 sources = [rel for _, rel in items] 

1031 stacked = f"experts.{projection}" 

1032 for rel in sources: 

1033 spec.params.pop(rel, None) 

1034 spec.params[stacked] = _multi_dim( 

1035 tp=None, cp=Replicate(), ep=template.moe_expert_placement 

1036 ) 

1037 # The planner owns the spec DSL internals. 

1038 spec._ep_stack[stacked] = sources # pylint: disable=protected-access 

1039 spec.region_dispatch = None 

1040 return 

1041 if batched: 

1042 for rel in batched: 

1043 spec.params[rel] = _multi_dim( 

1044 tp=None, cp=Replicate(), ep=template.moe_expert_placement 

1045 ) 

1046 spec.region_dispatch = None 

1047 return 

1048 for param_fqn in expert_params: 

1049 rel = param_fqn[len(boundary_fqn) + 1:] 

1050 spec.params[rel] = _multi_dim( 

1051 tp=None, cp=Replicate(), ep=template.moe_expert_placement 

1052 ) 

1053 

1054 @staticmethod 

1055 def _set_extended_ep_contract(spec: ModuleShardingSpec, ep_extend: int) -> None: 

1056 """Set the identity boundary contract used by TP-extended EP.""" 

1057 identity = copy.deepcopy(spec.in_src) 

1058 spec.in_dst = copy.deepcopy(identity) 

1059 out_layout = copy.deepcopy(next(iter(identity.values()))) 

1060 spec.out_src = {"output": copy.deepcopy(out_layout)} 

1061 spec.out_dst = {"output": copy.deepcopy(out_layout)} 

1062 spec._ep_size = ep_extend # pylint: disable=protected-access # planner owns the spec DSL internals 

1063 

1064 def _mark_hf_native_moe( 

1065 self, spec: ModuleShardingSpec, group, boundary_fqn: str, 

1066 template: ShardingTemplate, mesh_dim_names: Tuple[str, ...], arch: str, 

1067 *, ep_extend: int = 0, mesh=None, model=None, param_ndims=None, 

1068 ) -> None: 

1069 """Post-process moe_mlp spec for EP (05 §6.4.7/§6.4.8). 

1070 

1071 The EP **mode** is determined solely by whether the mesh includes an 

1072 explicit ``"ep"`` axis — NOT by parameter naming: 

1073 

1074 * **Old-style EP** (``"ep" in mesh_dim_names``): the mesh already has 

1075 an ``"ep"`` axis. :meth:`_build_spec_from_template` produced 

1076 ``{TP: Shard(…), EP: Shard(0)}`` — the correct dual-axis 

1077 sharding. This method only performs **stacking** when the expert 

1078 layout is per-expert 2D (``experts.<idx>.<proj>.weight``); the 

1079 stacked entry keeps both TP and EP keys. Batched 3D and custom 

1080 (``w1``/``w2``/``w3``) layouts are already ready — nothing to do. 

1081 No ``_ep_size`` is set; communication is handled by the module's 

1082 own dispatcher or external ``_attach_ep``. 

1083 

1084 * **D-10 TP-extend-EP** (``"ep" not in mesh_dim_names``, the 

1085 default for HF-native models): the ep group is *derived* from the 

1086 dense region. Expert weights are rewritten to 

1087 ``{EP: Shard(0)}`` (no TP key), the boundary contract is changed 

1088 to SP-in identity, and ``_ep_size`` is set. 

1089 

1090 The expert **layout** (per-expert / batched / custom) only affects 

1091 the *stacking strategy* — orthogonal to the EP mode: 

1092 

1093 - **per-expert**: ``experts.<idx>.<proj>.weight`` → stack into 

1094 ``experts.<proj>`` 3D before sharding; 

1095 - **batched** (D-11): ``experts.gate_up_proj`` etc., natively 3D; 

1096 - **custom**: ``experts.w1`` / ``w2`` / ``w3``, already 3D, 

1097 pre-stacked by the module author. 

1098 

1099 In D-10 mode all three layouts are supported; in old-style EP mode 

1100 only per-expert needs stacking (batched and custom are already 3D). 

1101 """ 

1102 # ``arch`` is part of the dispatch-interface signature shared with the 

1103 # other boundary post-processors; the EP mode is decided by the mesh 

1104 # and layout alone, so it is intentionally unused here. 

1105 _ = arch 

1106 if not ep_extend: 

1107 return 

1108 layout = self._detect_expert_layout(group, boundary_fqn, param_ndims) 

1109 if layout is None: 

1110 return 

1111 expert_params, stacks, batched = layout 

1112 if "ep" in mesh_dim_names: 

1113 if stacks: 

1114 self._mark_old_style_experts(spec, stacks, template) 

1115 return 

1116 self._validate_ep_extend(ep_extend, mesh, model) 

1117 self._mark_extended_expert_params( 

1118 spec, expert_params, stacks, batched, boundary_fqn, template 

1119 ) 

1120 self._set_extended_ep_contract(spec, ep_extend) 

1121 

1122 

1123 @staticmethod 

1124 def _finalize_fused_expert_tp_guard(plan: ShardingPlan, *, tp_size: int) -> None: 

1125 """Fail fast on fused expert weights TP-sharded without D-10 EP. 

1126 

1127 A fused expert weight (gate/up merged into ONE parameter — e.g. 

1128 ``experts.gate_up_proj [E, 2I, H]`` — and chunk-split inside the 

1129 module's forward) is incompatible with the framework's 

1130 contiguous-block TP ``Shard`` on the fused dim: after Phase A each 

1131 rank holds a contiguous slice of the fused dim (tp=2 → rank0 all 

1132 gate, rank1 all up), so the runtime ``chunk`` result is NOT 

1133 equivalent to the non-TP semantics (Megatron solves this with 

1134 chunk-aware sharding, which the framework does not support). The 

1135 error is silent: the MoE boundary is local-region black-box hosted 

1136 in BOTH modes, so production and validate run the same (wrong) 

1137 local forward and the dual-mode comparison cannot expose it. 

1138 

1139 Runs AFTER all plan_overrides are merged (next to 

1140 ``_finalize_deferred_biases``) and anchors detection on the FINAL 

1141 spec declarations, so an explicit TP-Replicate override on the 

1142 fused params legitimately clears the hazard. D-10 TP-extend-EP 

1143 (``_ep_size > 0``) removes the TP key from expert weights entirely 

1144 (each rank holds complete experts), so it is exempt. 

1145 """ 

1146 if tp_size <= 1: 

1147 return 

1148 offenders = [] 

1149 for fqn, spec in plan.modules.items(): 

1150 if getattr(spec, "_ep_size", 0): # pylint: disable=protected-access 

1151 # D-10 TP-extend-EP: expert weights carry no TP shard — the 

1152 # fused dim stays complete per rank, chunk is correct. 

1153 continue 

1154 for param_name, named in (spec.params or {}).items(): 

1155 if not isinstance(named, dict): 

1156 continue 

1157 if ShardingPlanner._FUSED_EXPERT_WEIGHT_RE.match(param_name) is None: 

1158 continue 

1159 if isinstance(named.get(TP), Shard): 

1160 offenders.append((fqn, param_name, named[TP])) 

1161 if not offenders: 

1162 return 

1163 listing = "\n".join( 

1164 f" - {fqn}.{param_name} → {{TP: {placement}, ...}}" 

1165 for fqn, param_name, placement in offenders[:8]) 

1166 more = (f"\n ... and {len(offenders) - 8} more" 

1167 if len(offenders) > 8 else "") 

1168 boundary_fqn, example_param, _ = offenders[0] 

1169 raise ValueError( 

1170 f"Detected {len(offenders)} fused MoE expert weight(s) (gate/up " 

1171 "merged into a single parameter, chunk-split inside forward) " 

1172 "declared with TP sharding:\n" 

1173 f"{listing}{more}\n" 

1174 "This pattern is incompatible with the framework's contiguous-" 

1175 "block TP Shard: after Phase A shards the fused dim contiguously, " 

1176 "each rank holds a slice whose gate/up layout is misordered, so " 

1177 "the runtime chunk is NOT equivalent to the non-TP semantics " 

1178 "(Megatron handles this with chunk-aware sharding, which the " 

1179 "framework does not support). Worse, the error is silent: the " 

1180 "MoE boundary is local-region black-box hosted in BOTH modes, so " 

1181 "production and validate run the same (wrong) local forward and " 

1182 "the dual-mode comparison cannot expose the accuracy corruption. " 

1183 "Choose one of:\n" 

1184 " (1) Enable ep_size (recommended): " 

1185 "ShardingPlanner().plan(..., ep_size=N) with N>1, N dividing the " 

1186 "dense region dp*cp*tp and dividing num_experts. Enabling ep_size " 

1187 "takes the TP-extend-EP path (design revision D-10): the dense " 

1188 "region is re-partitioned into the derived expert mesh " 

1189 "(edp_shard, ep), and expert weights are sharded ONLY as " 

1190 "{EP: Shard(0)} along the expert dim with NO TP key — every rank " 

1191 "holds complete experts, so the gate/up produced by the runtime " 

1192 "chunk matches the non-parallel semantics. Note: the MoE " 

1193 "boundary must then also declare local_compute_fn explicitly " 

1194 "(EP compute injection; the apply-time preflight checks this and " 

1195 "prints a YAML example).\n" 

1196 " (2) Keep ep=1: override the fused weight to TP Replicate via " 

1197 "plan_overrides (it then opts out of TP sharding and saves no " 

1198 "memory for that weight), e.g.:\n" 

1199 " ShardingPlanner(plan_overrides={\n" 

1200 f" {boundary_fqn!r}: ModuleShardingSpec(\n" 

1201 " params={\n" 

1202 f" {example_param!r}: " 

1203 "{TP: Replicate(), CP: Replicate()},\n" 

1204 " # ...declare ALL params of this boundary too " 

1205 "(experts.down_proj / gate.weight etc.) — params merge replaces " 

1206 "the field wholesale (no per-key merge)\n" 

1207 " },\n" 

1208 " # out_src TP must ALSO be changed from the template-" 

1209 "derived Partial to Replicate: with replicated weights each " 

1210 "rank's MoE output is already complete (not Partial); keeping " 

1211 "Partial would make the boundary exit reduction count the " 

1212 "output tp_size times\n" 

1213 " out_src={'output': {TP: Replicate(), CP: Replicate()}}," 

1214 " # keep the template-derived CP value (Shard(1) when " 

1215 "sequence_parallel is on)\n" 

1216 " ),\n" 

1217 " })\n" 

1218 " (3) Switch to separate w1/w3 expert weights (gate_proj and " 

1219 "up_proj as independent parameters) — natively supported, no " 

1220 "override needed.") 

1221 

1222 @staticmethod 

1223 def _should_defer_rowwise_bias( 

1224 module_fqn: str, 

1225 module: nn.Module, 

1226 owner_path: str, 

1227 param_name: str, 

1228 bias_tp, 

1229 out_src, 

1230 partial_outputs: List[str], 

1231 ) -> bool: 

1232 """Validate a rowwise bias and return whether it must be deferred.""" 

1233 if not partial_outputs: 

1234 return False 

1235 if len(out_src) != 1: 

1236 raise ValueError( 

1237 f"boundary {module_fqn!r}: rowwise bias deferral (D-22) v1 only supports single-output " 

1238 f"boundaries — this boundary's out_src declares {len(out_src)} outputs with a TP Partial " 

1239 f"reduction, so the framework cannot attribute {param_name!r} to a unique output. Take over " 

1240 "the region with local_compute_fn (add the bias yourself after the reduction)" 

1241 ) 

1242 if bias_tp is not None and not isinstance(bias_tp, Replicate): 

1243 raise ValueError( 

1244 f"boundary {module_fqn!r}: the bias of rowwise Linear {owner_path!r} declares a non-Replicate " 

1245 f"TP placement ({bias_tp!r}) — D-22 deferred addition requires the bias to stay Replicate " 

1246 f"(added exactly once as a whole after the TP reduction). Remove {param_name!r} from " 

1247 "spec.params, or change it to {TP: replicate()}" 

1248 ) 

1249 owner = module.get_submodule(owner_path) if owner_path else module 

1250 if isinstance(owner, nn.Linear): 

1251 return True 

1252 logger.warning( 

1253 "boundary %s: rowwise Linear %r carries a bias and the boundary out_src is TP Partial — but " 

1254 "the owner type is %s (not nn.Linear), so the framework does not touch its forward semantics: " 

1255 "the bias will be counted multiple times by the Partial reduction (production output = correct " 

1256 "value + tp_size × bias). Move the bias after the boundary communication, switch to nn.Linear, " 

1257 "or take over the region with local_compute_fn", 

1258 module_fqn, owner_path, type(owner).__name__, 

1259 ) 

1260 return False 

1261 

1262 @staticmethod 

1263 def _validate_colwise_bias( 

1264 module_fqn: str, 

1265 weight_path: str, 

1266 param_name: str, 

1267 param, 

1268 bias_named, 

1269 bias_tp, 

1270 shard_dim: int, 

1271 ) -> None: 

1272 """Require a colwise bias to follow its weight's output shard.""" 

1273 bias_dim = None 

1274 if isinstance(bias_tp, Shard): 

1275 bias_dim = bias_tp.dim if bias_tp.dim >= 0 else bias_tp.dim + param.ndim 

1276 if bias_dim == shard_dim: 

1277 return 

1278 declared = repr(bias_tp) if bias_named else "undeclared" 

1279 raise ValueError( 

1280 f"boundary {module_fqn!r}: {weight_path!r} is sharded along the output dim as Shard({shard_dim}), " 

1281 f"but {param_name!r} is not sharded along the output channels the same way ({declared}) — " 

1282 f"template mismatch (typical: lm_head.bias). Declare it explicitly via plan_overrides as " 

1283 f"{{'{param_name}': {{TP: shard({shard_dim})}}}}, or remove the bias" 

1284 ) 

1285 

1286 @staticmethod 

1287 def _bias_owner_path(param_name: str) -> Optional[str]: 

1288 """Return a bias owner's module path, or ``None`` for other params.""" 

1289 if param_name == "bias": 

1290 return "" 

1291 if param_name.endswith(".bias"): 

1292 return param_name[: -len(".bias")] 

1293 return None 

1294 

1295 @staticmethod 

1296 def _collect_deferred_biases(module_fqn: str, spec: ModuleShardingSpec, module: nn.Module) -> List[str]: 

1297 """Validate one boundary's biases and collect rowwise deferred names.""" 

1298 named_params = dict(module.named_parameters()) 

1299 out_src = spec.out_src or {} 

1300 partial_outputs = [ 

1301 out_name for out_name, named in out_src.items() if isinstance(named.get(TP), Partial) 

1302 ] 

1303 deferred: List[str] = [] 

1304 for param_name, param in named_params.items(): 

1305 owner_path = ShardingPlanner._bias_owner_path(param_name) 

1306 if owner_path is None: 

1307 continue 

1308 weight_path = f"{owner_path}.weight" if owner_path else "weight" 

1309 weight = named_params.get(weight_path) 

1310 tp_placement = (spec.params or {}).get(weight_path) 

1311 if weight is None or tp_placement is None: 

1312 continue 

1313 tp_placement = tp_placement.get(TP) 

1314 if not isinstance(tp_placement, Shard): 

1315 continue 

1316 shard_dim = tp_placement.dim if tp_placement.dim >= 0 else tp_placement.dim + weight.ndim 

1317 bias_tp = spec.params.get(param_name) 

1318 bias_tp = bias_tp.get(TP) if bias_tp else None 

1319 if shard_dim == weight.ndim - 1: 

1320 if ShardingPlanner._should_defer_rowwise_bias( 

1321 module_fqn, module, owner_path, param_name, bias_tp, out_src, partial_outputs 

1322 ): 

1323 deferred.append(param_name) 

1324 else: 

1325 ShardingPlanner._validate_colwise_bias( 

1326 module_fqn, weight_path, param_name, param, spec.params.get(param_name), bias_tp, shard_dim 

1327 ) 

1328 return deferred 

1329 

1330 @staticmethod 

1331 def _finalize_deferred_biases( 

1332 plan: ShardingPlan, model, mesh_dim_names: Tuple[str, ...], 

1333 ) -> None: 

1334 """D-22: decide which Linear biases are deferred to after the boundary 

1335 exit TP reduction, and validate every bias against its sibling weight's 

1336 sharding direction. 

1337 

1338 Runs AFTER all plan_overrides are merged (next to 

1339 ``_finalize_tp_local_attr_plans``) and anchors detection on the FINAL 

1340 spec declarations plus the model structure — never on ParamRole — so 

1341 derived / merge / insert / derive=False specs (and family sharding-rule 

1342 naming like ``wo``/``c_proj``) all share one code path. 

1343 

1344 Per boundary, for every physical ``X.bias`` parameter (scanned from 

1345 the module, regardless of whether spec.params declares it — a 

1346 physically present bias is fused by F.linear either way): 

1347 

1348 - sibling ``X.weight`` TP placement is ``Shard(weight.ndim - 1)`` 

1349 (contraction-dim = rowwise) AND the boundary out_src reduces on TP 

1350 (Partial) → the fused bias would be counted once per TP rank by the 

1351 exit reduction → defer it (bias stays Replicate, added exactly once 

1352 after the reduction). Fail-fast guards: a declared non-Replicate 

1353 bias placement is rejected; a non-nn.Linear owner gets a WARNING 

1354 and is skipped (its forward semantics are not touched); a 

1355 multi-output boundary cannot attribute the bias to one output → 

1356 fail-fast (use local_compute_fn). 

1357 - sibling ``X.weight`` TP placement is an output-dim ``Shard(d)`` 

1358 (colwise / lm_head / embed) → the bias must follow the same output 

1359 shard; Replicate / undeclared / wrong-dim → plan-time "template 

1360 mismatch" 

1361 error (typical: lm_head.bias), instead of a remote runtime 

1362 broadcast crash. 

1363 - out_src without a TP Partial (no boundary reduction, or the user 

1364 reduces inside the region) → the bias is already added exactly once 

1365 → no defer, no check. 

1366 """ 

1367 has_tp = "tp" in mesh_dim_names 

1368 modules = dict(model.named_modules()) 

1369 for module_fqn, spec in plan.modules.items(): 

1370 spec._deferred_bias_params = () # pylint: disable=protected-access 

1371 if not has_tp or not spec.is_boundary: 

1372 continue 

1373 module = modules.get(module_fqn) 

1374 if module is None: 

1375 continue 

1376 deferred = ShardingPlanner._collect_deferred_biases(module_fqn, spec, module) 

1377 spec._deferred_bias_params = tuple(deferred) # pylint: disable=protected-access 

1378 if deferred: 

1379 logger.info( 

1380 "boundary %s: deferred bias (D-22, added exactly once " 

1381 "after the TP reduction): %s", 

1382 module_fqn, list(deferred)) 

1383 

1384 @staticmethod 

1385 def _check_param_uniqueness(plan: ShardingPlan) -> None: 

1386 """D-14 invariant 1 (05 §13.3): every parameter is sharded by exactly 

1387 one boundary. spec.params keys are resolved to full parameter FQNs 

1388 (relative to the boundary module); any parameter declared by ≥2 specs 

1389 fails fast (double sharding corrupts silently under production).""" 

1390 seen: Dict[str, str] = {} # full param fqn -> first declaring boundary 

1391 for fqn, spec in plan.modules.items(): 

1392 prefix = fqn + "." if fqn else "" 

1393 for pname in spec.params: 

1394 full = prefix + pname 

1395 if full in seen: 

1396 raise ValueError( 

1397 f"param {full!r} is declared by two boundaries: " 

1398 f"{seen[full]!r} and {fqn!r} — each parameter must be " 

1399 f"sharded by exactly one boundary (D-14, 05 §13.3); " 

1400 f"drop it from one of the specs (an outer boundary " 

1401 f"may only declare params of its own/intermediate " 

1402 f"modules, never of a nested boundary's subtree)" 

1403 ) 

1404 seen[full] = fqn 

1405 

1406 @staticmethod 

1407 def _check_full_declaration(plan: ShardingPlan) -> None: 

1408 """D-14 (05 §13.2): chain fill is removed — every boundary spec must 

1409 fully declare its I/O contract. A non-empty in_dst with an empty 

1410 in_src fails fast (the previous Scenario-1 fill no longer exists).""" 

1411 for fqn, spec in plan.modules.items(): 

1412 if spec.is_boundary and spec.in_dst and not spec.in_src: 

1413 raise ValueError( 

1414 f"boundary {fqn!r} declares in_dst but an empty in_src — " 

1415 f"chain fill was removed (D-14, 05 §13.2); declare in_src " 

1416 f"explicitly (keys must mirror in_dst)" 

1417 ) 

1418 

1419 # ── F4 plan-time lints (accuracy_fix_plan.md §2) ───────────────────── 

1420 

1421 @staticmethod 

1422 def _check_param_shard_divisibility( 

1423 fqn: str, 

1424 prefix: str, 

1425 pname: str, 

1426 placement: Dict[str, Any], 

1427 param_shapes: Dict[str, Tuple[int, ...]], 

1428 ep_stack: Dict[str, List[str]], 

1429 axis_sizes: Dict[str, int], 

1430 ) -> None: 

1431 """Check every sharded mesh axis for one declared parameter.""" 

1432 full = prefix + pname 

1433 shape = param_shapes.get(full) 

1434 if shape is None and pname in ep_stack: 

1435 sources = ep_stack[pname] 

1436 shape = param_shapes.get(prefix + sources[0]) if sources else None 

1437 if shape is not None: 

1438 shape = (len(sources), *shape) 

1439 if shape is None: 

1440 return # created later (inner_target factory) — nothing to check 

1441 for axis, p in (placement or {}).items(): 

1442 if not isinstance(p, Shard): 

1443 continue 

1444 size = axis_sizes.get(axis, 1) 

1445 if size <= 1: 

1446 continue 

1447 axis_name = getattr(axis, "value", axis) # MeshAxisName → "tp" 

1448 dim = p.dim + len(shape) if p.dim < 0 else p.dim 

1449 if dim >= len(shape): 

1450 raise ValueError( 

1451 f"plan-time shard check failed: {full!r} has shape " 

1452 f"{tuple(shape)} but boundary {fqn!r} declares " 

1453 f"{{{axis_name}: Shard({p.dim})}} — dim {p.dim} is out " 

1454 f"of range for a {len(shape)}D parameter; fix the " 

1455 f"plan_overrides declaration" 

1456 ) 

1457 if shape[dim] % size != 0: 

1458 raise ValueError( 

1459 f"plan-time shard check failed: {full!r} has shape " 

1460 f"{tuple(shape)} but boundary {fqn!r} declares " 

1461 f"{{{axis_name}: Shard({p.dim})}} — shape[{dim}]={shape[dim]} " 

1462 f"is not divisible by {axis_name} size {size} (it would " 

1463 f"produce empty shards at apply time). This is most " 

1464 f"often a parameter-classification error (e.g. a " 

1465 f"replicated/gate parameter misclassified into a " 

1466 f"sharded role — see accuracy_fix_plan.md §2): fix " 

1467 f"the naming rule / family sharding_rules entry, or correct " 

1468 f"the plan_overrides declaration" 

1469 ) 

1470 

1471 @staticmethod 

1472 def _check_shard_divisibility( 

1473 plan: ShardingPlan, 

1474 param_shapes: Dict[str, Tuple[int, ...]], 

1475 *, 

1476 tp_size: int, 

1477 cp_size: int, 

1478 ep_size: int, 

1479 ) -> None: 

1480 """F4a: every Shard(dim) in every spec.params must divide the 

1481 parameter's shape along that dim — fail at plan time with a teaching 

1482 error instead of producing an empty shard at apply time 

1483 (accuracy_problem.md 10.1: a (1, 64) scalar-gate weight misclassified 

1484 SHARED_EXPERT was Shard(0)'d over tp=2 into a (0, 64) empty shard, 

1485 surfacing only much later at weight reconstruction). 

1486 

1487 Runs after the Phase 4.5 override merge, so hand-written specs are 

1488 checked too. Stacked expert params (D-09/D-10 ``_ep_stack``) resolve 

1489 their shape as ``(num_experts, *source_shape)``; D-10 experts use 

1490 ``spec._ep_size`` as the EP axis size. Params not resolvable at plan 

1491 time (e.g. created later by an inner_target factory) are skipped. 

1492 """ 

1493 for fqn, spec in plan.modules.items(): 

1494 prefix = fqn + "." if fqn else "" 

1495 ep_stack = getattr(spec, "_ep_stack", None) or {} 

1496 # D-10: the EP axis lives on the derived expert mesh whose size 

1497 # is spec._ep_size; old-style EP uses the mesh "ep" axis (ep_size). 

1498 axis_sizes = { 

1499 "tp": tp_size, 

1500 "cp": cp_size, 

1501 "ep": getattr(spec, "_ep_size", 0) or ep_size, 

1502 } 

1503 for pname, placement in (spec.params or {}).items(): 

1504 ShardingPlanner._check_param_shard_divisibility( 

1505 fqn, prefix, pname, placement, param_shapes, ep_stack, axis_sizes 

1506 ) 

1507 

1508 @staticmethod 

1509 def _declared_parameter_names(plan: ShardingPlan) -> set[str]: 

1510 """Collect full names covered by placements and special handlers.""" 

1511 covered = set() 

1512 for fqn, spec in plan.modules.items(): 

1513 prefix = fqn + "." if fqn else "" 

1514 for pname in (spec.params or {}): 

1515 covered.add(prefix + pname) 

1516 for sources in (getattr(spec, "_ep_stack", None) or {}).values(): 

1517 covered.update(prefix + source for source in sources) 

1518 covered.update(plan.special_handlers or {}) 

1519 return covered 

1520 

1521 def _check_all_trainable_params_covered(self, plan: ShardingPlan, model) -> None: 

1522 """F4b: every ``requires_grad=True`` parameter must appear in some 

1523 spec.params (resolved to a full FQN) or in special_handlers — 

1524 otherwise its gradient-sync semantics would be decided SILENTLY by 

1525 the consumer-side default (the same class of shape-legal/silent-wrong 

1526 hazard as accuracy_problem.md 10.1/10.2), so the plan must be a 

1527 complete declaration of every trainable parameter's layout. 

1528 

1529 Covered = spec.params ∪ _ep_stack sources ∪ special_handlers (a 

1530 param explicitly declared via plan_overrides therefore counts as 

1531 covered). Remediation paths, listed per parameter in the error: 

1532 ① classify it explicitly (naming rule / the family's sharding_rules, e.g. 

1533 shared_expert_gate → REPLICATED); 

1534 ② declare it in a spec via plan_overrides (e.g. all-Replicate); 

1535 ③ mark it SPECIAL (special_handlers) or freeze it 

1536 (requires_grad=False). 

1537 Escape hatch for exploratory debugging: 

1538 ``ShardingPlanner(allow_uncovered_params=True)`` downgrades to a 

1539 warning. Skipped entirely under derive=False (pure declaration 

1540 assembler for subtrees — coverage is the caller's responsibility). 

1541 """ 

1542 if not self._derive: 

1543 return 

1544 covered = self._declared_parameter_names(plan) 

1545 covered.update(plan.owned_parameter_names) 

1546 uncovered = [ 

1547 name for name, p in model.named_parameters() 

1548 if p.requires_grad and name not in covered 

1549 ] 

1550 if not uncovered: 

1551 return 

1552 lines = "\n".join(f" - {n}" for n in uncovered[:20]) 

1553 more = (f" ... and {len(uncovered) - 20} more\n" 

1554 if len(uncovered) > 20 else "") 

1555 msg = ( 

1556 f"plan-time coverage check failed: {len(uncovered)} trainable " 

1557 f"parameter(s) are not covered by any spec.params / " 

1558 f"special_handlers:\n{lines}\n{more}" 

1559 "An uncovered parameter is never sharded (kept replicated) AND is " 

1560 "absent from source_shard_info — its gradient-sync semantics would be " 

1561 "decided silently by the consumer-side default. Resolve each " 

1562 "parameter explicitly: ① add a naming rule / a family sharding_rules " 

1563 "entry " 

1564 "(e.g. shared_expert_gate → REPLICATED); ② declare it in a spec " 

1565 "via plan_overrides; ③ mark it SPECIAL or freeze it " 

1566 "(requires_grad=False). For exploratory debugging only, construct " 

1567 "ShardingPlanner(allow_uncovered_params=True) to downgrade this " 

1568 "error to a warning (accuracy_fix_plan.md §2 F4b)" 

1569 ) 

1570 if self._allow_uncovered_params: 

1571 logger.warning("%s", msg) 

1572 else: 

1573 raise ValueError(msg) 

1574 

1575 # ── Phase 5 ───────────────────────────────────────────────────────── 

1576 

1577 def _mark_terminal(self, plan: ShardingPlan, model) -> ShardingPlan: 

1578 """D-14 (05 §13.2): compile-time chain propagation/validation is 

1579 removed; only ``_is_terminal`` marking is kept — the last boundary 

1580 in forward order (each module vouches for its own propagation in 

1581 validate mode; adjacent-contract checks no longer exist).""" 

1582 boundaries = [fqn for fqn, spec in plan.modules.items() if spec.is_boundary] 

1583 sorted_fqns = self._topological_sort_by_forward_order(boundaries, model) 

1584 terminal = sorted_fqns[-1] if sorted_fqns else None 

1585 for fqn, spec in plan.modules.items(): 

1586 # The planner owns the spec DSL internals. 

1587 spec._is_terminal = fqn == terminal # pylint: disable=protected-access 

1588 return plan 

1589 

1590 @staticmethod 

1591 def _topological_sort_by_forward_order(fqns: List[str], model) -> List[str]: 

1592 """Sort by named_modules registration order; unmatched FQNs are 

1593 appended at the end with a warning.""" 

1594 fqn_set = set(fqns) 

1595 ordered: List[str] = [] 

1596 seen: set = set() 

1597 for name, _ in model.named_modules(): 

1598 if name in fqn_set and name not in seen: 

1599 ordered.append(name) 

1600 seen.add(name) 

1601 missing = fqn_set - seen 

1602 if missing: 

1603 logger.warning( 

1604 "_topological_sort_by_forward_order: %d FQNs not found in " 

1605 "named_modules; appended at the end: %s", 

1606 len(missing), sorted(missing)[:5], 

1607 ) 

1608 ordered.extend(sorted(missing)) 

1609 return ordered 

1610 

1611 # ── tied weights ──────────────────────────────────────────────────── 

1612 

1613 @staticmethod 

1614 def _detect_tied_pairs(model) -> List[Tuple[str, str]]: 

1615 """Detect the embed_tokens.weight <-> lm_head.weight tied pair. 

1616 

1617 With HF tie_word_embeddings both ends share storage; in PP 

1618 scenarios the two ends cannot be detected across stages, so the 

1619 user must declare plan.tied_pairs explicitly (05 

1620 detect_tied_weights comment). 

1621 """ 

1622 if not getattr(getattr(model, "config", None), "tie_word_embeddings", False): 

1623 return [] 

1624 embed_fqn = lm_head_fqn = None 

1625 # remove_duplicate=False: under the default deduplication of 

1626 # named_parameters a tied parameter appears only once. 

1627 for name, _ in model.named_parameters(remove_duplicate=False): 

1628 if name.endswith("embed_tokens.weight"): 

1629 embed_fqn = name 

1630 elif name.endswith("lm_head.weight"): 

1631 lm_head_fqn = name 

1632 if embed_fqn and lm_head_fqn: 

1633 return [(embed_fqn, lm_head_fqn)] 

1634 return [] 

1635 

1636 

1637def _validate_tp_model_compatibility(config: Any, tp_size: int, ep_size: int) -> None: 

1638 """Check model head and expert width divisibility on the TP axis.""" 

1639 heads = getattr(config, "num_attention_heads", None) 

1640 if heads is not None and heads % tp_size != 0: 

1641 raise ValueError( 

1642 f"num_attention_heads ({heads}) must be divisible by TP ({tp_size})" 

1643 ) 

1644 kv_heads = getattr(config, "num_key_value_heads", None) 

1645 if kv_heads is not None and kv_heads % tp_size != 0: 

1646 raise ValueError( 

1647 f"num_key_value_heads ({kv_heads}) must be divisible by TP ({tp_size})" 

1648 ) 

1649 moe_inter = getattr(config, "moe_intermediate_size", None) 

1650 if ep_size > 1 and moe_inter is not None and moe_inter % tp_size != 0: 

1651 raise ValueError( 

1652 f"moe_intermediate_size ({moe_inter}) must be divisible by TP ({tp_size})" 

1653 ) 

1654 

1655 

1656def _validate_ep_model_compatibility(config: Any, ep_size: int) -> None: 

1657 """Check that the model has a divisible routed-expert count.""" 

1658 num_experts = (getattr(config, "num_experts", None) 

1659 or getattr(config, "n_routed_experts", None) or 0) 

1660 if num_experts <= 0: 

1661 raise ValueError("EP>1 requires MoE model (num_experts > 0)") 

1662 if num_experts % ep_size != 0: 

1663 raise ValueError( 

1664 f"num_experts ({num_experts}) must be divisible by EP ({ep_size})" 

1665 ) 

1666 

1667 

1668def validate_model_compatibility( 

1669 model: Any, *, tp_size: int = 1, cp_size: int = 1, ep_size: int = 1, 

1670 seq_len: Optional[int] = None, 

1671) -> None: 

1672 """Validate model config against requested TP, CP, and EP degrees. 

1673 

1674 Args: 

1675 model: Model whose configuration declares attention and expert sizes. 

1676 tp_size: Requested decoder tensor-parallel degree. 

1677 cp_size: Requested decoder context-parallel degree. 

1678 ep_size: Requested expert-parallel degree. 

1679 seq_len: Optional global decoder token length. 

1680 """ 

1681 config = getattr(model, "config", None) 

1682 if config is None: 

1683 return 

1684 

1685 if tp_size > 1: 

1686 _validate_tp_model_compatibility(config, tp_size, ep_size) 

1687 

1688 if cp_size > 1 and seq_len is not None and seq_len % (cp_size * 2) != 0: 

1689 raise ValueError( 

1690 f"seq_len ({seq_len}) must be divisible by 2*cp ({2 * cp_size})" 

1691 ) 

1692 

1693 if ep_size > 1: 

1694 _validate_ep_model_compatibility(config, ep_size)