Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / components / modules / engram / host_state.py: 81%

217 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"""Host Engram table ownership across materialization, optimization and checkpoint lifecycle.""" 

16 

17from __future__ import annotations 

18 

19from collections.abc import Callable, Mapping 

20import hashlib 

21import logging 

22import os 

23import time 

24from typing import Any 

25 

26import numpy as np 

27import torch 

28import torch.distributed as dist 

29from torch import nn 

30 

31from hyper_parallel.core.dtensor.placement_types import Shard 

32from hyper_parallel.core.utils.clip_grad import ( 

33 build_norm_shard_plan, 

34 dense_grad_norm_sq_and_refs, 

35 scale_grad_refs_, 

36) 

37from hyper_parallel.components.modules.engram.parallel_engram import ( 

38 sparse_sum_same_ep, 

39 stage_check, 

40 stage_reduce_scalar, 

41) 

42from hyper_parallel.models.external_state import ( 

43 CheckpointRuntime, 

44 CheckpointTensorShard, 

45 ExternalBuildContext, 

46 ExternalLoadContext, 

47 ExternalMaterializationResult, 

48 GradientPreparation, 

49) 

50from hyper_parallel.components.modules.engram.host_checkpoint import ( 

51 HostSidecarLoadPlan, 

52 after_checkpoint_load, 

53 after_weights_only_load, 

54 before_checkpoint_load, 

55 before_checkpoint_save, 

56) 

57from hyper_parallel.components.modules.engram.host_source import materialize_owner_rows 

58from hyper_parallel.components.modules.engram.host_engram_table import HostEngramTable 

59from hyper_parallel.components.modules.engram.host_optimizer import ( 

60 HostSparseOptimizerCoordinator, 

61) 

62 

63logger = logging.getLogger(__name__) 

64 

65_BYTES_PER_GIB = 1 << 30 

66_HOST_WEIGHT_WARNING_GIB = 500 

67 

68 

69class HostEngramState: 

70 """Own final CPU table parameters for this pipeline stage.""" 

71 

72 supports_async_checkpoint = False 

73 

74 def __init__(self, model: nn.Module, tables: Mapping[str, HostEngramTable], mesh_context: Any) -> None: 

75 """Record final local table identities and the stage mesh.""" 

76 self.model = model 

77 self.tables = dict(sorted(tables.items())) 

78 self.mesh_context = mesh_context 

79 for table in self.tables.values(): 

80 table.mesh_context = mesh_context 

81 self.parameters = {f"{fqn}.weight": table.weight for fqn, table in self.tables.items()} 

82 self.optimizer = None 

83 self.sparse_optimizer = None 

84 self.norm_shard_plan = None 

85 

86 def check_identities(self) -> None: 

87 """Reject FSDP, loading or dtype conversion that replaced a Host parameter.""" 

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

89 for fqn, parameter in self.parameters.items(): 

90 table = self.tables[fqn.removesuffix(".weight")] 

91 if (named.get(fqn) is not parameter or parameter.device.type != "cpu" 

92 or parameter.dtype != torch.float32 

93 or tuple(parameter.shape) != (table.rows_per_owner, table.width)): 

94 raise RuntimeError(f"Host Engram parameter identity or device changed: {fqn}") 

95 

96 def weight_digests(self) -> dict[str, str]: 

97 """Fingerprint owner-local row bytes around ordinary model initialization.""" 

98 self.check_identities() 

99 return { 

100 fqn: hashlib.sha256(memoryview(parameter.detach().contiguous().numpy()).cast("B")).hexdigest() 

101 for fqn, parameter in self.parameters.items() 

102 } 

103 

104 def checkpoint_tensor_shards(self) -> dict[str, CheckpointTensorShard]: 

105 """Expose owner-local rows and padding to checkpoint verification tools.""" 

106 self.check_identities() 

107 return { 

108 f"{fqn}.weight": CheckpointTensorShard( 

109 tensor=table.weight, 

110 global_shape=(table.physical_rows, table.width), 

111 offsets=(table.global_row_start, 0), 

112 logical_shape=(table.logical_rows, table.width), 

113 ) 

114 for fqn, table in self.tables.items() 

115 } 

116 

117 def materialize(self, context: ExternalLoadContext) -> ExternalMaterializationResult: 

118 """Install owner-local CPU rows, optionally slicing safetensors by row. 

119 

120 The weight-size warning estimates node usage assuming equally sized shards across local workers. 

121 

122 Args: 

123 context: Build or load lifecycle context. 

124 """ 

125 if int(os.environ.get("LOCAL_RANK", "0")) == 0: 

126 local_workers = int(os.environ.get("LOCAL_WORLD_SIZE", "1")) 

127 shard_bytes = sum(weight.numel() * weight.element_size() for weight in self.parameters.values()) 

128 estimated_bytes = shard_bytes * local_workers 

129 if estimated_bytes >= _HOST_WEIGHT_WARNING_GIB * _BYTES_PER_GIB: 

130 logger.warning( 

131 "Host Engram weights are estimated at %d bytes across %d local workers " 

132 "(warning threshold %d GiB). These large tables may cause a host OOM and crash the node.", 

133 estimated_bytes, local_workers, _HOST_WEIGHT_WARNING_GIB, 

134 ) 

135 source_keys = materialize_owner_rows(self.model, self.tables, context) 

136 self.check_identities() 

137 return ExternalMaterializationResult(frozenset(self.parameters), source_keys) 

138 

139 def materialize_for_recovery(self) -> None: 

140 """Allocate owner-local CPU receive storage without reading or initializing weights.""" 

141 for table in self.tables.values(): 

142 if table.weight.is_meta: 

143 rows = torch.empty_like(table.weight, device="cpu") 

144 torch.utils.swap_tensors(table.weight, nn.Parameter(rows, requires_grad=table.weight.requires_grad)) 

145 self.check_identities() 

146 

147 def recovery_replica_ranks(self, rank: int) -> set[int]: 

148 """Derive same-owner replicas from the mesh used to synchronize sparse gradients.""" 

149 mesh = self.mesh_context 

150 if mesh is None or mesh.device_mesh is None: 

151 return {rank} 

152 moe = mesh.fsdp_moe_mesh 

153 if moe is None: 

154 return set(mesh.device_mesh.rank_list) 

155 ranks = tuple(moe.rank_list) 

156 own = np.unravel_index(ranks.index(rank), moe.mesh_shape) 

157 return { 

158 peer for peer, coordinate in zip(ranks, np.ndindex(moe.mesh_shape)) 

159 if all(name in ("edp_shard", "edp_replicate") or coordinate[axis] == own[axis] 

160 for axis, name in enumerate(moe.mesh_dim_names)) 

161 } 

162 

163 def recovery_schema(self) -> tuple: 

164 """Describe CPU table row ownership without copying table or moment values.""" 

165 return tuple( 

166 (fqn, table.global_row_start, table.rows_per_owner, table.logical_rows, 

167 table.physical_rows, table.width, table.ep_size) 

168 for fqn, table in self.tables.items() 

169 ) 

170 

171 def reset_after_recovery(self) -> None: 

172 """Discard sparse iteration state after the surviving worker has stopped.""" 

173 for table in self.tables.values(): 

174 table.clear_step() 

175 if self.optimizer is not None: 

176 self.optimizer.state = "ACCUMULATING" 

177 self.norm_shard_plan = None 

178 

179 def build_optimizer(self, optimizer_config: Any, *, wrap_dense: Callable[[Any], Any]) -> Any: 

180 """Build dense optimizer once, then combine it with CPU SparseAdam. 

181 

182 Args: 

183 optimizer_config: Dense optimizer configuration. 

184 """ 

185 host_ids = {id(parameter) for parameter in self.parameters.values()} 

186 dense_raw = optimizer_config.target.build( 

187 model=self.model, excluded_param_ids=host_ids, 

188 ).get_optimizer() 

189 dense_ids = {id(param) for group in dense_raw.param_groups for param in group["params"]} 

190 all_ids = {id(param) for param in self.model.parameters() if param.requires_grad} 

191 if dense_ids & host_ids or dense_ids | host_ids != all_ids: 

192 raise ValueError("Dense and Host optimizers do not partition trainable parameters") 

193 dense = wrap_dense(dense_raw) 

194 hparams = getattr(getattr(self.model, "config", None), "engram_sparse_adam_config", None) 

195 if hparams is None: 

196 hparams = {"lr": 1.0e-3} 

197 sparse = torch.optim.SparseAdam(list(self.parameters.values()), **hparams) if self.parameters else None 

198 self.optimizer = HostSparseOptimizerCoordinator(dense, sparse, self.tables) 

199 self.sparse_optimizer = sparse 

200 return self.optimizer 

201 

202 def optimizer_for_dcp(self) -> Any: 

203 """Return the dense optimizer that owns the DCP state.""" 

204 return self.optimizer.optimizer_for_dcp() 

205 

206 def before_checkpoint_save(self, runtime: CheckpointRuntime) -> None: 

207 """Write and verify CPU owner sidecars before dense DCP save. 

208 

209 Args: 

210 runtime: Checkpoint runtime and topology context. 

211 """ 

212 before_checkpoint_save(self, runtime) 

213 

214 def before_checkpoint_load(self, runtime: CheckpointRuntime) -> HostSidecarLoadPlan: 

215 """Validate all Host files before dense DCP state is read. 

216 

217 Args: 

218 runtime: Checkpoint runtime and topology context. 

219 """ 

220 return before_checkpoint_load(self, runtime) 

221 

222 def after_checkpoint_load(self, runtime: CheckpointRuntime, load_plan: HostSidecarLoadPlan) -> None: 

223 """Restore this rank's owner rows and optional sparse moments. 

224 

225 Args: 

226 runtime: Checkpoint runtime and topology context. 

227 load_plan: Validated sidecar schema from this restore attempt. 

228 """ 

229 after_checkpoint_load(self, runtime, load_plan) 

230 

231 def after_weights_only_load(self) -> None: 

232 """Reset sparse moments after a weights-only restore.""" 

233 after_weights_only_load(self) 

234 

235 def is_sparse_norm_representative(self) -> bool: 

236 """Count each owner's synchronized row gradient on one edp replica.""" 

237 mesh = self.mesh_context 

238 if mesh is None or mesh.device_mesh is None or not dist.is_initialized(): 

239 return True 

240 moe = mesh.fsdp_moe_mesh 

241 if moe is None: 

242 return dist.get_rank() == min(mesh.device_mesh.rank_list) 

243 return all(moe.get_local_rank(name) == 0 for name in 

244 ("edp_shard", "edp_replicate") if name in (moe.mesh_dim_names or ())) 

245 

246 def _prepare_sparse_rows(self, gradient_divisor: float = 1.0) -> None: 

247 """Coalesce and synchronize each table before the shared failure gate.""" 

248 mesh = self.mesh_context 

249 failed = False 

250 denominator = 1 if mesh is None else ( 

251 mesh.dp_size * mesh.cp_size * (1 if mesh.loss_parallel else mesh.tp_size) 

252 ) 

253 for table in self.tables.values(): 

254 try: 

255 started = time.perf_counter() 

256 local = table.coalesce_pending() 

257 table.coalesce_seconds += time.perf_counter() - started 

258 local_bad = False 

259 except (ValueError, IndexError) as exc: 

260 logger.error("Host sparse local row validation failed: %s", exc) 

261 local = None 

262 local_bad = True 

263 if stage_check(local_bad, mesh): 

264 failed = True 

265 break 

266 synced = sparse_sum_same_ep(local, mesh, table.width) 

267 synced_nnz = synced._nnz() # pylint: disable=protected-access 

268 table.max_synced_nnz = max(table.max_synced_nnz, synced_nnz) 

269 if stage_check(synced_nnz > table.max_sparse_rows_per_step or 

270 not bool(torch.isfinite(synced.values()).all()), mesh): 

271 failed = True 

272 break 

273 table.pending = torch.sparse_coo_tensor( 

274 synced.indices(), synced.values() / (denominator * gradient_divisor), synced.shape, 

275 ).coalesce() 

276 if mesh is not None and mesh.pp_size > 1: 

277 device_type = mesh.device_mesh.device_type 

278 failure_flag = torch.tensor(int(failed), device=torch.device(device_type)) 

279 dist.all_reduce(failure_flag, op=dist.ReduceOp.MAX) 

280 failed = bool(failure_flag.item()) 

281 if failed: 

282 raise RuntimeError("Host sparse gradient validation failed") 

283 

284 def _combined_gradient_norm(self) -> tuple[torch.Tensor, list[torch.Tensor]]: 

285 """Count each dense shard and synchronized sparse owner exactly once.""" 

286 mesh = self.mesh_context 

287 if self.norm_shard_plan is None: 

288 self.norm_shard_plan = build_norm_shard_plan( 

289 self.model, self.parameters.values(), mesh, 

290 ) 

291 dense_sq, dense_refs = dense_grad_norm_sq_and_refs( 

292 self.model, self.parameters.values(), self.norm_shard_plan, mesh, 

293 ) 

294 sparse_sq = torch.zeros_like(dense_sq) 

295 if self.is_sparse_norm_representative(): 

296 for table in self.tables.values(): 

297 sparse_sq.add_(table.pending.values().square().sum().to(dense_sq.device)) 

298 stage_reduce_scalar(sparse_sq, mesh) 

299 global_sq = dense_sq + sparse_sq 

300 if mesh is not None and mesh.pp_size > 1: 

301 dist.all_reduce(global_sq, op=dist.ReduceOp.SUM) 

302 global_sq.div_(mesh.dp_size * mesh.cp_size * mesh.tp_size) 

303 if not bool(torch.isfinite(global_sq)): 

304 raise RuntimeError("Non-finite combined Engram gradient norm") 

305 return global_sq.sqrt(), dense_refs 

306 

307 def prepare_optimizer_step(self, *, max_norm: float, gradient_divisor: float = 1.0) -> GradientPreparation: 

308 """Normalize owned sparse gradients, then clip jointly with dense gradients. 

309 

310 Args: 

311 max_norm: Joint clipping threshold; nonpositive disables clipping. 

312 gradient_divisor: Step divisor for sparse gradients only; Trainer has 

313 already normalized dense gradients. Defaults to no normalization. 

314 """ 

315 if self.optimizer is None or self.optimizer.state != "ACCUMULATING": 

316 raise RuntimeError("Host gradient preparation requires ACCUMULATING state") 

317 self._prepare_sparse_rows(gradient_divisor) 

318 norm, dense_refs = self._combined_gradient_norm() 

319 coefficient = (torch.clamp(max_norm / (norm + 1.0e-6), max=1.0) 

320 if max_norm > 0 else torch.ones_like(norm)) 

321 scale_grad_refs_(dense_refs, coefficient) 

322 cpu_coefficient = coefficient.cpu() 

323 for table in self.tables.values(): 

324 sparse = table.pending 

325 table.pending = torch.sparse_coo_tensor( 

326 sparse.indices(), sparse.values() * cpu_coefficient, sparse.shape, 

327 ).coalesce() 

328 self.optimizer.state = "PREPARED" 

329 return GradientPreparation(norm, coefficient, norm * coefficient) 

330 

331 

332def _validate_host_source_layout(target: str, layout: Any, ep_size: int) -> None: 

333 """Require the planner's sole EP row shard and reject any second shard.""" 

334 if ep_size == 1: 

335 if layout is not None and any(isinstance(place, Shard) for place in layout[0]): 

336 raise ValueError(f"EP1 Host Engram cannot be sharded: {target}") 

337 return 

338 if layout is None: 

339 raise ValueError(f"Missing EP source layout for {target}") 

340 placements, source_mesh = layout 

341 dim_names = source_mesh.mesh_dim_names or () 

342 if len(placements) != len(dim_names) or sum( 

343 name == "ep" and isinstance(place, Shard) and place.dim == 0 

344 for name, place in zip(dim_names, placements)) != 1: 

345 raise ValueError(f"Host Engram requires exactly one EP Shard(0): {target}") 

346 if any(isinstance(place, Shard) and name != "ep" for name, place in zip(dim_names, placements)): 

347 raise ValueError(f"Host Engram has an unexpected second shard: {target}") 

348 

349 

350def _validate_host_model_mode(model: nn.Module, tables: Mapping[str, HostEngramTable], 

351 context: ExternalBuildContext) -> bool: 

352 """Reject mixed device/Host replacements and unsupported build settings.""" 

353 backend = getattr(getattr(model, "config", None), "engram_storage_backend", "device") 

354 if backend not in ("device", "host"): 

355 raise ValueError("engram_storage_backend must be 'device' or 'host'") 

356 if not tables and backend != "host": 

357 return False 

358 if backend != "host": 

359 raise ValueError("HostEngramModule requires engram_storage_backend='host'") 

360 from hyper_parallel.components.modules.engram import EngramModule # pylint: disable=C0415 

361 if any(isinstance(module, EngramModule) 

362 and not isinstance(module.embed, HostEngramTable) 

363 for module in model.modules()): 

364 raise ValueError("Host Engram configuration still contains a device replacement") 

365 if (context.validate_placement or context.init_device is None 

366 or context.model_init_dtype not in (torch.float32, torch.bfloat16)): 

367 raise ValueError("Host Engram requires meta production build with model_init_dtype=float32 or bfloat16") 

368 return True 

369 

370 

371def build_engram_external_state(model: nn.Module, 

372 context: ExternalBuildContext) -> HostEngramState | None: 

373 """Bind every Host table to the EP row interval selected by the planner. 

374 

375 Args: 

376 model: Model being built or inspected. 

377 context: Build or load lifecycle context. 

378 """ 

379 tables = { 

380 fqn: module for fqn, module in model.named_modules() 

381 if isinstance(module, HostEngramTable) 

382 } 

383 if not _validate_host_model_mode(model, tables, context): 

384 return None 

385 mesh = context.mesh_context 

386 ep_size = mesh.ep_size if mesh is not None else 1 

387 ep_rank = mesh.ep_rank if mesh is not None else 0 

388 ep_mesh = mesh.fsdp_moe_mesh["ep"] if ep_size > 1 else None 

389 if ep_mesh is not None: 

390 ep_rank = ep_mesh.get_local_rank() 

391 for fqn, table in tables.items(): 

392 target = f"{fqn}.weight" 

393 layout = (context.source_shard_info or {}).get(target) 

394 _validate_host_source_layout(target, layout, ep_size) 

395 table.bind_planned_shard( 

396 ep_rank=ep_rank, ep_size=ep_size, 

397 ep_group=ep_mesh.get_group() if ep_mesh is not None else None, 

398 compute_dtype=context.model_init_dtype, 

399 ) 

400 return HostEngramState(model, tables, mesh)