Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / compile / optimizer_state.py: 87%

167 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"""Optimizer-state helpers for graph-mode FSDP. 

16 

17A checkpoint restored before the lazy graph compile materializes optimizer 

18moments at the unsharded parameter shapes. Once FSDPPass shards the live 

19parameters, those tensors must follow the same padded chunk geometry or the 

20first optimizer step sees a shape mismatch. 

21""" 

22 

23import logging 

24from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple 

25 

26import torch 

27import torch.distributed as dist 

28 

29from hyper_parallel.core.distributed_checkpoint.metadata import CHUNK_INFO 

30from hyper_parallel.core.dtensor.layout import infer_slice_area_by_layout 

31from hyper_parallel.core.dtensor.placement_types import StridedShard 

32 

33from .checkpoint_metadata import canonical_parameter_names, has_strided_placement 

34 

35_LOG = logging.getLogger(__name__) 

36 

37 

38def iter_optimizer_leaves(optimizer: Any) -> Iterator[Any]: 

39 """Yield the leaf optimizers that own ``state`` tensors. 

40 

41 Args: 

42 optimizer: Optimizer, chained optimizer, or wrapper to descend into. 

43 """ 

44 children = getattr(optimizer, "chained_optimizers", None) 

45 if children: 

46 for child in children: 

47 yield from iter_optimizer_leaves(child) 

48 return 

49 inner = getattr(optimizer, "optimizer", None) 

50 if inner is not None and inner is not optimizer and hasattr(inner, "state"): 

51 yield from iter_optimizer_leaves(inner) 

52 return 

53 yield optimizer 

54 

55 

56def reshard_state_tensor( 

57 tensor: Any, 

58 full_shape: Sequence[int], 

59 shard_index: int, 

60 degree: int, 

61 n: int, 

62 n_pad: int, 

63) -> Optional[torch.Tensor]: 

64 """Return one rank's padded shard of an unsharded optimizer-state tensor. 

65 

66 Args: 

67 tensor: Dense optimizer-state tensor to shard. 

68 full_shape: Shape of the unsharded parameter. 

69 shard_index: This rank's position along the shard axis. 

70 degree: Number of ranks the parameter is sharded across. 

71 n: True size of dim 0 before padding. 

72 n_pad: Padded size of dim 0 used by FSDP storage. 

73 

74 Returns: 

75 The local padded shard, or None when the tensor does not map. 

76 """ 

77 if not isinstance(tensor, torch.Tensor): 

78 return None 

79 if tuple(tensor.shape) != tuple(full_shape) or tensor.ndim == 0: 

80 return None 

81 if degree <= 1 or n_pad < n or n_pad % degree or not 0 <= shard_index < degree: 

82 return None 

83 shard_size = n_pad // degree 

84 if shard_size <= 0: 

85 return None 

86 start = shard_index * shard_size 

87 tail_shape = (shard_size, *tensor.shape[1:]) 

88 if start >= n: 

89 # This rank owns only padding rows; keep the padded local geometry. 

90 return tensor.new_zeros(tail_shape) 

91 end = start + shard_size 

92 if end <= n: 

93 return tensor[start:end].clone() 

94 # The shard straddles the true extent: copy the real rows and zero-fill the 

95 # padding tail without materializing a full padded copy of the tensor. 

96 shard = tensor.new_zeros(tail_shape) 

97 real = n - start 

98 shard[:real] = tensor[start:n] 

99 return shard 

100 

101 

102def reshard_optimizer_state(compiler: Any, optimizers: Any) -> None: 

103 """Re-shard pre-compile optimizer state onto the live FSDP shards. 

104 

105 Checkpoint restore runs before the lazy graph compile, so a resumed run 

106 materializes dense moments at the unsharded parameter shapes. Once 

107 ``FSDPPass`` shards the parameters, the moments must follow the same padded 

108 chunk geometry; leaving them unsharded makes the first step see a 

109 full-shaped state against a sharded gradient. 

110 

111 Only state tensors shaped exactly like the parameter (AdamW ``exp_avg``, 

112 Muon ``momentum_buffer``, ...) are re-sharded. Scalar bookkeeping is left 

113 alone; any other tensor shape (factored moments and the like) is left 

114 untouched and reported in a single warning, because such state has no 

115 general mapping onto one rectangular shard. 

116 

117 Args: 

118 compiler: Compiled graph compiler owning the sharded live model. 

119 optimizers: One optimizer or a list of optimizers whose leaf ``state`` 

120 tensors should be re-sharded in place. 

121 """ 

122 if compiler.joint_graph is None: 

123 raise RuntimeError( 

124 "reshard_optimizer_state() requires a completed compile: the " 

125 "live parameters are not sharded yet, so there is no FSDP " 

126 "shard geometry to map the dense optimizer state onto" 

127 ) 

128 compiler.attach_shard_metadata(strict_strided=False) 

129 layouts = compiler.parameter_layouts or {} 

130 if not layouts: 

131 return 

132 names = canonical_parameter_names(compiler.model) 

133 padded = getattr(compiler.joint_graph.graph_module, "fsdp_padded_params", {}) 

134 plans, strided, off_axis, unmappable = _optimizer_reshard_plans( 

135 compiler, layouts, names, padded 

136 ) 

137 if not plans and not strided and not off_axis and not unmappable: 

138 return 

139 entries = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers] 

140 unresharded = _reshard_restored_state( 

141 entries, plans, strided, off_axis, unmappable, names 

142 ) 

143 _warn_unresharded(unresharded) 

144 

145 

146def _optimizer_reshard_plans( 

147 compiler: Any, 

148 layouts: Dict[Any, Any], 

149 names: Dict[Any, str], 

150 padded: Dict[str, Tuple[int, int]], 

151) -> Tuple[ 

152 Dict[Any, Tuple[Tuple[int, ...], int, int, int, int]], 

153 Dict[Any, Any], 

154 Dict[Any, Any], 

155 Dict[Any, Any], 

156]: 

157 """Classify live parameters into reshard plans and rejection cases.""" 

158 plans: Dict[Any, Tuple[Tuple[int, ...], int, int, int, int]] = {} 

159 strided: Dict[Any, Tuple[str, Tuple[int, ...]]] = {} 

160 off_axis: Dict[Any, Tuple[str, Tuple[int, ...]]] = {} 

161 unmappable: Dict[Any, Tuple[str, Tuple[int, ...]]] = {} 

162 for parameter, layout in layouts.items(): 

163 name = names.get(parameter) 

164 full_shape = compiler.parameter_shapes.get(name) 

165 if name is None or full_shape is None or not parameter.shape: 

166 continue 

167 if tuple(parameter.shape) == tuple(full_shape): 

168 continue 

169 entry = (name, tuple(full_shape)) 

170 if has_strided_placement(layout): 

171 strided[parameter] = entry 

172 continue 

173 if not _is_plain_dim0_shard(layout): 

174 off_axis[parameter] = entry 

175 continue 

176 plan = _optimizer_reshard_plan(parameter, name, full_shape, padded, layout) 

177 if plan is None: 

178 unmappable[parameter] = entry 

179 else: 

180 plans[parameter] = plan 

181 return plans, strided, off_axis, unmappable 

182 

183 

184def _optimizer_reshard_plan( 

185 parameter: torch.nn.Parameter, 

186 name: str, 

187 full_shape: Tuple[int, ...], 

188 padded: Dict[str, Tuple[int, int]], 

189 layout: Any, 

190) -> Optional[Tuple[Tuple[int, ...], int, int, int, int]]: 

191 """Return the chunk plan for one live shard, or None when unmappable.""" 

192 chunk_info = getattr(parameter, CHUNK_INFO, None) 

193 local_size = int(parameter.shape[0]) 

194 n, n_pad = padded.get(name, (int(full_shape[0]), int(full_shape[0]))) 

195 degree = n_pad // local_size if local_size else 0 

196 if chunk_info is None or degree <= 1 or degree * local_size != n_pad: 

197 return None 

198 # Derive the physical shard index from the unpadded FSDP layout, not the DCP 

199 # chunk offset: ``attach_shard_metadata`` clips the chunk to the true global 

200 # extent, so a rank that owns only padding rows reports an empty logical 

201 # chunk at ``offset == true_dim0`` (e.g. 5 for a [8, ...] pad of a [5, ...] 

202 # param), whose offset is not a multiple of the local shard size. That rank 

203 # is still a valid physical shard and must map to an all-padding slice. 

204 rank = dist.get_rank() if dist.is_available() and dist.is_initialized() else 0 

205 rank_list = tuple(layout.rank_list) 

206 if rank not in rank_list: 

207 return None 

208 area = infer_slice_area_by_layout( 

209 layout, rank_list.index(rank), tuple(layout.tensor_shape) 

210 ) 

211 offset = int(area[0][0]) 

212 if offset % local_size: 

213 return None 

214 return (tuple(full_shape), offset // local_size, degree, n, n_pad) 

215 

216 

217def _reshard_restored_state( 

218 optimizers: List[Any], 

219 plans: Dict[Any, Tuple[Tuple[int, ...], int, int, int, int]], 

220 strided: Dict[Any, Any], 

221 off_axis: Dict[Any, Any], 

222 unmappable: Dict[Any, Any], 

223 names: Dict[Any, str], 

224) -> List[str]: 

225 """Re-shard each leaf optimizer's dense slots and collect leftovers.""" 

226 unresharded: List[str] = [] 

227 for optimizer in optimizers: 

228 for leaf in iter_optimizer_leaves(optimizer): 

229 state = getattr(leaf, "state", None) 

230 if not isinstance(state, dict): 

231 continue 

232 for parameter, slots in state.items(): 

233 unresharded.extend( 

234 _reshard_parameter_slots( 

235 parameter, slots, plans, strided, off_axis, unmappable, names 

236 ) 

237 ) 

238 return unresharded 

239 

240 

241def _reshard_parameter_slots( 

242 parameter: torch.nn.Parameter, 

243 slots: Any, 

244 plans: Dict[Any, Tuple[Tuple[int, ...], int, int, int, int]], 

245 strided: Dict[Any, Any], 

246 off_axis: Dict[Any, Any], 

247 unmappable: Dict[Any, Any], 

248 names: Dict[Any, str], 

249) -> List[str]: 

250 """Re-shard one parameter's slots; return leftover descriptions.""" 

251 if parameter in strided: 

252 _reject_strided_resume(strided[parameter], slots) 

253 return [] 

254 if parameter in off_axis: 

255 _reject_offaxis_resume(off_axis[parameter], slots) 

256 return [] 

257 if parameter in unmappable: 

258 _reject_unmappable_resume(unmappable[parameter], slots) 

259 return [] 

260 plan = plans.get(parameter) 

261 if plan is None or not isinstance(slots, dict): 

262 return [] 

263 full_shape, local_shape = plan[0], tuple(parameter.shape) 

264 leftovers = [] 

265 for key, value in _reshard_slots(slots, plan): 

266 if ( 

267 isinstance(value, torch.Tensor) 

268 and value.ndim > 0 

269 and tuple(value.shape) not in (full_shape, local_shape) 

270 ): 

271 leftovers.append(f"{names.get(parameter)}.{key}: {tuple(value.shape)}") 

272 return leftovers 

273 

274 

275def _warn_unresharded(unresharded: List[str]) -> None: 

276 """Warn once about state tensors matching neither dense nor shard shape.""" 

277 if not unresharded: 

278 return 

279 preview = ", ".join(unresharded[:8]) 

280 if len(unresharded) > 8: 

281 preview += ", ..." 

282 _LOG.warning( 

283 "Left %d optimizer-state tensor(s) un-resharded: their shape " 

284 "matches neither the dense parameter nor its local shard. Exotic " 

285 "state (for example factored moments) is not supported in graph " 

286 "FSDP resume: %s", 

287 len(unresharded), 

288 preview, 

289 ) 

290 

291 

292def _reshard_slots( 

293 slots: Dict[Any, Any], 

294 plan: Tuple[Tuple[int, ...], int, int, int, int], 

295) -> List[Tuple[Any, Any]]: 

296 """Re-shard one parameter's slots; return the slots left untouched.""" 

297 left = [] 

298 for key, value in list(slots.items()): 

299 reshaped = reshard_state_tensor(value, *plan) 

300 if reshaped is not None: 

301 slots[key] = reshaped 

302 else: 

303 left.append((key, value)) 

304 return left 

305 

306 

307def _reject_strided_resume( 

308 entry: Tuple[str, Tuple[int, ...]], 

309 slots: Any, 

310) -> None: 

311 """Fail loudly when dense state cannot map onto a strided dim-0 shard.""" 

312 name, full_shape = entry 

313 if not isinstance(slots, dict): 

314 return 

315 if not _has_dense_slot(slots, full_shape): 

316 return 

317 raise RuntimeError( 

318 f"Cannot reshard restored optimizer state for {name!r}: its dim-0 " 

319 "FSDP shard is strided (for example TP and FSDP shard the same axis), " 

320 "so the dense state has no single contiguous slice to map onto. " 

321 "Resume with a layout that does not combine strided dim-0 shards." 

322 ) 

323 

324 

325def _reject_offaxis_resume( 

326 entry: Tuple[str, Tuple[int, ...]], 

327 slots: Any, 

328) -> None: 

329 """Fail loudly when dense state maps to a non-contiguous dim-0 shard.""" 

330 name, full_shape = entry 

331 if not isinstance(slots, dict): 

332 return 

333 if not _has_dense_slot(slots, full_shape): 

334 return 

335 raise RuntimeError( 

336 f"Cannot reshard restored optimizer state for {name!r}: its FSDP " 

337 "shard is not a single contiguous dim-0 block (it shards another " 

338 "axis or spans several mesh dims), so the dense state has no single " 

339 "contiguous slice to map onto. Resume with a layout whose FSDP shard " 

340 "uses one non-strided dim-0 placement." 

341 ) 

342 

343 

344def _reject_unmappable_resume( 

345 entry: Tuple[str, Tuple[int, ...]], 

346 slots: Any, 

347) -> None: 

348 """Fail loudly when a sharded param has dense state but no shard geometry.""" 

349 name, full_shape = entry 

350 if not isinstance(slots, dict): 

351 return 

352 if not _has_dense_slot(slots, full_shape): 

353 return 

354 raise RuntimeError( 

355 f"Cannot reshard restored optimizer state for {name!r} (dense shape " 

356 f"{tuple(full_shape)}): the parameter is FSDP-sharded but its shard " 

357 "geometry is unavailable or inconsistent with the padded layout. " 

358 "This can happen with an uneven (unpadded) shard or when the sharding " 

359 "metadata name does not match the parameter. Resume from a checkpoint " 

360 "written by a compatible run." 

361 ) 

362 

363 

364def _has_dense_slot(slots: Dict[Any, Any], full_shape: Tuple[int, ...]) -> bool: 

365 """Whether any slot tensor still has the unsharded parameter shape.""" 

366 return any( 

367 isinstance(value, torch.Tensor) and tuple(value.shape) == full_shape 

368 for value in slots.values() 

369 ) 

370 

371 

372def _is_plain_dim0_shard(layout: Any) -> bool: 

373 """Whether dim 0 is sharded by exactly one non-strided placement.""" 

374 placements = tuple(layout.placements or ()) 

375 shard_axes = [ 

376 index for index, placement in enumerate(placements) if placement.is_shard(0) 

377 ] 

378 return len(shard_axes) == 1 and not isinstance( 

379 placements[shard_axes[0]], StridedShard 

380 )