Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / module_family.py: 93%

259 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"""Shared construction of concrete family members for direct and source models.""" 

16 

17from __future__ import annotations 

18 

19import inspect 

20from collections.abc import Mapping 

21from copy import deepcopy 

22from dataclasses import dataclass, replace 

23from types import MappingProxyType 

24from typing import Any, Callable 

25 

26from torch import nn 

27 

28from hyper_parallel.components.modules.family import ( 

29 ModuleFamily, 

30 SelectorSpec, 

31 VariantRule, 

32 _FAMILIES, 

33 _validate_deferred_arguments, 

34 _select_variant, 

35 get_family_selector_specs, 

36 get_module_family, 

37 register_module_family, 

38 resolve_module_family_target, 

39) 

40 

41 

42__all__ = [ 

43 "ModuleFamily", "SelectorSpec", "VariantRule", "FamilyRequest", "ResolvedFamily", 

44 "FamilyBuildInfo", "FamilyBoundary", "register_module_family", "get_module_family", 

45 "get_family_selector_specs", "resolve_module_family_target", "resolve_family", "build_family", 

46 "get_family_build_info", "collect_family_modules", "validate_family_context", 

47 "FamilyShardingContext", 

48] 

49 

50 

51@dataclass(frozen=True) 

52class FamilyShardingContext: 

53 """Logical computation axes and global shapes; no communication resources.""" 

54 

55 mesh_dim_names: tuple[str, ...] 

56 axis_sizes: Mapping[str, int] 

57 parameter_shapes: Mapping[str, tuple[int, ...]] 

58 sequence_parallel: bool = False 

59 loss_parallel: bool = False 

60 

61 def __post_init__(self) -> None: 

62 object.__setattr__(self, "axis_sizes", MappingProxyType(dict(self.axis_sizes))) 

63 object.__setattr__(self, "parameter_shapes", MappingProxyType(dict(self.parameter_shapes))) 

64 

65 

66@dataclass(frozen=True) 

67class FamilyRequest: 

68 """A public family and its explicit construction arguments, before selection.""" 

69 

70 target: Callable 

71 kwargs: Mapping[str, Any] 

72 

73 def __post_init__(self) -> None: 

74 family = get_module_family(self.target) 

75 if family is None or family.default_variant is None: 

76 raise ValueError("FamilyRequest requires a family with a concrete default_variant") 

77 _validate_deferred_arguments(family, self.kwargs) 

78 object.__setattr__(self, "kwargs", MappingProxyType(deepcopy(dict(self.kwargs)))) 

79 

80 

81@dataclass(frozen=True) 

82class ResolvedFamily: 

83 """One validated implementation choice without parameters or communication resources.""" 

84 

85 family: ModuleFamily 

86 variant: str 

87 constructor: Callable 

88 arguments: Mapping[str, Any] 

89 selectors: Mapping[str, Any] 

90 axis_sizes: Mapping[str, int] 

91 

92 @property 

93 def sharding(self) -> Callable | None: 

94 """Return the selected family's layout provider.""" 

95 return self.family.sharding 

96 

97 

98@dataclass(frozen=True) 

99class _FamilyLayout: 

100 """Borrowed mesh and completed component layout, outside serialized requests.""" 

101 

102 mesh: Any 

103 sharding: Any 

104 parallel: Any 

105 parameter_shapes: Mapping[str, tuple[int, ...]] 

106 source_shard_info: Mapping[str, Any] 

107 applied: bool = True 

108 

109 

110@dataclass(frozen=True) 

111class FamilyBuildInfo: 

112 """Construction provenance and layout records; execution resources stay on the module.""" 

113 

114 request: FamilyRequest 

115 resolved: ResolvedFamily 

116 config_snapshot: Any 

117 origin: str 

118 layout: _FamilyLayout | None = None 

119 

120 def __deepcopy__(self, memo: dict[int, Any]) -> "FamilyBuildInfo": 

121 """Preserve immutable construction provenance across module deepcopy.""" 

122 del memo 

123 return self 

124 

125 

126@dataclass(frozen=True) 

127class FamilyBoundary: 

128 """One concrete family instance with all its paths in the final model tree.""" 

129 

130 module: nn.Module 

131 fqns: tuple[str, ...] 

132 info: FamilyBuildInfo 

133 

134 

135def _axis_sizes(context: Mapping[str, Any]) -> Mapping[str, int]: 

136 """Read and validate logical parallel degrees from the construction context.""" 

137 result = {} 

138 for axis in ("tp", "cp", "ep", "pp"): 

139 size = context.get(f"{axis}_size") 

140 if size is None: 

141 if context.get(axis): 

142 raise ValueError(f"{axis}_size is required when {axis} is active") 

143 size = 1 

144 actual_type = type(size) 

145 if actual_type is not int or size < 1: 

146 raise ValueError(f"{axis}_size must be a positive integer") 

147 result[axis] = size 

148 return MappingProxyType(result) 

149 

150 

151def _mesh_axis_size(mesh: Any, axis: str) -> int: 

152 """Validate declared sizes against the actual borrowed axis views.""" 

153 device_mesh = mesh.device_mesh 

154 region = getattr(mesh, "fsdp_moe_mesh", None) if axis == "ep" else None 

155 if region is None: 

156 region = device_mesh 

157 names = tuple(getattr(region, "mesh_dim_names", ()) or ()) 

158 actual = region[axis].size() if axis in names else 1 

159 size = getattr(mesh, f"{axis}_size", actual) 

160 actual_type = type(size) 

161 if actual_type is not int or size < 1: 

162 raise ValueError(f"{axis}_size must be a positive integer") 

163 if axis in names and size != actual: 

164 raise ValueError(f"{axis}_size={size} disagrees with the mesh size {actual}") 

165 if axis not in names and size > 1 and axis != "pp": 

166 raise ValueError(f"{axis}_size={size} requires an axis named {axis!r}; available mesh axes: {names!r}") 

167 return size 

168 

169 

170def _context_from_mesh(mesh: Any, context: Mapping[str, Any] | None) -> Mapping[str, Any]: 

171 """Read actual job axes without copying mesh resources into a request.""" 

172 result = dict(context or {}) 

173 if mesh is None: 

174 mesh = result.get("mesh") 

175 if getattr(mesh, "device_mesh", None) is None: 

176 return result 

177 device_mesh = getattr(mesh, "device_mesh", None) 

178 if device_mesh is None: 

179 raise ValueError("mesh requires a prebuilt device_mesh") 

180 previous = result.get("mesh") 

181 if previous is not None and not _same_mesh(previous, mesh): 

182 raise ValueError("context and mesh belong to different jobs") 

183 for axis in ("tp", "cp", "ep", "pp"): 

184 size = _mesh_axis_size(mesh, axis) 

185 if f"{axis}_size" in result and result[f"{axis}_size"] != size: 

186 raise ValueError(f"context and mesh disagree on {axis}_size") 

187 result[f"{axis}_size"] = size 

188 result[axis] = size > 1 

189 result["mesh"] = mesh 

190 result["sequence_parallel"] = bool(getattr(mesh, "sequence_parallel", False)) 

191 result["loss_parallel"] = bool(getattr(mesh, "loss_parallel", False)) 

192 return result 

193 

194 

195def resolve_family(request: FamilyRequest, *, context: Mapping[str, Any] | None = None) -> ResolvedFamily: 

196 """Resolve exactly one allowlisted member using the current job context. 

197 

198 Args: 

199 request: Original family and explicit arguments. 

200 context: Read-only job topology used for automatic CP/EP selection. 

201 

202 Returns: 

203 Concrete construction information without allocating model resources. 

204 """ 

205 family = get_module_family(request.target) 

206 context = context or {} 

207 axes = _axis_sizes(context) 

208 args = deepcopy(dict(request.kwargs)) 

209 parallel = family.parallel_axis is not None and axes[family.parallel_axis] > 1 

210 constructor, variant, selectors = _select_variant(family, args, parallel=parallel) 

211 if constructor is family.baseline: 

212 raise ValueError("a concrete family member cannot be its public factory") 

213 return ResolvedFamily( 

214 family, variant, constructor, MappingProxyType(args), MappingProxyType(selectors), axes, 

215 ) 

216 

217 

218def _constructor_arguments( 

219 member: ResolvedFamily, config: Any, module: nn.Module | None, fqn: str, context: Mapping[str, Any], 

220) -> dict[str, Any]: 

221 """Project validated public options onto the selected member's explicit signature.""" 

222 signature = inspect.signature(member.constructor) 

223 required = "config" if module is None else "module" 

224 if required not in signature.parameters: 

225 raise TypeError(f"member {member.variant!r} must explicitly accept {required}") 

226 # FamilyRequest checks public names; family validation sees every option before this point. 

227 # Members need not declare options used only by another implementation in the family. 

228 kwargs = {name: value for name, value in member.arguments.items() if name in signature.parameters} 

229 runtime = {"config": config, "module": module, "module_fqn": fqn, "context": context} 

230 kwargs.update({name: value for name, value in runtime.items() if name in signature.parameters}) 

231 signature.bind(**kwargs) 

232 return kwargs 

233 

234 

235def _normalize_family_request(target, kwargs): 

236 """Resolve a public name without selecting a topology-dependent member.""" 

237 if isinstance(target, str): 

238 matches = [family.baseline for family in _FAMILIES.values() if family.name == target] 

239 if len(matches) != 1: 

240 raise ValueError(f"family name {target!r} must identify exactly one registration") 

241 target = matches[0] 

242 if isinstance(target, FamilyRequest): 

243 if kwargs: 

244 raise ValueError("request arguments cannot be combined with additional keywords") 

245 return target 

246 return FamilyRequest(target, kwargs) 

247 

248 

249def _validate_initialization_contract(module: nn.Module) -> bool: 

250 """Require replacement-owned reset hooks to declare checkpoint conversion too. 

251 

252 Torch's inherited default reset is not a replacement initialization policy. 

253 An empty conversion list still declares that policy and permits a later reset. 

254 Conversion-only modules may rely on their ordinary children for initialization. 

255 """ 

256 make_transforms = getattr(module, "make_transforms", None) 

257 if make_transforms is not None and not callable(make_transforms): 

258 raise TypeError("replacement make_transforms must be callable") 

259 reset_parameters = getattr(module, "reset_parameters", None) 

260 reset_owner = next((base for base in type(module).__mro__ if "reset_parameters" in vars(base)), None) 

261 custom_reset = (callable(reset_parameters) and reset_owner is not None 

262 and not reset_owner.__module__.startswith("torch.nn.")) 

263 if custom_reset and not callable(make_transforms): 

264 raise TypeError( 

265 f"{type(module).__name__}.reset_parameters requires a callable make_transforms(); " 

266 "return [] when checkpoint conversion is unnecessary" 

267 ) 

268 return callable(make_transforms) and callable(reset_parameters) 

269 

270 

271def _build_family_member( 

272 request: FamilyRequest, 

273 member: ResolvedFamily, 

274 *, 

275 config: Any = None, 

276 module: nn.Module | None = None, 

277 module_fqn: str = "", 

278 context: Mapping[str, Any], 

279) -> nn.Module: 

280 """Construct an already resolved choice without parsing the same request again.""" 

281 context = MappingProxyType(dict(context)) 

282 if member.family.validate is not None: 

283 member.family.validate(config=config, module=module, context=context, member=member) 

284 config = deepcopy(config) 

285 result = member.constructor(**_constructor_arguments(member, config, module, module_fqn, context)) 

286 if not isinstance(result, nn.Module): 

287 raise TypeError("a family constructor must return nn.Module") 

288 requires_reset = _validate_initialization_contract(result) 

289 info = FamilyBuildInfo(request, member, deepcopy(config), "direct" if module is None else "replacement") 

290 result._hp_family_build_info = info # pylint: disable=protected-access 

291 if config is not None and requires_reset: 

292 result._hp_reset_after_materialization = True # pylint: disable=protected-access 

293 return result 

294 

295 

296def build_family( 

297 target: Callable | str | FamilyRequest, 

298 *, 

299 config: Any = None, 

300 mesh: Any = None, 

301 module: nn.Module | None = None, 

302 module_fqn: str = "", 

303 context: Mapping[str, Any] | None = None, 

304 **kwargs: Any, 

305) -> nn.Module: 

306 """Construct a selected member and retain its request for model preparation. 

307 

308 Args: 

309 target: Public family callable, registered name, or preserved request. 

310 config: Complete logical model configuration for direct construction. 

311 mesh: Prebuilt job mesh context; select, shard and bind this component when supplied. 

312 Active CP requires a 'cp' axis in device_mesh. Active EP requires an 'ep' axis 

313 in fsdp_moe_mesh, or device_mesh when no expert view is supplied. 

314 module: Existing source module; mutually exclusive with config. 

315 module_fqn: Source path when converting an existing module. 

316 context: Optional job constraints; without mesh, may supply logical topology for selection. 

317 **kwargs: Explicit selectors and ordinary public factory arguments. 

318 

319 Returns: 

320 The concrete member with construction provenance. Logical/meta builds finish physical work at runtime. 

321 

322 Note: 

323 The family validator receives all public options. Each concrete constructor receives 

324 only the options it explicitly declares; unknown public argument names still raise. 

325 """ 

326 request = _normalize_family_request(target, kwargs) 

327 arguments = dict(request.kwargs) 

328 if "config" in arguments: 

329 if config is not None: 

330 raise ValueError("config was supplied twice") 

331 config = arguments.pop("config") 

332 request = FamilyRequest(request.target, arguments) 

333 if (config is None) == (module is None): 

334 raise ValueError("provide exactly one of config or module") 

335 context = _context_from_mesh(mesh, context) 

336 member = resolve_family(request, context=context) 

337 result = _build_family_member(request, member, config=config, module=module, 

338 module_fqn=module_fqn, context=context) 

339 if mesh is not None: 

340 # Layout discovery imports this module; defer its runtime dependency to avoid a cycle. 

341 from hyper_parallel.distributed._builder.family_layout import _prepare_family_layout # pylint: disable=C0415,R0401 

342 _prepare_family_layout(result, mesh) 

343 return result 

344 

345 

346def get_family_build_info(module: nn.Module) -> FamilyBuildInfo | None: 

347 """Return only framework-created family provenance, or None for ordinary modules. 

348 

349 Args: 

350 module: Module whose construction provenance is queried. 

351 """ 

352 value = getattr(module, "_hp_family_build_info", None) 

353 return value if isinstance(value, FamilyBuildInfo) else None 

354 

355 

356def _family_parameter_shapes(model: nn.Module) -> dict[str, tuple[int, ...]]: 

357 """Return logical parameter shapes even after component construction localized weights.""" 

358 by_identity = {} 

359 for boundary in collect_family_modules(model): 

360 layout = boundary.info.layout 

361 if layout is not None: 

362 for name, shape in layout.parameter_shapes.items(): 

363 identity = id(boundary.module.get_parameter(name)) 

364 if by_identity.setdefault(identity, shape) != shape: 

365 raise ValueError(f"shared family parameter {name!r} has conflicting logical shapes") 

366 return {name: by_identity.get(id(value), tuple(value.shape)) 

367 for name, value in model.named_parameters(remove_duplicate=False)} 

368 

369 

370def _module_aliases(model: nn.Module) -> dict[int, tuple[nn.Module, tuple[str, ...]]]: 

371 """Inventory registered module identities and all paths, including the root.""" 

372 found: dict[int, tuple[nn.Module, list[str]]] = {} 

373 for fqn, module in model.named_modules(remove_duplicate=False): 

374 found.setdefault(id(module), (module, []))[1].append(fqn) 

375 return {identity: (module, tuple(paths)) for identity, (module, paths) in found.items()} 

376 

377 

378def collect_family_modules(model: nn.Module) -> tuple[FamilyBoundary, ...]: 

379 """Discover final family boundaries by object identity, including root and aliases. 

380 

381 Args: 

382 model: Final or source model tree for this build. 

383 """ 

384 boundaries = [] 

385 for module, paths in _module_aliases(model).values(): 

386 info = get_family_build_info(module) 

387 if info is not None: 

388 boundaries.append(FamilyBoundary(module, paths, info)) 

389 return tuple(boundaries) 

390 

391 

392def validate_family_context(model: nn.Module, context: Mapping[str, Any]) -> None: 

393 """Validate that model preparation has finalized members for the job context. 

394 

395 Args: 

396 model: Final or source model tree for this build. 

397 context: Read-only job context and effective model facts. 

398 """ 

399 axes = _axis_sizes(_context_from_mesh(None, context)) 

400 for boundary in collect_family_modules(model): 

401 if boundary.info.layout is not None and boundary.info.layout.applied: 

402 _context_from_mesh(boundary.info.layout.mesh, context) 

403 member = boundary.info.resolved 

404 for axis in ("cp", "ep"): 

405 if member.axis_sizes[axis] != axes[axis]: 

406 raise ValueError( 

407 f"family at {boundary.fqns} was constructed with {axis}={member.axis_sizes[axis]}, " 

408 f"job requires {axes[axis]}; call prepare_model_components with the job context before layout" 

409 ) 

410 

411 

412def _validate_applied_layout(cached: _FamilyLayout, spec: Any, fqn: str) -> None: 

413 """Reject post-construction changes to a component's declared computation layout.""" 

414 original = cached.sharding 

415 if any(name not in original.params or named != original.params[name] for name, named in spec.params.items()): 

416 raise ValueError(f"layout at {fqn!r} conflicts with its constructed family layout") 

417 for field_name in ("in_src", "in_dst", "out_src", "out_dst", "out_names", "is_boundary"): 

418 if getattr(spec, field_name) != getattr(original, field_name): 

419 raise ValueError(f"{field_name} at {fqn!r} conflicts with its constructed family layout") 

420 

421 

422def _record_family_layouts(model, plan, mesh, shapes, source_shard_info, *, applied=True): 

423 """Retain relative declarations once for constructor and model-level application.""" 

424 for boundary in collect_family_modules(model): 

425 fqn = boundary.fqns[0] 

426 if fqn not in plan.modules or boundary.info.resolved.sharding is None: 

427 continue 

428 existing = boundary.info.layout 

429 if existing is not None and existing.applied: 

430 continue 

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

432 names = plan.modules[fqn].params 

433 relative_shapes = {name: shapes[prefix + name] for name in names} 

434 source = {name: source_shard_info[prefix + name] for name in names 

435 if source_shard_info is not None and prefix + name in source_shard_info} 

436 layout = _FamilyLayout(mesh, deepcopy(plan.modules[fqn]), plan.parallel_modules.get(fqn), 

437 MappingProxyType(relative_shapes), MappingProxyType(source), applied) 

438 boundary.module._hp_family_build_info = replace(boundary.info, layout=layout) # pylint: disable=protected-access 

439 

440 

441def _family_source_shard_info(model: nn.Module) -> dict[str, Any]: 

442 """Gather constructed component source layouts under their final model paths.""" 

443 result = {} 

444 for boundary in collect_family_modules(model): 

445 layout = boundary.info.layout 

446 if layout is not None and layout.applied: 

447 for fqn in boundary.fqns: 

448 result.update({f"{fqn}.{name}" if fqn else name: value 

449 for name, value in layout.source_shard_info.items()}) 

450 return result 

451 

452 

453def _same_mesh(first: Any, second: Any) -> bool: 

454 """Compare borrowed job views without copying or reconstructing their groups.""" 

455 return (getattr(first, "device_mesh", first) is getattr(second, "device_mesh", second) 

456 and getattr(first, "fsdp_moe_mesh", None) is getattr(second, "fsdp_moe_mesh", None)) 

457 

458 

459def _family_mesh(model: nn.Module, mesh: Any) -> Any: 

460 """Reuse the complete context when a caller passes its dense DeviceMesh view.""" 

461 layouts = [boundary.info.layout for boundary in collect_family_modules(model) 

462 if boundary.info.layout is not None and boundary.info.layout.applied] 

463 if not hasattr(mesh, "device_mesh"): 

464 mesh = next((layout.mesh for layout in layouts if layout.mesh.device_mesh is mesh), mesh) 

465 if any(not _same_mesh(layout.mesh, mesh) for layout in layouts): 

466 raise ValueError("constructed families cannot be applied with a different job mesh") 

467 return mesh