Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / trainer / config / parallelism.py: 92%

582 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"""Parallel topology, activation-checkpoint and plan-override configuration. 

16 

17Split from ``auto_models/trainer/config.py`` in stage 7 (05 §15.2.5). 

18``PlanOverride`` stays the YAML DTO that desugars to 

19``auto_models.distributed.recipe_spec.ModuleShardingSpec``. 

20""" 

21# pylint: disable=unused-import 

22 

23import importlib 

24import logging 

25import re 

26from collections.abc import Mapping 

27from dataclasses import dataclass, field 

28from types import MappingProxyType 

29from typing import Any, List, Literal, Optional, Union 

30 

31from torch import nn 

32 

33from hyper_parallel.components.quantization.config import ( 

34 LowPrecisionConfig, 

35 LowPrecisionDtypeScheme, 

36) 

37from hyper_parallel.distributed.encoder_parallel.config import EncoderParallelConfig 

38from hyper_parallel.models.replacement import ( 

39 MethodReplacementSpec, 

40 ModuleReplacementFactory, 

41 ModuleReplacementSpec, 

42 ModuleReplacementRequest, 

43 method_replacement, 

44 module_replacement, 

45) 

46 

47from hyper_parallel.components.modules.family import get_module_family 

48from hyper_parallel.trainer.config.replacement import ReplacementTarget 

49from hyper_parallel.trainer.config.target import Target, _serialize_config_value 

50 

51logger = logging.getLogger(__name__) 

52 

53 

54@dataclass 

55class AcceleratorConfig: 

56 """Parallel topology and target-selected strategy configurations.""" 

57 

58 tp_size: int = 1 

59 cp_size: int = 1 

60 ep_size: int = 1 

61 pp_size: int = 1 

62 sequence_parallel: bool = False 

63 loss_parallel: bool = False 

64 encoder_parallel: EncoderParallelConfig = field(default_factory=EncoderParallelConfig) 

65 

66 

67_LAYER_RANGE_PATTERN = re.compile(r"^(\d+)-(\d+)$") 

68_SWAP_OPTION_KEYS = frozenset(("group_swap", "cpu_pool")) 

69 

70 

71def _normalize_layer_set(value: object, *, path: str) -> tuple[int, ...]: 

72 """Normalize one YAML layer set into an ordered, duplicate-free tuple.""" 

73 if not isinstance(value, (list, tuple)) or not value: 

74 raise ValueError(f"{path} must be a non-empty list of layer numbers or ranges") 

75 

76 layers = [] 

77 seen = set() 

78 for item in value: 

79 if isinstance(item, bool): 

80 raise ValueError(f"{path} must not contain boolean layer values") 

81 if isinstance(item, int): 

82 if item < 0: 

83 raise ValueError(f"{path} must not contain negative layer index {item}") 

84 expanded = (item,) 

85 elif isinstance(item, str): 

86 match = _LAYER_RANGE_PATTERN.fullmatch(item) 

87 if match is None: 

88 raise ValueError( 

89 f"{path} contains invalid layer range {item!r}; expected forms such as '0-3'" 

90 ) 

91 start, end = (int(group) for group in match.groups()) 

92 if start > end: 

93 raise ValueError(f"{path} contains reversed layer range {item!r}") 

94 expanded = tuple(range(start, end + 1)) 

95 else: 

96 raise ValueError( 

97 f"{path} must contain only non-negative integers or closed ranges, " 

98 f"got {type(item).__name__}" 

99 ) 

100 

101 for layer_index in expanded: 

102 if layer_index in seen: 

103 raise ValueError(f"{path} contains duplicate layer index {layer_index}") 

104 seen.add(layer_index) 

105 layers.append(layer_index) 

106 return tuple(sorted(layers)) 

107 

108 

109def _validate_module_path(module_path: object, *, path: str) -> str: 

110 """Validate one exact layer-relative module path.""" 

111 if not isinstance(module_path, str) or not module_path.strip(): 

112 raise ValueError(f"{path} module paths must be non-empty strings") 

113 normalized = module_path.strip() 

114 if normalized != module_path or any(not part for part in normalized.split(".")): 

115 raise ValueError(f"{path}.{module_path} is not a valid dotted module path") 

116 if any(character in normalized for character in "*?[]"): 

117 raise ValueError( 

118 f"{path}.{module_path} must be an exact module path; glob and index syntax are unsupported" 

119 ) 

120 return normalized 

121 

122 

123@dataclass(frozen=True) 

124class ModuleRegionSpec: 

125 """One normalized layer-relative activation-wrapper target.""" 

126 

127 module_path: str 

128 layers: tuple[int, ...] 

129 

130 

131@dataclass(frozen=True) 

132class ModelModuleSpec: 

133 """One normalized model-root-relative activation-wrapper target.""" 

134 

135 module_path: str 

136 

137 

138def _normalize_region_mapping(value: object, *, path: str) -> tuple[ModuleRegionSpec, ...]: 

139 """Normalize an exact module-path mapping into immutable region specs.""" 

140 if not isinstance(value, Mapping): 

141 raise ValueError(f"{path} must be a mapping from module paths to layer sets") 

142 regions = [] 

143 for raw_module_path, raw_layers in value.items(): 

144 module_path = _validate_module_path(raw_module_path, path=path) 

145 regions.append( 

146 ModuleRegionSpec( 

147 module_path=module_path, 

148 layers=_normalize_layer_set(raw_layers, path=f"{path}.{module_path}"), 

149 ) 

150 ) 

151 return tuple(regions) 

152 

153 

154def _normalize_recompute_targets( 

155 value: object, 

156 *, 

157 path: str, 

158) -> tuple[ 

159 tuple[Union[ModuleRegionSpec, ModelModuleSpec], ...], 

160 tuple[ModuleRegionSpec, ...], 

161 tuple[ModelModuleSpec, ...], 

162]: 

163 """Normalize selective recompute layer regions and model-level modules.""" 

164 if isinstance(value, Mapping): 

165 targets: list[Union[ModuleRegionSpec, ModelModuleSpec]] = list( 

166 _normalize_region_mapping(value, path=path) 

167 ) 

168 elif isinstance(value, (list, tuple)): 

169 targets = [] 

170 for index, item in enumerate(value): 

171 item_path = f"{path}[{index}]" 

172 if isinstance(item, str): 

173 targets.append( 

174 ModelModuleSpec(_validate_module_path(item, path=item_path)) 

175 ) 

176 continue 

177 if not isinstance(item, Mapping): 

178 raise ValueError( 

179 f"{item_path} must be a model module path string or a single-entry " 

180 "mapping from a layer-relative module path to a layer set" 

181 ) 

182 if len(item) != 1: 

183 raise ValueError(f"{item_path} must contain exactly one layer-relative module target") 

184 targets.extend(_normalize_region_mapping(item, path=item_path)) 

185 else: 

186 raise ValueError(f"{path} must be a mapping or list of recompute targets") 

187 

188 regions = tuple(target for target in targets if isinstance(target, ModuleRegionSpec)) 

189 modules = tuple(target for target in targets if isinstance(target, ModelModuleSpec)) 

190 

191 region_paths = set() 

192 for region in regions: 

193 if region.module_path in region_paths: 

194 raise ValueError(f"{path} contains duplicate layer-relative module path {region.module_path!r}") 

195 region_paths.add(region.module_path) 

196 

197 module_paths = set() 

198 for module in modules: 

199 if module.module_path in module_paths: 

200 raise ValueError(f"{path} contains duplicate model module path {module.module_path!r}") 

201 module_paths.add(module.module_path) 

202 for index, module in enumerate(modules): 

203 for other in modules[index + 1:]: 

204 if module.module_path.startswith(f"{other.module_path}.") or other.module_path.startswith( 

205 f"{module.module_path}." 

206 ): 

207 raise ValueError( 

208 f"{path} has nested model targets {module.module_path!r} and " 

209 f"{other.module_path!r}" 

210 ) 

211 return tuple(targets), regions, modules 

212 

213 

214def _normalize_group_swap(value: object, *, path: str) -> bool: 

215 """Normalize one optional group-swap flag.""" 

216 if not isinstance(value, bool): 

217 raise ValueError(f"{path} must be a bool") 

218 return value 

219 

220 

221def _normalize_cpu_pool(value: object, *, path: str) -> Optional[int]: 

222 """Normalize one optional pinned-memory-pool capacity in MiB.""" 

223 if value is None: 

224 return None 

225 if isinstance(value, bool) or not isinstance(value, int) or value <= 0: 

226 raise ValueError(f"{path} must be a positive integer MiB value or null") 

227 return value 

228 

229 

230def _split_swap_mapping( 

231 value: object, 

232 *, 

233 path: str, 

234) -> tuple[tuple[ModuleRegionSpec, ...], bool, Optional[int]]: 

235 """Split swap common options from exact module-path targets.""" 

236 if not isinstance(value, Mapping): 

237 raise ValueError(f"{path} must be a mapping") 

238 group_swap = _normalize_group_swap(value.get("group_swap", True), path=f"{path}.group_swap") 

239 cpu_pool_mb = _normalize_cpu_pool(value.get("cpu_pool"), path=f"{path}.cpu_pool") 

240 regions = _normalize_region_mapping( 

241 {key: item for key, item in value.items() if key not in _SWAP_OPTION_KEYS}, 

242 path=path, 

243 ) 

244 return regions, group_swap, cpu_pool_mb 

245 

246 

247def _region_layer_pairs(regions: tuple[ModuleRegionSpec, ...]) -> set[tuple[int, str]]: 

248 """Expand region specs into layer/path conflict keys.""" 

249 return { 

250 (layer_index, region.module_path) 

251 for region in regions 

252 for layer_index in region.layers 

253 } 

254 

255 

256def _validate_nested_regions( 

257 regions: tuple[ModuleRegionSpec, ...], 

258 *, 

259 path: str, 

260) -> None: 

261 """Reject ancestor/descendant activation targets within one layer.""" 

262 by_layer: dict[int, list[str]] = {} 

263 for region in regions: 

264 for layer_index in region.layers: 

265 by_layer.setdefault(layer_index, []).append(region.module_path) 

266 for layer_index, module_paths in by_layer.items(): 

267 for index, module_path in enumerate(module_paths): 

268 for other_path in module_paths[index + 1:]: 

269 if module_path.startswith(f"{other_path}.") or other_path.startswith(f"{module_path}."): 

270 raise ValueError( 

271 f"{path} has nested targets on layer {layer_index}: " 

272 f"{module_path!r} and {other_path!r}" 

273 ) 

274 

275 

276@dataclass 

277class FullExcludeRegionConfig: 

278 """Normalized exclusion regions inside full-layer checkpointing.""" 

279 

280 save: Mapping[str, Any] = field(default_factory=dict) 

281 swap: Mapping[str, Any] = field(default_factory=dict) 

282 save_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

283 swap_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

284 group_swap: bool = field(init=False) 

285 cpu_pool_mb: Optional[int] = field(init=False) 

286 

287 def __post_init__(self) -> None: 

288 """Normalize save and swap mappings.""" 

289 self.save_regions = _normalize_region_mapping( 

290 self.save, 

291 path="activation_checkpoint.full.exclude_region.save", 

292 ) 

293 self.swap_regions, self.group_swap, self.cpu_pool_mb = _split_swap_mapping( 

294 self.swap, 

295 path="activation_checkpoint.full.exclude_region.swap", 

296 ) 

297 

298 def to_dict(self) -> dict[str, Any]: 

299 """Serialize the normalized exclusion configuration.""" 

300 swap = { 

301 "group_swap": self.group_swap, 

302 "cpu_pool": self.cpu_pool_mb, 

303 **{region.module_path: list(region.layers) for region in self.swap_regions}, 

304 } 

305 return { 

306 "save": {region.module_path: list(region.layers) for region in self.save_regions}, 

307 "swap": swap, 

308 } 

309 

310 

311@dataclass 

312class FullCheckpointConfig: 

313 """Full-layer recomputation and optional exclusion regions.""" 

314 

315 recompute_layer: List[Union[int, str]] 

316 exclude_region: Optional[FullExcludeRegionConfig] = None 

317 recompute_layers: tuple[int, ...] = field(init=False) 

318 save_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

319 swap_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

320 group_swap: bool = field(init=False) 

321 cpu_pool_mb: Optional[int] = field(init=False) 

322 

323 def __post_init__(self) -> None: 

324 """Normalize full-layer coverage and exclusion settings.""" 

325 self.recompute_layers = _normalize_layer_set( 

326 self.recompute_layer, 

327 path="activation_checkpoint.full.recompute_layer", 

328 ) 

329 exclude_region = self.exclude_region or FullExcludeRegionConfig() 

330 self.save_regions = exclude_region.save_regions 

331 self.swap_regions = exclude_region.swap_regions 

332 self.group_swap = exclude_region.group_swap 

333 self.cpu_pool_mb = exclude_region.cpu_pool_mb 

334 

335 def validate_active(self) -> None: 

336 """Validate conflicts that matter when full mode is active.""" 

337 recompute_layers = set(self.recompute_layers) 

338 for config_path, regions in ( 

339 ("activation_checkpoint.full.exclude_region.save", self.save_regions), 

340 ("activation_checkpoint.full.exclude_region.swap", self.swap_regions), 

341 ): 

342 for region in regions: 

343 outside = sorted(set(region.layers) - recompute_layers) 

344 if outside: 

345 raise ValueError( 

346 f"{config_path}.{region.module_path} selects layer(s) {outside} outside " 

347 "activation_checkpoint.full.recompute_layer" 

348 ) 

349 conflicts = _region_layer_pairs(self.save_regions) & _region_layer_pairs(self.swap_regions) 

350 if conflicts: 

351 layer_index, module_path = sorted(conflicts)[0] 

352 raise ValueError( 

353 "activation_checkpoint.full.exclude_region.save and " 

354 "activation_checkpoint.full.exclude_region.swap conflict on " 

355 f"layer {layer_index}, module {module_path!r}" 

356 ) 

357 _validate_nested_regions( 

358 self.save_regions + self.swap_regions, 

359 path="activation_checkpoint.full.exclude_region", 

360 ) 

361 

362 def to_dict(self) -> dict[str, Any]: 

363 """Serialize the normalized full configuration.""" 

364 result = {"recompute_layer": list(self.recompute_layers)} 

365 if self.exclude_region is not None: 

366 result["exclude_region"] = self.exclude_region.to_dict() 

367 return result 

368 

369 

370@dataclass 

371class SelectiveCheckpointConfig: 

372 """Exact submodule recomputation and swap targets.""" 

373 

374 recompute: Union[ 

375 Mapping[str, Any], 

376 List[Union[str, Mapping[str, Any]]], 

377 ] = field(default_factory=dict) 

378 swap: Mapping[str, Any] = field(default_factory=dict) 

379 recompute_targets: tuple[Union[ModuleRegionSpec, ModelModuleSpec], ...] = field(init=False) 

380 recompute_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

381 recompute_modules: tuple[ModelModuleSpec, ...] = field(init=False) 

382 swap_regions: tuple[ModuleRegionSpec, ...] = field(init=False) 

383 group_swap: bool = field(init=False) 

384 cpu_pool_mb: Optional[int] = field(init=False) 

385 

386 def __post_init__(self) -> None: 

387 """Normalize exact selective targets and swap options.""" 

388 self.recompute_targets, self.recompute_regions, self.recompute_modules = _normalize_recompute_targets( 

389 self.recompute, 

390 path="activation_checkpoint.selective.recompute", 

391 ) 

392 self.swap_regions, self.group_swap, self.cpu_pool_mb = _split_swap_mapping( 

393 self.swap, 

394 path="activation_checkpoint.selective.swap", 

395 ) 

396 

397 def validate_active(self) -> None: 

398 """Validate active selective coverage and target conflicts.""" 

399 if not self.recompute_regions and not self.recompute_modules and not self.swap_regions: 

400 raise ValueError( 

401 "activation_checkpoint.selective requires at least one recompute or swap module target" 

402 ) 

403 conflicts = _region_layer_pairs(self.recompute_regions) & _region_layer_pairs(self.swap_regions) 

404 if conflicts: 

405 layer_index, module_path = sorted(conflicts)[0] 

406 raise ValueError( 

407 "activation_checkpoint.selective.recompute and activation_checkpoint.selective.swap " 

408 f"conflict on layer {layer_index}, module {module_path!r}" 

409 ) 

410 _validate_nested_regions( 

411 self.recompute_regions + self.swap_regions, 

412 path="activation_checkpoint.selective", 

413 ) 

414 

415 def to_dict(self) -> dict[str, Any]: 

416 """Serialize the normalized selective configuration.""" 

417 if self.recompute_modules: 

418 recompute: Union[dict[str, Any], list[Union[str, dict[str, Any]]]] = [ 

419 ( 

420 {target.module_path: list(target.layers)} 

421 if isinstance(target, ModuleRegionSpec) 

422 else target.module_path 

423 ) 

424 for target in self.recompute_targets 

425 ] 

426 else: 

427 recompute = { 

428 region.module_path: list(region.layers) 

429 for region in self.recompute_regions 

430 } 

431 return { 

432 "recompute": recompute, 

433 "swap": { 

434 "group_swap": self.group_swap, 

435 "cpu_pool": self.cpu_pool_mb, 

436 **{region.module_path: list(region.layers) for region in self.swap_regions}, 

437 }, 

438 } 

439 

440 

441@dataclass 

442class ActivationCheckpointConfig: 

443 """Top-level activation-memory strategy using the replacement YAML schema.""" 

444 

445 mode: Literal["off", "full", "selective", "hybrid"] 

446 full: Optional[FullCheckpointConfig] = None 

447 selective: Optional[SelectiveCheckpointConfig] = None 

448 

449 def __post_init__(self) -> None: 

450 """Validate mode-specific requirements and configuration conflicts.""" 

451 if self.mode not in ("off", "full", "selective", "hybrid"): 

452 raise ValueError( 

453 "activation_checkpoint.mode must be off, full, selective, or hybrid; " 

454 f"got {self.mode!r}" 

455 ) 

456 if self.mode in ("full", "hybrid") and self.full is not None: 

457 self.full.validate_active() 

458 if self.mode == "hybrid" and self.full is None: 

459 raise ValueError("activation_checkpoint.mode=hybrid requires activation_checkpoint.full") 

460 if self.mode in ("selective", "hybrid"): 

461 if self.selective is None: 

462 raise ValueError( 

463 f"activation_checkpoint.mode={self.mode} requires activation_checkpoint.selective" 

464 ) 

465 self.selective.validate_active() 

466 if self.mode == "hybrid": 

467 full_layers = set(self.full.recompute_layers) 

468 selective_layers = { 

469 layer_index 

470 for region in self.selective.recompute_regions + self.selective.swap_regions 

471 for layer_index in region.layers 

472 } 

473 overlap = sorted(full_layers & selective_layers) 

474 if overlap: 

475 raise ValueError( 

476 "activation_checkpoint.mode=hybrid requires disjoint full and selective layers; " 

477 f"overlap={overlap}" 

478 ) 

479 

480 def to_dict(self) -> dict[str, Any]: 

481 """Serialize the normalized activation-checkpoint configuration.""" 

482 result: dict[str, Any] = {"mode": self.mode} 

483 if self.full is not None: 

484 result["full"] = self.full.to_dict() 

485 if self.selective is not None: 

486 result["selective"] = self.selective.to_dict() 

487 return result 

488 

489 

490def _resolve_replace_implementation(value: Union[str, Target[Any]]) -> Target[Any]: 

491 """Resolve a replacement implementation without invoking its callable.""" 

492 if isinstance(value, Target): 

493 return value 

494 if not isinstance(value, str) or not value.strip(): 

495 raise TypeError("replace.implementation must be a non-empty import path or Target") 

496 parts = value.split(".") 

497 for split_at in range(len(parts), 0, -1): 

498 module_name = ".".join(parts[:split_at]) 

499 try: 

500 symbol = importlib.import_module(module_name) 

501 except ModuleNotFoundError as exc: 

502 if exc.name == module_name or module_name.startswith(f"{exc.name}."): 

503 continue 

504 raise ValueError(f"replace.implementation {value!r} failed while importing {exc.name!r}") from exc 

505 except ImportError as exc: 

506 raise ValueError(f"replace.implementation {value!r} failed while importing: {exc}") from exc 

507 for attribute in parts[split_at:]: 

508 if not hasattr(symbol, attribute): 

509 raise ValueError(f"replace.implementation {value!r} has no attribute {attribute!r}") 

510 symbol = getattr(symbol, attribute) 

511 if not callable(symbol): 

512 raise TypeError(f"replace.implementation {value!r} must name a callable") 

513 return Target(symbol, target_path=value) 

514 raise ValueError(f"replace.implementation {value!r} could not be imported") 

515 

516 

517@dataclass(frozen=True) 

518class ReplaceAction: 

519 """One public module or method replacement declaration.""" 

520 

521 kind: Literal["module", "method"] 

522 implementation: Union[str, Target[Any]] 

523 source_type: Optional[str] = None 

524 exact_type: bool = False 

525 

526 def __post_init__(self) -> None: 

527 """Validate kind-specific fields and normalize the delayed target.""" 

528 if self.kind not in ("module", "method"): 

529 raise ValueError("replace.kind must be 'module' or 'method'") 

530 if not isinstance(self.exact_type, bool): 

531 raise TypeError("replace.exact_type must be a bool") 

532 if self.kind == "module": 

533 if self.source_type is not None and ( 

534 not isinstance(self.source_type, str) or not self.source_type.strip()): 

535 raise ValueError("replace.source_type must be a non-empty import path when provided") 

536 if self.exact_type and self.source_type is None: 

537 raise ValueError("replace.exact_type requires replace.source_type") 

538 elif self.source_type is not None or self.exact_type: 

539 raise ValueError("replace.source_type and replace.exact_type are only valid for kind='module'") 

540 object.__setattr__( 

541 self, "implementation", _resolve_replace_implementation(self.implementation) 

542 ) 

543 

544 

545@dataclass 

546class PlanOverride: 

547 """One plan_overrides entry (YAML ``plan_overrides`` list item). 

548 

549 This is the **YAML transport form** of ``ShardingPlanner(plan_overrides= 

550 {...})`` — the planner's single override interface. Placement objects are 

551 not YAML-serializable, so contract fields use the string DSL 

552 (``"replicate"`` / ``"partial"`` / ``"shard(N)"``) plus the sentinels 

553 ``"auto"`` (explicit inherit) / ``"none"`` (explicit clear); they are 

554 desugared to real objects in ``to_override()`` — the planner never sees 

555 strings. The desugar happens trainer-side in 

556 ``instantiate_infrastructure`` BEFORE planner construction. 

557 

558 Fields: 

559 replace: public replacement action. ``kind='module'`` requires a 

560 decorated module factory at ``implementation``; optional 

561 ``source_type`` checks the expected source module type; 

562 ``kind='method'`` selects a literal method suffix in ``match``; 

563 ``.forward`` uses the existing boundary executor and defaults to 

564 ``region_dispatch=False``, while other methods use a decorated 

565 ``@method_replacement`` factory before sharding. 

566 match: module FQN/glob, or module glob plus a literal method suffix for 

567 ``kind='method'``. Boundary globs first merge matching planner boundaries; 

568 a glob with a concrete params/I/O contract also expands against 

569 the final model's ``named_modules`` and creates missing boundaries. 

570 A merge-only glob fails if it matches a real module that has no 

571 planner boundary, with a suggested contract skeleton. 

572 ``*`` spans dots, so ``"*.self_attn"`` hits 

573 ``model.layers.0.self_attn``. 

574 when: optional activation condition. Sharding actions accept ``"cp"`` 

575 (active when cp_size>1), ``"ep"`` (ep_size>1), 

576 ``"sequence_parallel"``, or ``"low_precision"`` (active when 

577 online low precision is enabled). Module replacement accepts only 

578 ``"low_precision"`` and cannot depend on the parallel topology. 

579 low_precision_dtype_scheme: a named ``training.low_precision. 

580 dtype_schemes`` entry bound to this match. Only valid on 

581 ``when="low_precision"`` replacement entries; the resolved scheme 

582 is injected into the replacement factory context so the strategy 

583 factory never resolves a catalog at replacement time. 

584 Forward replacements use ``@forward_replacement`` or ``@local_compute`` 

585 factories through ``replace.implementation``. 

586 region_dispatch: validate execution-mode declaration; forward method 

587 replacement defaults to ``false``. ``false`` = the region 

588 computation (the module's own forward or the injected function) 

589 cannot be dispatched: it contains communication primitives / 

590 custom kernels (e.g. an in-house EP-aware MoE all-to-all inside 

591 forward, or the in-repo CP/EP reference implementations), so it 

592 runs as a local-region skeleton black box; ``true`` = the 

593 injected code is pure standard operators (fused kernels / 

594 scripted-style optimizations), so under validate the dispatch 

595 passes through and out_src is genuinely checked. This field is 

596 not needed without an injection (ordinary boundaries pass through 

597 naturally). 

598 params / in_src / in_dst / out_src / out_dst: contract fields in the 

599 YAML form ``{name: {axis: placement_str}}`` (out_* also accept 

600 the scalar shorthand ``{axis: placement_str}``), or the sentinels 

601 ``"auto"`` / ``"none"``. Merge mode (match hits a derived 

602 boundary): an omitted field inherits and an explicit ``{}`` 

603 clears. Insert mode (misses every boundary): nothing can inherit; 

604 at least one concrete parameter/I/O field must declare the new 

605 boundary, and all fields required by that module's contract must 

606 be written explicitly. 

607 tp_divide_attrs: optional module-instance integer attributes divided 

608 exactly by the active TP size when the module forward runs on 

609 local tensors. Omit for no user adjustment; an explicit empty 

610 list clears an inherited glob declaration. 

611 """ 

612 

613 match: Union[str, List[str]] 

614 replace: Optional[ReplaceAction] = None 

615 when: Optional[Literal[ 

616 "cp", "ep", "sequence_parallel", "low_precision" 

617 ]] = None 

618 low_precision_dtype_scheme: Optional[str] = None 

619 region_dispatch: Optional[bool] = None 

620 params: Optional[Any] = None 

621 in_src: Optional[Any] = None 

622 in_dst: Optional[Any] = None 

623 out_src: Optional[Any] = None 

624 out_dst: Optional[Any] = None 

625 tp_divide_attrs: Optional[List[str]] = None 

626 

627 # Contract fields (string sentinels are resolved at planner merge time; 

628 # insert mode rejects them) 

629 _CONTRACT_FIELDS = ("params", "in_src", "in_dst", "out_src", "out_dst") 

630 _BOUNDARY_FIELDS = _CONTRACT_FIELDS + ("tp_divide_attrs",) 

631 

632 def __post_init__(self) -> None: 

633 """Validate the public replacement action and its boundary contract.""" 

634 if self.replace is None: 

635 return 

636 if not isinstance(self.replace, ReplaceAction): 

637 raise TypeError("plan_overrides.replace must be a ReplaceAction") 

638 if self.replace.kind == "module": 

639 self._validate_module_replacement() 

640 return 

641 self._validate_method_replacement() 

642 

643 def _validate_module_replacement(self) -> None: 

644 """Validate fields exclusive to a module replacement rule.""" 

645 if self.when not in (None, "low_precision"): 

646 raise ValueError("kind='module' only supports when='low_precision'") 

647 if self.region_dispatch is not None: 

648 raise ValueError("region_dispatch cannot appear with kind='module'") 

649 if any(getattr(self, name) is not None for name in self._BOUNDARY_FIELDS): 

650 raise ValueError("kind='module' must use its own plan_overrides rule") 

651 

652 def _validate_method_replacement(self) -> None: 

653 """Validate a literal method match and dispatch to its protocol checks.""" 

654 if isinstance(self.match, list): 

655 raise ValueError(f"kind={self.replace.kind!r} requires one string match per rule") 

656 if self.low_precision_dtype_scheme is not None: 

657 raise ValueError("low_precision_dtype_scheme is only valid for kind='module'") 

658 if not isinstance(self.match, str): 

659 raise TypeError("kind='method' match must be a string") 

660 owner_pattern, separator, method_name = self.match.rpartition(".") 

661 if (not separator or not owner_pattern or not method_name.isidentifier() 

662 or (method_name.startswith("__") and method_name.endswith("__"))): 

663 raise ValueError("kind='method' match must end in a literal method name") 

664 if method_name != "forward": 

665 self._validate_non_forward_method() 

666 return 

667 self._validate_forward_method() 

668 

669 def _validate_non_forward_method(self) -> None: 

670 """Validate a decorated method factory without a planner contract.""" 

671 if self.region_dispatch is not None or any( 

672 getattr(self, name) is not None for name in self._BOUNDARY_FIELDS): 

673 raise ValueError("kind='method' on a non-forward method cannot declare a boundary contract") 

674 if not getattr(self.replace.implementation.callable, "_hp_method_replacement", False): 

675 raise TypeError("kind='method' implementation must use @method_replacement") 

676 

677 def _validate_forward_method(self) -> None: 

678 """Validate a forward factory and its boundary dispatch declaration.""" 

679 self.region_dispatch = False if self.region_dispatch is None else self.region_dispatch 

680 if not isinstance(self.region_dispatch, bool): 

681 raise TypeError("region_dispatch must be a bool") 

682 implementation = self.replace.implementation 

683 meta = getattr(implementation.callable, "_injection_meta", None) 

684 if meta is None: 

685 raise TypeError( 

686 "kind='method' on forward implementation must use @forward_replacement or @local_compute" 

687 ) 

688 if meta.kind not in ("local_compute", "inner_wrapper"): 

689 raise TypeError(f"unsupported forward target metadata kind {meta.kind!r}") 

690 

691 def _serialized_replacement(self): 

692 """Serialize only the replacement action, independently of layout fields.""" 

693 implementation_config = _serialize_config_value(self.replace.implementation) 

694 implementation_value = ( 

695 implementation_config["_target_"] 

696 if isinstance(implementation_config, dict) and set(implementation_config) == {"_target_"} 

697 else implementation_config 

698 ) 

699 action = {"kind": self.replace.kind, "implementation": implementation_value} 

700 if self.replace.kind == "module": 

701 if self.replace.source_type is not None: 

702 action["source_type"] = self.replace.source_type 

703 if self.replace.exact_type: 

704 action["exact_type"] = True 

705 return action 

706 

707 def to_dict(self) -> dict[str, Any]: 

708 """Serialize the public declaration.""" 

709 result: dict[str, Any] = {"match": self.match} 

710 if self.when is not None: 

711 result["when"] = self.when 

712 if self.low_precision_dtype_scheme is not None: 

713 result["low_precision_dtype_scheme"] = self.low_precision_dtype_scheme 

714 if self.replace is not None: 

715 result["replace"] = self._serialized_replacement() 

716 for name in ("region_dispatch", "params", "in_src", "in_dst", "out_src", "out_dst", "tp_divide_attrs"): 

717 value = getattr(self, name) 

718 default_forward_dispatch = ( 

719 name == "region_dispatch" and value is False 

720 and self.replace is not None and self.replace.kind == "method" 

721 and self.match.rpartition(".")[2] == "forward" 

722 ) 

723 if value is not None and not default_forward_dispatch: 

724 result[name] = _serialize_config_value(value) 

725 return result 

726 

727 def _validate_override_match(self): 

728 """Reject method-only and empty declarations before creating a boundary.""" 

729 if self.replace is not None and self.replace.kind == "method" and ( 

730 self.match.rpartition(".")[2] != "forward"): 

731 raise ValueError("non-forward method replacements do not create planner boundaries") 

732 

733 if not self.match: 

734 raise ValueError( 

735 "plan_overrides entry is missing 'match' (an fqn or " 

736 "fqn glob such as '*.self_attn' or '*.mlp')") 

737 

738 def to_override(self) -> "tuple[str, Any]": 

739 """Desugar to a ``(match, ModuleShardingSpec)`` plan_overrides entry. 

740 

741 Placement DSL strings become real Placement objects here; the 

742 ``"auto"``/``"none"`` sentinels pass through AS STRINGS into the spec 

743 (the planner's merge resolves them; insert rejects them). Imports are 

744 lazy: trainer.config must not become an import-time dependency of 

745 components.distributed (the zero-dependency boundary is guarded by 

746 test_s5_zero_dep_lint). 

747 """ 

748 # Keep trainer.config outside the distributed component's import-time dependency graph. 

749 # pylint: disable-next=import-outside-toplevel 

750 from hyper_parallel.distributed.recipe_spec import ( 

751 ModuleShardingSpec, 

752 ) 

753 

754 self._validate_override_match() 

755 implementation = self.replace.implementation if self.replace is not None else None 

756 meta = getattr(implementation.callable, "_injection_meta", None) if implementation is not None else None 

757 spec = ModuleShardingSpec( 

758 local_compute_fn=implementation if meta is not None and meta.kind == "local_compute" else None, 

759 inner_target="self" if meta is not None and meta.kind == "inner_wrapper" else None, 

760 inner_wrapper=implementation if meta is not None and meta.kind == "inner_wrapper" else None, 

761 region_dispatch=self.region_dispatch, 

762 tp_divide_attrs=self._validate_tp_divide_attrs(), 

763 ) 

764 for attr in self._CONTRACT_FIELDS: 

765 raw = getattr(self, attr) 

766 if raw is None: 

767 continue 

768 setattr(spec, attr, self._parse_contract_field(attr, raw)) 

769 match = ( 

770 self.match.rpartition(".")[0] 

771 if self.replace is not None and self.replace.kind == "method" 

772 else self.match 

773 ) 

774 return match, spec 

775 

776 def _validate_tp_divide_attrs(self) -> Optional[List[str]]: 

777 """Validate the YAML transport shape for TP-local attributes.""" 

778 attrs = self.tp_divide_attrs 

779 if attrs is None: 

780 return None 

781 if not isinstance(attrs, list): 

782 raise ValueError( 

783 f"plan_overrides match={self.match!r}: tp_divide_attrs " 

784 f"must be a list of attribute names, got {type(attrs).__name__}") 

785 seen = set() 

786 for attr in attrs: 

787 if not isinstance(attr, str) or not attr or not attr.isidentifier(): 

788 raise ValueError( 

789 f"plan_overrides match={self.match!r}: " 

790 f"tp_divide_attrs may only contain valid attribute names, got {attr!r}") 

791 if attr in seen: 

792 raise ValueError( 

793 f"plan_overrides match={self.match!r}: " 

794 f"tp_divide_attrs contains duplicate attribute {attr!r}") 

795 seen.add(attr) 

796 return list(attrs) 

797 

798 def _parse_contract_field(self, attr, raw): 

799 """YAML form → spec field value (DSL parse / sentinel pass-through).""" 

800 # Keep trainer.config outside the distributed component's import-time dependency graph. 

801 # pylint: disable-next=import-outside-toplevel 

802 from hyper_parallel.distributed.recipe_spec import ( 

803 parse_named_placement, 

804 ) 

805 

806 if isinstance(raw, str): 

807 if raw in ("auto", "none"): 

808 return raw 

809 raise ValueError( 

810 f"plan_overrides match={self.match!r}: string value of contract " 

811 f"field {attr} only accepts the sentinels 'auto' (explicit " 

812 f"inherit) / 'none' (explicit clear), got {raw!r}") 

813 if not isinstance(raw, dict): 

814 raise ValueError( 

815 f"plan_overrides match={self.match!r}: contract field {attr} " 

816 f"expects a mapping or a sentinel string, got {raw!r}") 

817 if not raw: 

818 return {} # explicit empty ("as written": clear / no sharding), unlike omitting the field 

819 if attr in ("out_src", "out_dst") and all( 

820 isinstance(v, str) for v in raw.values()): 

821 # Scalar shorthand {axis: placement} — already a NamedPlacement 

822 # (the output name is filled in uniformly by the planner's 

823 # _normalize_out_fields) 

824 return parse_named_placement( 

825 raw, path=f"plan_overrides[{self.match!r}].{attr}") 

826 return { 

827 name: parse_named_placement( 

828 named, path=f"plan_overrides[{self.match!r}].{attr}.{name}") 

829 for name, named in raw.items() 

830 } 

831 

832 

833_WHEN_CONDITIONS = ("cp", "ep", "sequence_parallel", "low_precision") 

834 

835 

836def _import_module_type(path: str) -> type[nn.Module]: 

837 """Import the source module type named by a replacement YAML entry.""" 

838 

839 if not isinstance(path, str) or not path.strip(): 

840 raise ValueError("plan_overrides.replace.source_type must be a non-empty symbol path") 

841 parts = path.split(".") 

842 for split_at in range(len(parts), 0, -1): 

843 module_name = ".".join(parts[:split_at]) 

844 try: 

845 symbol = importlib.import_module(module_name) 

846 except ModuleNotFoundError as exc: 

847 if exc.name == module_name or module_name.startswith(f"{exc.name}."): 

848 continue 

849 raise ValueError( 

850 f"plan_overrides.replace.source_type {path!r} failed while importing {exc.name!r}" 

851 ) from exc 

852 except ImportError as exc: 

853 raise ValueError( 

854 f"plan_overrides.replace.source_type {path!r} failed while importing: {exc}" 

855 ) from exc 

856 for attribute in parts[split_at:]: 

857 if not hasattr(symbol, attribute): 

858 raise ValueError( 

859 f"plan_overrides.replace.source_type {path!r} has no attribute {attribute!r}" 

860 ) 

861 symbol = getattr(symbol, attribute) 

862 if not isinstance(symbol, type) or not issubclass(symbol, nn.Module): 

863 raise TypeError(f"plan_overrides.replace.source_type {path!r} must name an nn.Module type") 

864 return symbol 

865 raise ValueError(f"plan_overrides.replace.source_type {path!r} could not be imported") 

866 

867 

868def _target_replacement_factory( 

869 target: Target[Any], 

870 low_precision_policy: Optional[LowPrecisionDtypeScheme] = None, 

871) -> ModuleReplacementFactory: 

872 """Bind a YAML Target's static args to the replacement factory protocol.""" 

873 

874 if not isinstance(target, ReplacementTarget) and get_module_family(target.callable) is not None: 

875 # Preserve configured Python objects; only Family baselines need selection. 

876 # Target has no public accessors for its raw constructor values. 

877 target = ReplacementTarget( 

878 target.callable, target_path=target._target_path, **target._kwargs, 

879 ) 

880 

881 if isinstance(target, ReplacementTarget) and target.low_precision_dtype_scheme is not None: 

882 target = target.bind_dtype_scheme(low_precision_policy) 

883 

884 if not getattr(target.callable, "_hp_module_replacement", False): 

885 raise TypeError( 

886 "plan_overrides replace.implementation for kind='module' must use @module_replacement" 

887 ) 

888 

889 @module_replacement 

890 def factory( 

891 *, 

892 module: nn.Module, 

893 module_fqn: str, 

894 context: Mapping[str, Any], 

895 ) -> nn.Module: 

896 """Build one replacement module by delegating to the bound YAML Target.""" 

897 if low_precision_policy is not None: 

898 factory_context = dict(context) 

899 factory_context["low_precision"] = low_precision_policy 

900 context = MappingProxyType(factory_context) 

901 return target.build(module=module, module_fqn=module_fqn, context=context) 

902 

903 return factory 

904 

905 

906def _target_method_factory(target: Target[Any]): 

907 """Bind YAML static arguments to the method replacement factory protocol.""" 

908 if not getattr(target.callable, "_hp_method_replacement", False): 

909 raise TypeError("plan_overrides replace.implementation for kind='method' must use @method_replacement") 

910 

911 @method_replacement 

912 def factory( 

913 *, module: nn.Module, method_fqn: str, original_method: Any, context: Mapping[str, Any], 

914 ) -> Any: 

915 """Build one replacement callable from the configured target.""" 

916 return target.build( 

917 module=module, method_fqn=method_fqn, original_method=original_method, context=context, 

918 ) 

919 

920 return factory 

921 

922 

923def entries_to_method_replacements( 

924 entries: List[PlanOverride], *, cp_size: int = 1, ep_size: int = 1, 

925 sequence_parallel: bool = False, low_precision_enabled: bool = False, 

926) -> tuple[MethodReplacementSpec, ...]: 

927 """Resolve active non-forward method actions into executable rules. 

928 

929 Args: 

930 entries: Trainer plan override declarations. 

931 cp_size: Active context parallel degree. 

932 ep_size: Active expert parallel degree. 

933 sequence_parallel: Whether sequence parallelism is active. 

934 low_precision_enabled: Whether online low precision is enabled. 

935 

936 Returns: 

937 Rules applied after module replacement and before sharding. 

938 """ 

939 rules = [] 

940 for entry in entries: 

941 if entry.replace is None or entry.replace.kind != "method": 

942 continue 

943 if entry.match.rpartition(".")[2] == "forward": 

944 continue 

945 _validate_when(entry) 

946 active = { 

947 None: True, 

948 "cp": cp_size > 1, 

949 "ep": ep_size > 1, 

950 "sequence_parallel": sequence_parallel, 

951 "low_precision": low_precision_enabled, 

952 }[entry.when] 

953 if active: 

954 rules.append(MethodReplacementSpec( 

955 match=entry.match, 

956 factory=_target_method_factory(entry.replace.implementation), 

957 )) 

958 else: 

959 logger.info("plan_overrides: match=%r skipped because condition %r is inactive", 

960 entry.match, entry.when) 

961 return tuple(rules) 

962 

963 

964def entries_to_module_replacement_requests( 

965 entries: List[PlanOverride], *, low_precision_enabled: bool = False, 

966 low_precision_config: Optional[LowPrecisionConfig] = None, 

967) -> tuple[ModuleReplacementRequest, ...]: 

968 """Preserve public family identity and explicit parameters through desugaring. 

969 

970 Args: 

971 entries: Value passed to this operation. 

972 """ 

973 effective = low_precision_config if low_precision_enabled else None 

974 result = [] 

975 for entry_index, entry in enumerate(entries): 

976 if entry.replace is None or entry.replace.kind != "module": 

977 continue 

978 if entry.when == "low_precision" and not low_precision_enabled: 

979 continue 

980 _validate_replacement_entry(entry, effective) 

981 target = entry.replace.implementation 

982 baseline = target.requested_target if isinstance(target, ReplacementTarget) else target.callable 

983 arguments = {name: value for name, value in target._kwargs.items() # pylint: disable=protected-access 

984 if name not in {"module", "module_fqn", "context"}} 

985 if isinstance(target, ReplacementTarget): 

986 arguments.update(target.selectors) 

987 if entry.when == "low_precision": 

988 # Legacy policy-bearing closures remain on the explicit compatibility path. 

989 continue 

990 result.append(ModuleReplacementRequest( 

991 match=(entry.match,) if isinstance(entry.match, str) else tuple(entry.match), 

992 target=baseline, kwargs=arguments, origin="user", 

993 declaration_id=f"plan_override:{entry_index}:replace", 

994 module_type=_import_module_type(entry.replace.source_type) if entry.replace.source_type else None, 

995 exact_type=entry.replace.exact_type, 

996 )) 

997 return tuple(result) 

998 

999 

1000def _replacement_dtype_scheme( 

1001 entry: PlanOverride, config: Optional[LowPrecisionConfig], direct_formats: frozenset[str], 

1002) -> Optional[LowPrecisionDtypeScheme]: 

1003 """Resolve a weight/activation policy for an active module replacement.""" 

1004 implementation = entry.replace.implementation 

1005 target = (implementation.requested_target if isinstance(implementation, ReplacementTarget) 

1006 else implementation.callable) 

1007 consumes_direct_format = not direct_formats.isdisjoint(getattr(target, "low_precision_formats", ())) 

1008 scheme_name = getattr(implementation, "low_precision_dtype_scheme", None) 

1009 if consumes_direct_format and (entry.low_precision_dtype_scheme is not None or scheme_name is not None): 

1010 raise ValueError( 

1011 f"plan_overrides match={entry.match!r} cannot select a W/A dtype scheme " 

1012 "and CSA2 formats on the same replacement" 

1013 ) 

1014 if scheme_name is not None: 

1015 if entry.low_precision_dtype_scheme is not None: 

1016 raise ValueError( 

1017 f"plan_overrides match={entry.match!r}: specify dtype scheme only inside replace.implementation") 

1018 if config is None: 

1019 raise ValueError(f"plan_overrides match={entry.match!r}: dtype scheme requires training.low_precision") 

1020 return config.resolve_dtype_scheme(scheme_name) 

1021 if entry.when == "low_precision" and config is not None and not consumes_direct_format: 

1022 return config.resolve_dtype_scheme(entry.low_precision_dtype_scheme) 

1023 return None 

1024 

1025 

1026def entries_to_module_replacements( 

1027 entries: List[PlanOverride], 

1028 *, 

1029 low_precision_enabled: bool = False, 

1030 low_precision_config: Optional[LowPrecisionConfig] = None, 

1031) -> tuple[ModuleReplacementSpec, ...]: 

1032 """Desugar replacement actions and bind their named dtype schemes. 

1033 

1034 Args: 

1035 entries: Raw planner override entries. 

1036 low_precision_enabled: Whether low-precision replacement is active. 

1037 low_precision_config: Named dtype schemes for active replacements. 

1038 """ 

1039 

1040 effective_config = low_precision_config if low_precision_enabled else None 

1041 direct_formats = effective_config.active_direct_formats() if effective_config is not None else frozenset() 

1042 rules = [] 

1043 for entry_index, entry in enumerate(entries): 

1044 if entry.replace is None or entry.replace.kind != "module": 

1045 continue 

1046 if entry.when == "low_precision" and not low_precision_enabled: 

1047 continue 

1048 _validate_replacement_entry(entry, effective_config) 

1049 patterns = (entry.match,) if isinstance(entry.match, str) else tuple(entry.match) 

1050 policy = _replacement_dtype_scheme(entry, low_precision_config, direct_formats) 

1051 serialized_target = entry.replace.implementation.to_dict() 

1052 rules.append( 

1053 ModuleReplacementSpec( 

1054 match=patterns, 

1055 factory=_target_replacement_factory(entry.replace.implementation, policy), 

1056 module_type=( 

1057 _import_module_type(entry.replace.source_type) 

1058 if entry.replace.source_type is not None else None 

1059 ), 

1060 exact_type=entry.replace.exact_type, 

1061 declaration_id=f"plan_override:{entry_index}:replace", 

1062 replacement_target=serialized_target["_target_"], 

1063 static_arguments={ 

1064 key: value 

1065 for key, value in serialized_target.items() 

1066 if key != "_target_" 

1067 }, 

1068 ) 

1069 ) 

1070 return tuple(rules) 

1071 

1072 

1073def _validate_replacement_entry(entry: PlanOverride, effective_config: Optional[LowPrecisionConfig]) -> None: 

1074 """Validate one replacement before constructing its planner rule.""" 

1075 if entry.when not in (None, "low_precision"): 

1076 raise ValueError( 

1077 f"plan_overrides match={entry.match!r} uses kind='module' and " 

1078 "does not support 'when' values other than 'low_precision' " 

1079 "(module replacements are not conditioned on parallel topology)" 

1080 ) 

1081 if entry.low_precision_dtype_scheme is not None and ( 

1082 not isinstance(entry.low_precision_dtype_scheme, str) 

1083 or not entry.low_precision_dtype_scheme.strip() 

1084 ): 

1085 raise ValueError( 

1086 f"plan_overrides match={entry.match!r}: " 

1087 "low_precision_dtype_scheme must be a non-empty string" 

1088 ) 

1089 if entry.low_precision_dtype_scheme is not None and entry.when != "low_precision": 

1090 raise ValueError( 

1091 f"plan_overrides match={entry.match!r} sets " 

1092 "low_precision_dtype_scheme but is not a low-precision entry" 

1093 ) 

1094 if entry.when == "low_precision" and effective_config is None: 

1095 raise ValueError( 

1096 f"plan_overrides match={entry.match!r} enables a low-precision " 

1097 "replacement but training.low_precision is missing" 

1098 ) 

1099 if not isinstance(entry.replace.implementation, Target): 

1100 raise TypeError( 

1101 f"plan_overrides match={entry.match!r} replace.implementation must be a YAML Target" 

1102 ) 

1103 

1104 

1105def _has_sharding_action(entry: PlanOverride) -> bool: 

1106 action_names = ( 

1107 "region_dispatch", "params", "in_src", "in_dst", "out_src", "out_dst", 

1108 ) 

1109 return any(getattr(entry, name) is not None for name in action_names) 

1110 

1111 

1112def _validate_when(entry: PlanOverride) -> None: 

1113 """Validate programmatic when values that bypass the YAML Literal check.""" 

1114 

1115 if entry.when is not None and entry.when not in _WHEN_CONDITIONS: 

1116 raise ValueError( 

1117 f"plan_overrides match={entry.match!r} has invalid when={entry.when!r}; " 

1118 f"expected one of {list(_WHEN_CONDITIONS)}" 

1119 ) 

1120 

1121 

1122def _merge_plan_override(overrides: dict[str, Any], match: str, spec: Any) -> None: 

1123 """Merge one desugared spec into an existing match, with later fields winning.""" 

1124 if match not in overrides: 

1125 overrides[match] = spec 

1126 return 

1127 previous = overrides[match] 

1128 for name in ("local_compute_fn", "inner_target", "inner_wrapper", 

1129 "inner_out_src", "params", "in_src", "in_dst", 

1130 "out_src", "out_dst", "tp_divide_attrs"): 

1131 value = getattr(spec, name) 

1132 if value is not None: 

1133 setattr(previous, name, value) 

1134 if spec.region_dispatch is not None: 

1135 previous.region_dispatch = spec.region_dispatch 

1136 

1137 

1138def _validate_override_transport(entry): 

1139 """Validate YAML module-selection transport separately from placement lowering.""" 

1140 if isinstance(entry.match, list) and ( 

1141 entry.replace is None or entry.replace.kind != "module" or _has_sharding_action(entry) 

1142 ): 

1143 raise ValueError( 

1144 "plan_overrides match lists are supported only for replace.kind='module' " 

1145 "entries; use separate string matches for sharding actions" 

1146 ) 

1147 if entry.replace is not None and entry.replace.kind == "module" and entry.when not in ( 

1148 None, 

1149 "low_precision", 

1150 ): 

1151 raise ValueError( 

1152 f"plan_overrides match={entry.match!r} uses replace.kind='module' and " 

1153 "does not support 'when' values other than 'low_precision' " 

1154 "(module replacements are not conditioned on parallel topology)" 

1155 ) 

1156 

1157 

1158def entries_to_plan_overrides( 

1159 entries: "List[PlanOverride]", *, cp_size: int = 1, ep_size: int = 1, 

1160 sequence_parallel: bool = False, 

1161 low_precision_enabled: bool = False, 

1162) -> "dict[str, Any]": 

1163 """Desugar PlanOverride entries into a ``plan_overrides`` dict. 

1164 

1165 Args: 

1166 entries: Raw YAML planner override entries. 

1167 cp_size: Context-parallel degree. 

1168 ep_size: Expert-parallel degree. 

1169 sequence_parallel: Whether decoder sequence parallelism is active. 

1170 low_precision_enabled: Whether low-precision rules are active. 

1171 

1172 - ``when`` filter: an entry whose declared condition is inactive 

1173 (``when="cp"`` with cp_size==1 etc.) is SKIPPED with an INFO log — 

1174 declared gating, never silent application. An unknown ``when`` value 

1175 fails fast listing the valid conditions (programmatic construction 

1176 bypasses the resolver's Literal check); 

1177 - two entries sharing the same ``match`` are merged field-wise 

1178 (non-None fields, later entry wins) — the planner's interface is 

1179 exactly this dict. 

1180 """ 

1181 overrides: dict[str, Any] = {} 

1182 for entry in entries: 

1183 if entry.replace is not None and entry.replace.kind == "method" and ( 

1184 entry.match.rpartition(".")[2] != "forward"): 

1185 _validate_when(entry) 

1186 continue 

1187 _validate_override_transport(entry) 

1188 _validate_when(entry) 

1189 if entry.when is not None: 

1190 active = { 

1191 "cp": cp_size > 1, 

1192 "ep": ep_size > 1, 

1193 "sequence_parallel": sequence_parallel, 

1194 "low_precision": low_precision_enabled, 

1195 }[entry.when] 

1196 if not active: 

1197 logger.info( 

1198 "plan_overrides: match=%r skipped because condition %r " 

1199 "is inactive", 

1200 entry.match, entry.when) 

1201 continue 

1202 if entry.replace is not None and entry.replace.kind == "module": 

1203 continue 

1204 match, spec = entry.to_override() 

1205 _merge_plan_override(overrides, match, spec) 

1206 return overrides 

1207 

1208 

1209def normalize_distributed_setup_overrides( 

1210 distributed_setup: Any, 

1211 config: "TrainerConfig", 

1212) -> None: 

1213 """Fill the normalized plan fields of a ``DistributedSetup`` (05 §15.2.6). 

1214 

1215 Args: 

1216 distributed_setup: Mutable setup receiving normalized planner rules. 

1217 config: Trainer configuration containing raw override entries. 

1218 

1219 This is the single Trainer-side desugar point: raw YAML ``PlanOverride`` 

1220 entries (``TrainerConfig.plan_overrides``) are converted HERE — 

1221 when-filtered against the built mesh and compiled into replacement 

1222 rules — so the AutoModels build pipeline consumes only normalized 

1223 objects and never imports trainer config. 

1224 """ 

1225 entries = list(getattr(config, "plan_overrides", None) or []) 

1226 mesh_context = getattr(distributed_setup, "mesh_context", None) 

1227 low_precision_enabled = bool( 

1228 getattr( 

1229 getattr(distributed_setup, "low_precision_config", None), 

1230 "enabled", 

1231 False, 

1232 ) 

1233 ) 

1234 distributed_setup._hp_legacy_low_precision_targets = any( # pylint: disable=protected-access 

1235 entry.replace is not None and entry.replace.kind == "module" and ( 

1236 entry.when == "low_precision" 

1237 or getattr(entry.replace.implementation, "low_precision_dtype_scheme", None) is not None 

1238 ) 

1239 for entry in entries 

1240 ) 

1241 if not distributed_setup._hp_legacy_low_precision_targets: # pylint: disable=protected-access 

1242 distributed_setup.module_replacement_requests = entries_to_module_replacement_requests( 

1243 entries, low_precision_enabled=low_precision_enabled, 

1244 low_precision_config=getattr(distributed_setup, "low_precision_config", None), 

1245 ) 

1246 else: 

1247 distributed_setup.module_replacement_requests = None 

1248 distributed_setup.module_replacements = entries_to_module_replacements( 

1249 entries, 

1250 low_precision_enabled=low_precision_enabled, 

1251 low_precision_config=getattr(distributed_setup, "low_precision_config", None), 

1252 ) 

1253 distributed_setup.method_replacements = entries_to_method_replacements( 

1254 entries, 

1255 cp_size=getattr(mesh_context, "cp_size", 1), 

1256 ep_size=getattr(mesh_context, "ep_size", 1), 

1257 sequence_parallel=getattr(mesh_context, "sequence_parallel", False), 

1258 low_precision_enabled=low_precision_enabled, 

1259 ) 

1260 distributed_setup.plan_overrides = ( 

1261 entries_to_plan_overrides( 

1262 entries, 

1263 cp_size=getattr(mesh_context, "cp_size", 1), 

1264 ep_size=getattr(mesh_context, "ep_size", 1), 

1265 sequence_parallel=getattr(mesh_context, "sequence_parallel", False), 

1266 low_precision_enabled=low_precision_enabled, 

1267 ) 

1268 if entries 

1269 else None 

1270 )