Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / fully_shard / utils.py: 78%

189 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"""Torch helpers, policies and mesh metadata for fully_shard. 

16 

17The fully_shard core used to reach process-group management, module traversal and 

18tensor plumbing through the platform abstraction layer. Only the torch backend is 

19supported now, so those implementations live here and every caller calls them 

20directly. 

21""" 

22# pylint: disable=C9006,C9007 

23from __future__ import annotations 

24 

25from collections import OrderedDict 

26from collections.abc import Mapping 

27from dataclasses import dataclass, fields, is_dataclass, replace 

28from typing import Any, Callable, Dict, Optional 

29 

30import torch 

31from torch import Tensor, nn 

32from torch.nn.utils.rnn import PackedSequence 

33from torch.utils._pytree import tree_flatten, tree_unflatten 

34 

35from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

36from hyper_parallel.core.dtensor.placement_types import Placement 

37from hyper_parallel.core.utils.communication import get_device_handle 

38from hyper_parallel.core.utils.communication import get_group_local_rank 

39 

40DType = torch.dtype 

41 

42 

43# --------------------------------------------------------------------------- 

44# Module traversal 

45# --------------------------------------------------------------------------- 

46 

47def get_modules(module: nn.Module): 

48 """Return every sub-module contained in ``module``. 

49 

50 Args: 

51 module: The root module to traverse. 

52 

53 Returns: 

54 An iterator over the module tree. 

55 """ 

56 return module.modules() 

57 

58 

59def parameters_dict(cell: nn.Module): 

60 """Return every named parameter registered by the module tree. 

61 

62 Args: 

63 cell: The root module to traverse. 

64 

65 Returns: 

66 An iterator of ``(name, parameter)`` pairs. 

67 """ 

68 return cell.named_parameters() 

69 

70 

71def buffers_dict(cell: nn.Module): 

72 """Return every named buffer registered by the module tree. 

73 

74 Args: 

75 cell: The root module to traverse. 

76 

77 Returns: 

78 An iterator of ``(name, buffer)`` pairs. 

79 """ 

80 return cell.named_buffers() 

81 

82 

83# --------------------------------------------------------------------------- 

84# Tensor plumbing 

85# --------------------------------------------------------------------------- 

86 

87def load_into_param(param: Tensor, data: Tensor) -> None: 

88 """Write ``data`` into ``param``, materialising a meta local tensor first. 

89 

90 Args: 

91 param: The destination parameter, possibly a DTensor. 

92 data: The data to write into it. 

93 """ 

94 from hyper_parallel.core.dtensor.dtensor import DTensor # pylint: disable=C0415 

95 

96 if isinstance(param, DTensor): 

97 local = param._local_tensor # pylint: disable=protected-access 

98 if local.is_meta: 

99 orig_requires_grad = param.requires_grad 

100 param._local_tensor = data # pylint: disable=protected-access 

101 if data.requires_grad != orig_requires_grad: 

102 param.requires_grad_(orig_requires_grad) 

103 else: 

104 local.copy_(data) 

105 else: 

106 param.copy_(data) 

107 

108 

109def cast_fp_tensor(dtype: DType, x: Any) -> Any: 

110 """Cast a floating-point tensor to ``dtype``, leaving anything else alone. 

111 

112 Args: 

113 dtype: The target dtype. 

114 x: The candidate tensor. 

115 

116 Returns: 

117 Any: The cast tensor, or ``x`` unchanged when it is not a floating-point tensor. 

118 """ 

119 if not isinstance(x, Tensor) or not torch.is_floating_point(x) or x.dtype == dtype: 

120 return x 

121 return x.to(dtype) 

122 

123 

124def apply_to_tensors(fn: Callable[[Tensor], Any], container: Any) -> Any: 

125 """Recursively apply ``fn`` to every tensor inside ``container``. 

126 

127 Handles tensors, dataclasses, ordered and plain dicts, named tuples, 

128 lists, tuples, sets and packed sequences. 

129 

130 Args: 

131 fn: The callable applied to each tensor. 

132 container: The structure to walk. 

133 

134 Returns: 

135 Any: A structure of the same shape with every tensor replaced by ``fn``'s result. 

136 """ 

137 

138 def apply_dataclass(x): 

139 leaves, spec = tree_flatten(x) 

140 if not spec.is_leaf(): 

141 mapped = [apply(leaf) for leaf in leaves] 

142 return x if all(old is new for old, new in zip(leaves, mapped)) else tree_unflatten(mapped, spec) 

143 changes = {} 

144 for item in fields(x): 

145 if item.init: 

146 old = getattr(x, item.name) 

147 new = apply(old) 

148 if new is not old: 

149 changes[item.name] = new 

150 return replace(x, **changes) 

151 

152 def apply_mapping(x): 

153 mapped = {key: apply(value) for key, value in x.items()} 

154 if all(mapped[key] is value for key, value in x.items()): 

155 return x 

156 if isinstance(x, OrderedDict): 

157 ordered = x.__class__() 

158 ordered.update(mapped) 

159 return ordered 

160 return mapped 

161 

162 def apply(x): 

163 if isinstance(x, Tensor): 

164 return fn(x) 

165 if is_dataclass(x) and not isinstance(x, type): 

166 return apply_dataclass(x) 

167 if isinstance(x, PackedSequence): 

168 data = apply(x.data) 

169 return x if data is x.data else x._replace(data=data) 

170 if isinstance(x, dict): 

171 return apply_mapping(x) 

172 if not isinstance(x, (list, tuple, set)): 

173 return x 

174 mapped = [apply(item) for item in x] 

175 if all(old is new for old, new in zip(x, mapped)): 

176 return x 

177 if isinstance(x, tuple) and hasattr(x, "_asdict") and hasattr(x, "_fields"): 

178 return type(x)(*mapped) 

179 return type(x)(mapped) 

180 

181 return apply(container) 

182 

183 

184def profiler_record(name: str): 

185 """Return the torch profiler annotation context for ``name``. 

186 

187 Args: 

188 name: Label shown in profiler traces for the enclosed region. 

189 

190 Returns: 

191 A context manager that records the region when the profiler is active. 

192 """ 

193 return torch.profiler.record_function(name) 

194 

195 

196# --------------------------------------------------------------------------- 

197# Gradient-ready stream 

198# --------------------------------------------------------------------------- 

199# The handle and its stream are per-process singletons: at most one gradient 

200# reduction is in flight across the whole process, so the state belongs at 

201# module scope rather than on any scheduler or parameter object. 

202_GRAD_READY_STATE: Dict[str, Any] = { 

203 "handle": None, 

204 "post_process": None, 

205 "stream": None, 

206} 

207 

208 

209def _process_pending_grad_handle() -> None: 

210 """Wait for the in-flight gradient handle and run its post-process callback.""" 

211 handle = _GRAD_READY_STATE["handle"] 

212 if handle is None: 

213 return 

214 handle.wait() 

215 post_process = _GRAD_READY_STATE["post_process"] 

216 if post_process is not None: 

217 post_process() 

218 

219 

220def _grad_ready_stream(): 

221 """Return the stream used to order gradient-handle waits, creating it lazily.""" 

222 if _GRAD_READY_STATE["stream"] is None: 

223 _GRAD_READY_STATE["stream"] = get_device_handle().Stream() 

224 return _GRAD_READY_STATE["stream"] 

225 

226 

227def grad_ready_stream(): 

228 """Return the context manager that switches to the gradient-ready stream. 

229 

230 Returns: 

231 The device stream context manager guarding the synchronisation stream. 

232 """ 

233 return get_device_handle().stream(_grad_ready_stream()) 

234 

235 

236def set_grad_reduce_handle(handle: Any, post_process: Optional[Callable[[], None]] = None) -> None: 

237 """Record a new in-flight gradient reduction handle. 

238 

239 Any previously recorded handle is waited on first, so at most one handle is 

240 ever outstanding. 

241 

242 Args: 

243 handle: The async work handle returned by the reduction collective. 

244 post_process: Callback run once ``handle`` completes, or ``None``. 

245 """ 

246 with grad_ready_stream(): 

247 _process_pending_grad_handle() 

248 _GRAD_READY_STATE["handle"] = handle 

249 _GRAD_READY_STATE["post_process"] = post_process 

250 

251 

252def wait_grad_handle() -> None: 

253 """Block until the in-flight gradient reduction handle completes and clear it.""" 

254 handle = _GRAD_READY_STATE["handle"] 

255 if handle is None: 

256 return 

257 with grad_ready_stream(): 

258 _process_pending_grad_handle() 

259 sync_event = _grad_ready_stream().record_event() 

260 sync_event.wait() 

261 _GRAD_READY_STATE["handle"] = None 

262 _GRAD_READY_STATE["post_process"] = None 

263 

264 

265# --------------------------------------------------------------------------- 

266# Policies and mesh metadata 

267# --------------------------------------------------------------------------- 

268 

269@dataclass 

270class MixedPrecisionPolicy: 

271 """ 

272 Configures mixed precision training for HSDP. 

273 

274 This policy controls data type casting during forward/backward computation 

275 and gradient reduction, enabling memory savings and potential speedups. 

276 

277 Attributes: 

278 param_dtype: Data type for parameter computation. If None, uses original dtype. 

279 reduce_dtype: Data type for gradient reduction. If None, uses the gradient dtype. 

280 output_dtype: Data type for module outputs. If None, no casting applied. 

281 custom_params: Per-parameter overrides that take precedence over this policy's 

282 ``param_dtype`` and ``reduce_dtype`` defaults. 

283 """ 

284 param_dtype: Optional[DType] = None 

285 reduce_dtype: Optional[DType] = None 

286 output_dtype: Optional[DType] = None 

287 cast_forward_inputs: bool = True 

288 apply_grad_on_fp32_main_grad: bool = False 

289 custom_params: Optional[Mapping[nn.Parameter, Mapping[str, Optional[DType]]]] = None 

290 

291 def __post_init__(self) -> None: 

292 """Validate overrides and index dtype configurations by source Parameter ID.""" 

293 if self.custom_params is None: 

294 return 

295 self._check_custom_param() 

296 self.custom_params = { 

297 id(parameter): dict(custom_dtypes) 

298 for parameter, custom_dtypes in self.custom_params.items() 

299 } 

300 

301 def _check_custom_param(self) -> None: 

302 """Validate configured parameter keys and dtype values without changing the mapping.""" 

303 if not isinstance(self.custom_params, Mapping): 

304 raise ValueError("custom_params must map Parameter objects to dtype dictionaries") 

305 for parameter, custom_dtypes in self.custom_params.items(): 

306 if not isinstance(parameter, nn.Parameter): 

307 raise ValueError("custom_params keys must be Parameter objects") 

308 if not isinstance(custom_dtypes, Mapping): 

309 raise ValueError("custom_params values must be dtype dictionaries") 

310 if custom_dtypes.keys() - {"param_dtype", "reduce_dtype"}: 

311 raise ValueError("custom_params only supports param_dtype and reduce_dtype overrides") 

312 for dtype_name, dtype in custom_dtypes.items(): 

313 if dtype is not None and not isinstance(dtype, torch.dtype): 

314 raise ValueError(f"custom_params {dtype_name} must be torch.dtype or None, got {dtype!r}") 

315 

316 

317def resolve_param_dtypes( 

318 policy: MixedPrecisionPolicy, source_parameter_id: int, storage_dtype: DType 

319) -> tuple[Optional[DType], Optional[DType]]: 

320 """Resolve compute and reduction casts for the original parameter identity. 

321 

322 Missing override fields inherit the policy. An explicit None preserves the 

323 storage dtype for compute or the incoming gradient dtype for reduction. 

324 """ 

325 custom_dtypes = (policy.custom_params or {}).get(source_parameter_id, {}) 

326 param_dtype = custom_dtypes.get("param_dtype", policy.param_dtype) 

327 reduce_dtype = custom_dtypes.get("reduce_dtype", policy.reduce_dtype) 

328 if reduce_dtype == param_dtype: 

329 reduce_dtype = None 

330 if param_dtype == storage_dtype: 

331 param_dtype = None 

332 return param_dtype, reduce_dtype 

333 

334 

335@dataclass 

336class OffloadPolicy: 

337 """ 

338 Base class for offload policies. 

339 

340 This represents no offloading and serves as the default policy. 

341 Subclass this to implement custom offload strategies. 

342 """ 

343 

344 

345@dataclass 

346class CPUOffloadPolicy(OffloadPolicy): 

347 """ 

348 Offloads sharded parameters and gradients to CPU memory. 

349 

350 When enabled, sharded parameters are kept on CPU and copied to device 

351 before all-gather. Gradients are copied back to CPU after backward. 

352 This reduces NPU memory usage at the cost of additional data transfers. 

353 

354 Attributes: 

355 pin_memory: If True, pins CPU memory for faster H2D/D2H transfers 

356 and enables overlap with computation. Disable if CPU memory 

357 is constrained. (Default: True) 

358 """ 

359 pin_memory: bool = True 

360 

361 

362@dataclass 

363class CommFusionPolicy(): 

364 enable_comm_fusion: bool = False 

365 comm_fusion_zero_copy: bool = False 

366 

367 

368@dataclass 

369class DataParallelMeshInfo: 

370 mesh: DeviceMesh 

371 shard_mesh_dim: Optional[int] = None 

372 replicate_mesh_dim: Optional[int] = None 

373 

374 def __post_init__(self): 

375 if self.shard_mesh_dim is None and self.replicate_mesh_dim is None: 

376 raise AssertionError( 

377 "At least one of shard_mesh_dim and replicate_mesh_dim must not be None" 

378 ) 

379 

380 

381@dataclass 

382class FSDPMeshInfo(DataParallelMeshInfo): 

383 def __post_init__(self): 

384 super().__post_init__() 

385 if self.shard_mesh_dim is None: 

386 raise AssertionError("Expects non-None shard_mesh_dim") 

387 self.shard_mesh_size: int = self.mesh.mesh_shape[self.shard_mesh_dim] 

388 self.shard_process_group = self.mesh.get_group(self.shard_mesh_dim) 

389 self.shard_mesh_rank: int = get_group_local_rank(self.shard_process_group) 

390 

391 

392@dataclass 

393class DDPMeshInfo(DataParallelMeshInfo): 

394 def __post_init__(self): 

395 super().__post_init__() 

396 if self.replicate_mesh_dim is None: 

397 raise AssertionError("Expects non-None replicate_mesh_dim") 

398 self.replicate_mesh_size: int = self.mesh.mesh_shape[self.replicate_mesh_dim] 

399 self.replicate_process_group = self.mesh.get_group(self.replicate_mesh_dim) 

400 self.replicate_mesh_rank: int = get_group_local_rank(self.replicate_process_group) 

401 

402 

403@dataclass 

404class HSDPMeshInfo(FSDPMeshInfo, DDPMeshInfo): 

405 # pylint: disable=W0246 

406 def __post_init__(self): 

407 # Calls `FSDPMeshInfo` -> `DDPMeshInfo` -> `DataParallelMeshInfo` 

408 super().__post_init__() 

409 

410 

411@dataclass(frozen=True) 

412class SourceShardMetaInfo: 

413 """Describe a parameter's source TP/EP layout before fully_shard.""" 

414 

415 mesh: DeviceMesh 

416 placements: tuple[Placement, ...] 

417 origin_is_dtensor: bool = False 

418 

419 

420__all__ = [ 

421 # Module traversal and tensor plumbing. 

422 "DType", 

423 "get_modules", 

424 "parameters_dict", 

425 "buffers_dict", 

426 "load_into_param", 

427 "cast_fp_tensor", 

428 "apply_to_tensors", 

429 "profiler_record", 

430 # Grad-reduce handle choreography. 

431 "grad_ready_stream", 

432 "set_grad_reduce_handle", 

433 "wait_grad_handle", 

434 # Precision/offload policies and mesh metadata. 

435 "MixedPrecisionPolicy", 

436 "OffloadPolicy", 

437 "CPUOffloadPolicy", 

438 "CommFusionPolicy", 

439 "DataParallelMeshInfo", 

440 "FSDPMeshInfo", 

441 "DDPMeshInfo", 

442 "HSDPMeshInfo", 

443 "SourceShardMetaInfo", 

444 # Re-exported from :mod:`hyper_parallel.core.utils.communication` because 

445 # callers here and in the tests reach them through this module. 

446 "get_device_handle", 

447 "get_group_local_rank", 

448]