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

167 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"""parameter_sharding: parameter-side apply machinery (05 §4.2 + Phase D). 

16 

17Owns parameter placement/localize/stack (merged from the legacy 

18``components/distributed/sharding/apply.py`` — there is exactly one parameter 

19sharding implementation), source-mesh resolution, runtime source_shard_info 

20construction, and the tied-weights replication pass (same-rank shared 

21storage, no cross-rank shard broadcast). 

22""" 

23 

24import logging 

25from contextlib import contextmanager 

26from typing import Any, Dict, List, Tuple 

27 

28import torch 

29from torch import nn 

30 

31from hyper_parallel.components.modules.module_family import ( 

32 _family_source_shard_info, get_family_build_info, _validate_applied_layout, 

33) 

34from hyper_parallel.core.dtensor.dtensor import DTensor, distribute_tensor 

35from hyper_parallel.core.dtensor.placement_types import Shard 

36from hyper_parallel.distributed.recipe_spec import ( 

37 EP, 

38 PlacementMismatchError, 

39 resolve_placements, 

40) 

41from hyper_parallel.distributed._builder.source_shard import ( 

42 build_source_shard_info, 

43) 

44from hyper_parallel.distributed.tensor_parallel.head_count import ( 

45 maybe_update_head_counts, 

46) 

47 

48logger = logging.getLogger(__name__) 

49 

50 

51# ──────────────────────────────────────────────────────────────────────────── 

52# Legacy path helpers (merged from components/distributed/sharding/apply.py) 

53# ──────────────────────────────────────────────────────────────────────────── 

54 

55def _get_attr_by_path(model, fqn): 

56 """Fetch an attribute along a dotted FQN (numeric segments index into ModuleLists).""" 

57 obj = model 

58 for part in fqn.split(".") if fqn else (): 

59 if part.isdigit() and not isinstance(obj, nn.Module): 

60 obj = obj[int(part)] 

61 else: 

62 obj = getattr(obj, part) 

63 return obj 

64 

65 

66def _set_param_by_path(model: nn.Module, fqn: str, new_param) -> None: 

67 """Locate the parent module along a dotted FQN and replace the leaf parameter. 

68 

69 object.__setattr__(model, dotted_name, ...) would only set a stray 

70 attribute on model and would not replace the submodule parameter — you 

71 must walk the path to the true parent module before assigning. 

72 """ 

73 parent, _, leaf = fqn.rpartition(".") 

74 obj = _get_attr_by_path(model, parent) 

75 if hasattr(obj, "register_parameter"): 

76 obj.register_parameter(leaf, new_param) 

77 else: 

78 object.__setattr__(obj, leaf, new_param) 

79 

80 

81def _resolve_module(model, fqn): 

82 """Fetch a module by FQN (the last segment is NOT stripped; call sites pass module FQNs). 

83 

84 Same semantics as _get_attr_by_path — every call site (Phase A/B/C) 

85 passes a module fully-qualified name (e.g. `model.layers.0.self_attn`), 

86 not a parameter FQN, so no last-segment stripping is done (stripping 

87 would incorrectly return the parent module). The empty FQN "" resolves 

88 to the model itself (D-14: a root-level outer spec, e.g. a whole-LM 

89 contract, 05 §13.4). 

90 """ 

91 return _get_attr_by_path(model, fqn) 

92 

93 

94def _local_params_context(model: nn.Module): 

95 """One-shot unwrap at build time: replace DTensor parameters with their 

96 _local_tensor (plain), zero-copy. 

97 

98 Called at the Phase C entry of apply_sharding_plan, before fully_shard; 

99 the permanent unwrap is not restored. _local_tensor shares storage with 

100 the original DTensor (same data_ptr). 

101 

102 Returns a {fqn: placements} snapshot of the placements before unwrapping 

103 (diagnostic use only; the canonical source for source_shard_info is the 

104 ShardingPlan, see build_source_shard_info). 

105 """ 

106 source_shard_records = {} 

107 for name, param in list(model.named_parameters()): 

108 if isinstance(param, DTensor): 

109 source_shard_records[name] = param.placements 

110 _set_param_by_path(model, name, nn.Parameter( 

111 param.to_local(), requires_grad=param.requires_grad)) 

112 return source_shard_records 

113 

114 

115@contextmanager 

116def _temp_local_params(module, exclude=()): 

117 """Temporarily unwrap DTensor parameters inside a validate-mode local region (restored on exit). 

118 

119 Under production the parameters were already permanently unwrapped at build 

120 time, so this context is unnecessary. A validate-mode local region (MoE 

121 all-to-all / HF CP attention) computes on local tensors internally and 

122 needs local parameters; after restoration the DTensor propagation chain is 

123 unbroken. 

124 

125 exclude: relative FQN prefixes of nested-boundary subtrees whose 

126 parameters must stay DTensors (D-14 invariant 3, 05 §13.3 — inner 

127 validate islands dispatch via __torch_function__ and break if the outer 

128 region unwraps their parameters). 

129 """ 

130 excluded = tuple(e.rstrip(".") + "." for e in exclude) 

131 saved = [] 

132 for name, param in list(module.named_parameters(recurse=True)): 

133 if excluded and name.startswith(excluded): 

134 continue 

135 if isinstance(param, DTensor): 

136 saved.append((name, param)) 

137 parent, _, leaf = name.rpartition(".") 

138 owner = _get_attr_by_path(module, parent) 

139 owner._parameters[leaf] = param.to_local() # pylint: disable=protected-access 

140 try: 

141 yield 

142 finally: 

143 for name, param in saved: 

144 _set_param_by_path(module, name, param) 

145 

146 

147class _StackedExperts(nn.Module): 

148 """Container for stacked per-expert weights: gate_proj/up_proj/down_proj 

149 (or w1/w2/w3) become Parameters of shape [E, ...], sharded uniformly by 

150 EP Shard(0) + TP (the D-08 ndim=3 rule).""" 

151 

152 

153def _install_stacked_expert_holders(module: nn.Module, holders: Dict[str, Dict[str, nn.Parameter]]) -> None: 

154 """Replace per-expert containers with their stacked parameter holders.""" 

155 for parent_path, params in holders.items(): 

156 holder = _StackedExperts() 

157 for name, p in params.items(): 

158 holder.register_parameter(name, p) 

159 *path, leaf = parent_path.split(".") 

160 obj = module 

161 for seg in path: 

162 obj = obj[int(seg)] if seg.isdigit() else getattr(obj, seg) 

163 setattr(obj, leaf, holder) # replace the original ModuleList (original expert params freed) 

164 

165 

166def _stack_moe_experts(module: nn.Module, ep_stack: Dict[str, List[str]]) -> None: 

167 """Per-expert parameters → stacked 3D parameters (stack is concat, values 

168 exactly equal). 

169 

170 Executed before _shard_module_params in Phase A: 

171 - fetch weights by source path → torch.stack(dim=0), register onto the 

172 replaced experts holder; 

173 - the original ModuleList is replaced as a whole (memory freed); 

174 - v1 asserts no bias and consistent source-parameter shapes; meta tensors 

175 work the same way (concat of metas). 

176 

177 ep_stack: {stacked relative path: [source parameter relative paths 

178 (ordered by expert idx)]}, e.g. 

179 {"experts.gate_proj": ["experts.0.gate_proj.weight", ...]}. 

180 """ 

181 holders: Dict[str, Dict[str, nn.Parameter]] = {} 

182 for stacked_path, sources in ep_stack.items(): 

183 parent_path, param_name = stacked_path.rsplit(".", 1) 

184 tensors = [] 

185 requires_grad = True 

186 for src in sources: 

187 owner = _resolve_module(module, src.rsplit(".", 1)[0]) 

188 if getattr(owner, "bias", None) is not None: 

189 raise NotImplementedError( 

190 f"D-09 v1 does not support experts with bias " 

191 f"({src.rsplit('.', 1)[0]}); use an EP-aware MoE module instead" 

192 ) 

193 t = _get_attr_by_path(module, src) 

194 tensors.append(t.data if hasattr(t, "data") else t) 

195 requires_grad = getattr(t, "requires_grad", True) 

196 stacked = torch.stack(tensors, dim=0) 

197 holders.setdefault(parent_path, {})[param_name] = nn.Parameter( 

198 stacked, requires_grad=requires_grad) 

199 

200 _install_stacked_expert_holders(module, holders) 

201 

202 

203# ──────────────────────────────────────────────────────────────────────────── 

204# Source-mesh resolution + Phase A parameter sharding (05 §4.2) 

205# ──────────────────────────────────────────────────────────────────────────── 

206 

207def _resolve_parameter_source_meshes(plan, mesh_context, full_mesh, tp_mesh): 

208 """Resolve dense TP and virtual-EP source meshes for one sharding plan.""" 

209 # Lazy import: applier imports parameter_sharding (_resolve_module) at 

210 # module level — importing applier here at module level would cycle. 

211 from hyper_parallel.distributed._builder.applier import ( # pylint: disable=C0415,R0401 

212 _build_expert_mesh, 

213 ) 

214 ep_size = next( 

215 ( 

216 spec._ep_size # pylint: disable=protected-access 

217 for spec in plan.modules.values() 

218 if spec._ep_size > 0 # pylint: disable=protected-access 

219 ), 

220 0, 

221 ) 

222 if mesh_context is not None: 

223 expert_mesh = getattr(mesh_context, "fsdp_moe_mesh", None) 

224 elif ep_size > 0: 

225 expert_mesh = _build_expert_mesh( 

226 full_mesh, 

227 full_mesh.mesh_dim_names, 

228 ep_size, 

229 ) 

230 else: 

231 expert_mesh = None 

232 if ep_size > 0 and expert_mesh is None: 

233 raise ValueError("Virtual-EP plan requires MeshContext.fsdp_moe_mesh") 

234 if expert_mesh is not None: 

235 logger.info( 

236 "virtual-EP mesh: using %s for parameter sharding, explicit compute injection, " 

237 "and FSDP source metadata", 

238 dict(zip(tuple(expert_mesh.mesh_dim_names), tuple(expert_mesh.mesh_shape))), 

239 ) 

240 # Pass the full region meshes: build_source_shard_info strips the FSDP-owned 

241 # axes itself and records the complete source (non-FSDP) layout. 

242 dense_source_mesh = ( 

243 mesh_context.fsdp_non_moe_mesh 

244 if mesh_context is not None and getattr(mesh_context, "fsdp_non_moe_mesh", None) is not None 

245 else tp_mesh 

246 ) 

247 expert_source_mesh = ( 

248 expert_mesh 

249 if expert_mesh is not None and "ep" in expert_mesh.mesh_dim_names 

250 else None 

251 ) 

252 return expert_mesh, dense_source_mesh, expert_source_mesh 

253 

254 

255def _shard_planned_parameters(models, plan, mesh, expert_mesh, validate_mode): 

256 """Shard dense and virtual-EP parameters, then update local metadata.""" 

257 for model in models: 

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

259 module = _resolve_module(model, module_fqn) 

260 info = get_family_build_info(module) 

261 if info is not None and info.layout is not None and info.layout.applied: 

262 _validate_applied_layout(info.layout, spec, module_fqn) 

263 continue 

264 # Runtime planner metadata is internal to the sharding pipeline. 

265 if spec._ep_stack: # pylint: disable=protected-access 

266 _stack_moe_experts( 

267 module, 

268 spec._ep_stack, # pylint: disable=protected-access 

269 ) 

270 if spec._ep_size > 0: # pylint: disable=protected-access 

271 expert_params = { 

272 name: placement 

273 for name, placement in spec.params.items() 

274 if isinstance((placement or {}).get(EP), Shard) 

275 } 

276 dense_params = { 

277 name: placement 

278 for name, placement in spec.params.items() 

279 if not isinstance((placement or {}).get(EP), Shard) 

280 } 

281 _shard_module_params( 

282 module, 

283 expert_params, 

284 expert_mesh, 

285 expert_mesh.mesh_dim_names, 

286 ) 

287 _shard_module_params( 

288 module, 

289 dense_params, 

290 mesh, 

291 plan.mesh_dim_names, 

292 ) 

293 else: 

294 _shard_module_params( 

295 module, 

296 spec.params, 

297 mesh, 

298 plan.mesh_dim_names, 

299 ) 

300 if not validate_mode: 

301 maybe_update_head_counts( 

302 module, 

303 spec, 

304 module_fqn, 

305 mesh, 

306 plan.mesh_dim_names, 

307 ) 

308 

309 

310def _build_runtime_source_shard_info( 

311 models, 

312 plan, 

313 dense_source_mesh, 

314 expert_source_mesh, 

315 validate_mode, 

316): 

317 """Unwrap production parameters and build FSDP source-layout metadata.""" 

318 if validate_mode: 

319 return None 

320 source_shard_records = {} 

321 existing = {} 

322 for model in models: 

323 source_shard_records.update(_local_params_context(model)) 

324 existing.update(_family_source_shard_info(model)) 

325 if not source_shard_records and not existing: 

326 return None 

327 if dense_source_mesh is None and expert_source_mesh is None: 

328 return existing or None 

329 result = build_source_shard_info( 

330 plan, 

331 dense_source_mesh, 

332 expert_source_mesh=expert_source_mesh, 

333 ) 

334 result.update(existing) 

335 return result 

336 

337 

338def _shard_module_params(module, param_specs, mesh, mesh_dim_names): 

339 """distribute_tensor() converts parameters into DTensors. 

340 

341 - meta tensor -> DTensor: _local_tensor remains meta (zero-memory path); 

342 - real tensor -> DTensor: physically split; each rank holds a local shard; 

343 - already a DTensor: skipped if the placement matches, otherwise raises 

344 PlacementMismatchError. 

345 """ 

346 for param_path, named in param_specs.items(): 

347 param = _get_attr_by_path(module, param_path) 

348 placements = tuple(resolve_placements(named, mesh_dim_names)) 

349 if not placements: 

350 continue # no active DTensor axes (all size 1) -- no sharding needed 

351 

352 if isinstance(param, DTensor): 

353 if tuple(param.placements) != placements: 

354 raise PlacementMismatchError( 

355 f"{type(module).__name__}.{param_path}", 

356 placements, tuple(param.placements), "params", 

357 ) 

358 continue 

359 

360 src = param.data if hasattr(param, "data") else param 

361 dt = distribute_tensor(src, mesh, placements) 

362 requires_grad = getattr(param, "requires_grad", True) 

363 _set_param_by_path(module, param_path, 

364 nn.Parameter(dt, requires_grad=requires_grad)) 

365 

366 

367# ──────────────────────────────────────────────────────────────────────────── 

368# Phase D: tied weights 

369# ──────────────────────────────────────────────────────────────────────────── 

370 

371def detect_tied_weights(model: Any) -> List[Tuple[str, str]]: 

372 """Detect tied-weight pairs (embed_tokens.weight <-> lm_head.weight). 

373 

374 In PP scenarios cross-stage pairs cannot be detected; the user must 

375 explicitly declare plan.tied_pairs. 

376 

377 Args: 

378 model: The model to inspect (an HF-style ``nn.Module`` with a 

379 ``config`` carrying ``tie_word_embeddings``). 

380 

381 Returns: 

382 A list of ``(embed_fqn, lm_head_fqn)`` tied-parameter FQN pairs. 

383 """ 

384 tied = [] 

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

386 embed_fqn = lm_head_fqn = None 

387 # remove_duplicate=False: under the default dedup of named_parameters 

388 # a tied parameter appears only once; duplicates must be explicitly 

389 # retained to discover the FQNs of both ends. 

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

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

392 embed_fqn = name 

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

394 lm_head_fqn = name 

395 if embed_fqn and lm_head_fqn: 

396 tied.append((embed_fqn, lm_head_fqn)) 

397 return tied 

398 

399 

400def _broadcast_tied_param(model, tied_pair): 

401 """A tied-weight pair shares storage within this rank (end A's storage is authoritative; end B shares it). 

402 

403 Cross-rank broadcast would be **wrong**: a tied pair (embed/lm_head) is 

404 usually Shard(0)-sharded on both ends, and each rank's local shard carries 

405 a different vocab interval -- broadcasting rank0's shard to rank1 would 

406 corrupt rank1's sharding. Tied semantics require that **within the same 

407 rank** the two ends are the same physical parameter (shared gradients), 

408 not cross-rank consistency (sharding is naturally consistent: same global 

409 source, same placement). 

410 """ 

411 fqn_a, fqn_b = tied_pair 

412 try: 

413 param_a = _get_attr_by_path(model, fqn_a) 

414 param_b = _get_attr_by_path(model, fqn_b) 

415 except AttributeError: 

416 return 

417 if param_a is None or param_b is None: 

418 return 

419 tensor_a = param_a.to_local() if isinstance(param_a, DTensor) else param_a.data 

420 # B shares storage with A (a tied weight is the same physical parameter) 

421 if isinstance(param_b, DTensor): 

422 param_b._local_tensor = tensor_a # pylint: disable=protected-access 

423 else: 

424 param_b.data = tensor_a 

425 

426 

427def _replicate_tied_weights(model, tied_pairs=None): 

428 """Phase D: replicate tied weights across ranks.""" 

429 for tied_pair in (tied_pairs if tied_pairs is not None 

430 else detect_tied_weights(model)): 

431 _broadcast_tied_param(model, tied_pair)