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

343 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"""hybrid shard data parallel interface""" 

16import warnings 

17from collections import namedtuple 

18from typing import Any, List, Mapping, cast, Optional, Union 

19 

20import torch 

21import torch.distributed as dist 

22from torch import Tensor, nn 

23 

24from hyper_parallel.core.fully_shard.utils import ( 

25 MixedPrecisionPolicy, 

26 OffloadPolicy, 

27 SourceShardMetaInfo, 

28 load_into_param, 

29 parameters_dict, 

30 wait_grad_handle, 

31) 

32from hyper_parallel.core.utils.communication import get_device_handle 

33from hyper_parallel.core.fully_shard.hsdp_scheduler import HSDPSchedulerV2 

34from hyper_parallel.core.fully_shard.state_dict_utils import ( 

35 get_model_state_dict as get_model_state_dict_impl, 

36 set_model_state_dict as set_model_state_dict_impl, 

37) 

38from hyper_parallel import DeviceMesh, init_device_mesh 

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

40from hyper_parallel.core.fully_shard.hsdp_utils import ( 

41 get_managed_modules_parameters, 

42) 

43 

44origin_class_to_extend_class = {} 

45 

46 

47def _resolve_comm_fusion_zero_copy_default( 

48 comm_fusion: bool, 

49 comm_fusion_zero_copy: Optional[bool], 

50) -> bool: 

51 """Resolve the default for the comm_fusion zero-copy path.""" 

52 if comm_fusion_zero_copy is not None: 

53 return comm_fusion_zero_copy 

54 return comm_fusion 

55 

56 

57def _check_strict_keys( 

58 module: nn.Module, state_dict: Mapping[str, Any], 

59) -> None: 

60 """Raise ``RuntimeError`` if *state_dict* keys do not match *module*.""" 

61 expected_keys = set(module.state_dict().keys()) 

62 missing = expected_keys - set(state_dict.keys()) 

63 unexpected = set(state_dict.keys()) - expected_keys 

64 error_msgs: list[str] = [] 

65 if missing: 

66 error_msgs.append( 

67 "Missing key(s): " + ", ".join(repr(k) for k in sorted(missing)) 

68 ) 

69 if unexpected: 

70 error_msgs.append( 

71 "Unexpected key(s): " + ", ".join(repr(k) for k in sorted(unexpected)) 

72 ) 

73 if error_msgs: 

74 raise RuntimeError( 

75 f"Error(s) in loading state_dict for " 

76 f"{module.__class__.__name__}:\n\t" 

77 + "\n\t".join(error_msgs) 

78 ) 

79 

80 

81def _resolve_local_tensor( 

82 key: str, val: Tensor, target: DTensor, 

83) -> Tensor: 

84 """Return the local shard tensor to be loaded into *target*.""" 

85 if isinstance(val, DTensor): 

86 return val.to_local() 

87 local_shape = tuple(target.local_shape) 

88 global_shape = tuple(target.shape) 

89 val_shape = tuple(val.shape) 

90 if val_shape == local_shape: 

91 return val 

92 if val_shape == global_shape: 

93 wrapped = distribute_tensor( 

94 val, target.device_mesh, 

95 target.layout.alias_placements if target.layout else target.placements, 

96 ) 

97 return wrapped.to_local() 

98 

99 raise ValueError( 

100 f"load '{key}': plain tensor shape {val_shape} " 

101 f"matches neither local shard {local_shape} " 

102 f"nor global {global_shape}." 

103 ) 

104 

105 

106class _UnshardHandle: 

107 """Unshard handle for user call HSDPModule.unshard(async_op=True)""" 

108 def __init__(self, hsdp_state=None): 

109 """ 

110 Initialize an async unshard handle. 

111 

112 Args: 

113 hsdp_state (HSDPState, optional): The state to wait on. None means a no-op handle. 

114 """ 

115 self._hsdp_state = hsdp_state 

116 

117 def wait(self): 

118 """Block until the async unshard operation completes.""" 

119 if self._hsdp_state is not None: 

120 self._hsdp_state.wait_for_unshard() 

121 self._hsdp_state = None 

122 

123 

124class HSDPModule: 

125 """ 

126 The hsdp block of neural networks with hsdp interface. 

127 """ 

128 

129 def __init__(self): 

130 """Initialize HSDPModule.""" 

131 self.hsdp_scheduler = None # Initialized in hsdp_init() 

132 

133 def _apply(self, *args: Any, **kwargs: Any) -> Any: 

134 """Apply a tensor conversion while preserving HSDP parameter storage. 

135 

136 ``nn.Module._apply`` can replace the DTensor local storage while an 

137 unsharded parameter buffer is still materialized on the device. HSDP 

138 must reshard before delegating to the conversion and rebuild its 

139 sharded-parameter bookkeeping afterwards. The bookkeeping reset is a 

140 storage operation and must not become part of an autograd graph. 

141 

142 The module's original class is added after HSDPModule in the runtime 

143 MRO, so static analysis cannot resolve the delegated ``_apply``. 

144 """ 

145 if not hasattr(self, "hsdp_scheduler") or self.hsdp_scheduler is None: 

146 return super()._apply(*args, **kwargs) # pylint: disable=no-member 

147 self.reshard() 

148 result = super()._apply(*args, **kwargs) # pylint: disable=no-member 

149 hsdp_state = self.hsdp_scheduler.hsdp_state 

150 if hsdp_state is None: 

151 return result 

152 with torch.no_grad(): 

153 for hsdp_param in hsdp_state.hsdp_params: 

154 hsdp_param.reset_sharded_param() 

155 if hsdp_state.param_group is not None: 

156 for bucket in hsdp_state.param_group.all_gather_buckets: 

157 # Conversion rebinds shards; an obsolete zero-copy buffer 

158 # must not keep the previous device allocation resident. 

159 if not bucket.is_flat_buffer_valid(): 

160 bucket.flat_param_buffer = None 

161 return result 

162 

163 def hsdp_init(self, module, mesh, reshard_after_forward, 

164 shard_placement_fn, mp_policy, offload_policy, ignored_params, replicate_params, device, 

165 comm_fusion, comm_fusion_zero_copy: Optional[bool] = None, 

166 source_shard_infos: Optional[Mapping[nn.Parameter, SourceShardMetaInfo]] = None): 

167 """init hsdp2 scheduler.""" 

168 resolved_comm_fusion_zero_copy = _resolve_comm_fusion_zero_copy_default( 

169 comm_fusion, 

170 comm_fusion_zero_copy, 

171 ) 

172 

173 self.hsdp_scheduler = HSDPSchedulerV2(module, 

174 mesh, 

175 reshard_after_forward, 

176 shard_placement_fn, 

177 mp_policy, 

178 offload_policy, 

179 ignored_params, 

180 replicate_params, 

181 device, 

182 comm_fusion, 

183 resolved_comm_fusion_zero_copy, 

184 source_shard_infos=source_shard_infos, 

185 ) 

186 

187 def set_requires_gradient_sync(self, requires_grad_sync: bool, *, recurse: bool = True) -> None: 

188 """Set gradient synchronization for this module and optionally its descendants.""" 

189 if not isinstance(requires_grad_sync, bool): 

190 raise ValueError("requires_grad_sync must be bool") 

191 if not isinstance(recurse, bool): 

192 raise ValueError("recurse must be bool") 

193 self_module = cast(nn.Module, self) 

194 for _, module in self_module.named_modules() if recurse else (("", self),): 

195 if isinstance(module, HSDPModule): 

196 module.hsdp_scheduler.set_requires_grad_sync(requires_grad_sync) 

197 

198 def set_modules_to_forward_prefetch(self, modules): 

199 """set forward prefetch module list to prefetch all gather for unsharded parameters""" 

200 if not isinstance(modules, (tuple, list)): 

201 raise ValueError("modules must be HSDPModule list") 

202 for module in modules: 

203 if not isinstance(module, HSDPModule): 

204 raise ValueError(f"modules must be HSDPModule list but got {type(module)} in list.") 

205 if not hasattr(self, "hsdp_scheduler"): 

206 raise ValueError("call hsdp interface first.") 

207 self.hsdp_scheduler.set_forward_prefetch_cells(modules) 

208 

209 def set_modules_to_backward_prefetch(self, modules): 

210 """set backward prefetch module list to prefetch all gather for unsharded parameters""" 

211 if not isinstance(modules, (tuple, list)): 

212 raise ValueError("modules must be HSDPModule list") 

213 for module in modules: 

214 if not isinstance(module, HSDPModule): 

215 raise ValueError(f"modules must be HSDPModule list but got {type(module)} in list.") 

216 if not hasattr(self, "hsdp_scheduler"): 

217 raise ValueError("call fully_shard interface first.") 

218 self.hsdp_scheduler.set_backward_prefetch_cells(modules) 

219 

220 def reshard(self) -> None: 

221 """reshard all sharded parameters""" 

222 if not self.hsdp_scheduler: 

223 raise ValueError("hsdp_scheduler is None") 

224 hsdp_state = self.hsdp_scheduler.hsdp_state 

225 if hsdp_state: 

226 hsdp_state.shard() 

227 

228 def unshard(self, async_op: bool = False): 

229 """unshard all sharded parameters""" 

230 if not isinstance(async_op, bool): 

231 raise ValueError(f"async_op should be a bool, got {type(async_op)}") 

232 if not self.hsdp_scheduler: 

233 raise ValueError("hsdp_scheduler is None") 

234 hsdp_state = self.hsdp_scheduler.hsdp_state 

235 if hsdp_state: 

236 hsdp_state.unshard(async_op) # pylint: disable=too-many-function-args 

237 if async_op: 

238 return _UnshardHandle(hsdp_state=hsdp_state) 

239 return None 

240 

241 def load_state_dict( 

242 self, 

243 state_dict: Mapping[str, Any], 

244 strict: bool = True, 

245 assign: bool = False, 

246 ): 

247 """ 

248 Load state dict by copying directly into local shards. 

249 

250 Bypasses ``super().load_state_dict()`` because the standard PyTorch 

251 implementation triggers ``copy_`` through the DTensor dispatcher, which 

252 is not registered in the hyper-parallel layout system. 

253 

254 Each value in ``state_dict`` is dispatched by type: 

255 - hyper DTensor: extract local shard and copy directly. 

256 - plain Tensor whose shape == local shard shape: copy as-is. 

257 - plain Tensor whose shape == global shape: distribute via 

258 ``distribute_tensor``, then copy the local shard. 

259 

260 Args: 

261 state_dict (Mapping[str, Any]): Fully-qualified parameter/buffer 

262 names mapped to tensors (DTensor or plain Tensor). 

263 strict (bool): If ``True`` (default), missing or unexpected keys 

264 raise ``RuntimeError``, matching ``nn.Module.load_state_dict`` 

265 semantics. 

266 assign (bool): When ``True`` *and* every value in ``state_dict`` is 

267 already a hyper DTensor, defer to the standard 

268 ``nn.Module.load_state_dict(assign=True)``, which replaces the 

269 module's parameters/buffers with the given DTensors instead of 

270 copying into existing storage. This is required when loading 

271 sharded DTensors onto a meta-device model (e.g. 

272 ``cpu_ram_efficient_loading``). If ``state_dict`` contains any 

273 plain tensor (local-shard or global shape), ``assign`` is 

274 ignored and the copy/distribute path below is used so the 

275 target stays a properly sharded DTensor. 

276 

277 Raises: 

278 RuntimeError: When ``strict`` is ``True`` and keys do not match. 

279 ValueError: When a plain tensor shape matches neither the local 

280 shard shape nor the global shape of the target DTensor. 

281 """ 

282 if assign and state_dict and all( 

283 isinstance(val, DTensor) for val in state_dict.values() 

284 ): 

285 return super().load_state_dict(state_dict, strict=strict, assign=True) 

286 self_module = cast(nn.Module, self) 

287 

288 target_map: dict[str, Tensor] = {} 

289 for name, p in parameters_dict(self_module): 

290 target_map[name] = p 

291 for name, b in self_module.named_buffers(): 

292 target_map[name] = b 

293 

294 if strict: 

295 _check_strict_keys(self_module, state_dict) 

296 

297 with torch.no_grad(): 

298 for key, val in state_dict.items(): 

299 target = target_map.get(key) 

300 if target is None: 

301 continue 

302 

303 if isinstance(target, DTensor): 

304 val = _resolve_local_tensor(key, val, target) 

305 load_into_param(target, val) 

306 

307 # Trigger load_state_dict post-hooks so that HSDP internal 

308 # bookkeeping (e.g. _sharded_param_data) stays in sync. 

309 # Pass an IncompatibleKeys with the same attribute names as PyTorch 

310 # so external hooks can safely read .missing_keys/.unexpected_keys. 

311 _IK = namedtuple("IncompatibleKeys", ["missing_keys", "unexpected_keys"]) 

312 incompatible_keys = _IK([], []) 

313 for _, module in self_module.named_modules(): 

314 hooks = module._load_state_dict_post_hooks # pylint: disable=protected-access 

315 for hook in hooks.values(): 

316 hook(module, incompatible_keys) 

317 

318 def set_is_last_backward(self, is_last_backward: bool): 

319 """set is_last_backward flag""" 

320 self.hsdp_scheduler.scheduler_ctx.is_last_backward = is_last_backward 

321 

322 def set_reduce_comm_interval(self, interval: int = 1) -> None: 

323 """Set the non-fused reduction interval for the entire FSDP module tree. 

324 

325 Call on the root module before its first forward. A unit's reduce-scatter 

326 is waited after the next ``interval`` non-fused units finish backward; 

327 units without gradients still count. Larger intervals retain more 

328 communication buffers. Root backward always drains the remaining work. 

329 

330 Args: 

331 interval: Positive number of subsequent non-fused units to overlap. 

332 

333 Raises: 

334 ValueError: If the interval is invalid, fully_shard has not initialized 

335 the module, or the root has already started its first forward. 

336 

337 Note: 

338 Communication fusion supports only interval=1. Configuring a larger 

339 interval on a fused root warns and falls back to one for the tree. 

340 """ 

341 if isinstance(interval, bool) or not isinstance(interval, int) or interval < 1: 

342 raise ValueError(f"interval must be a positive int, but got {interval!r}.") 

343 if self.hsdp_scheduler is None: 

344 raise ValueError("call fully_shard before setting reduce communication interval") 

345 ctx = self.hsdp_scheduler.scheduler_ctx 

346 if ctx.lazy_init_done: 

347 raise ValueError("set reduce communication interval before the root module's first forward") 

348 if self.hsdp_scheduler.comm_fusion_policy.enable_comm_fusion and interval > 1: 

349 warnings.warn( 

350 "reduce communication intervals greater than one are not supported when " 

351 "comm_fusion=True; using interval=1.", 

352 UserWarning, 

353 stacklevel=2, 

354 ) 

355 interval = 1 

356 ctx.reduce_interval = interval 

357 

358 def reset_iter_state(self, recursive: bool = True) -> None: 

359 """Reset fully_shard iteration bookkeeping without clearing optimizer gradients. 

360 

361 This method must be called only after communication for the iteration has 

362 completed. It does not wait in-flight collectives or clear 

363 ``sharded_param.grad``/``main_grad``. 

364 

365 Args: 

366 recursive: Whether to reset every HSDPModule in this module tree. 

367 

368 Raises: 

369 ValueError: If ``recursive`` is not a bool. 

370 """ 

371 if not isinstance(recursive, bool): 

372 raise ValueError(f"recursive should be a bool, got {type(recursive)}") 

373 self_module = cast(nn.Module, self) 

374 modules = ( 

375 [module for _, module in self_module.named_modules()] 

376 if recursive 

377 else [self_module] 

378 ) 

379 for module in modules: 

380 if isinstance(module, HSDPModule): 

381 module.hsdp_scheduler.reset_iter_state() 

382 

383 def set_requires_all_reduce(self, requires_all_reduce: bool, *, recurse: bool = True) -> None: 

384 """Set all-reduce for this module and optionally its descendants.""" 

385 if not isinstance(requires_all_reduce, bool): 

386 raise ValueError("requires_all_reduce must be bool") 

387 if not isinstance(recurse, bool): 

388 raise ValueError("recurse must be bool") 

389 self_module = cast(nn.Module, self) 

390 for _, module in self_module.named_modules() if recurse else (("", self),): 

391 if isinstance(module, HSDPModule): 

392 module.hsdp_scheduler.set_requires_all_reduce(requires_all_reduce) 

393 

394 def set_reshard_after_forward(self, reshard_after_forward: bool, recurse: bool = True) -> None: 

395 """Set forward resharding for this module and optionally its descendants.""" 

396 if not isinstance(reshard_after_forward, bool): 

397 raise ValueError("reshard_after_forward must be bool") 

398 if not isinstance(recurse, bool): 

399 raise ValueError("recurse must be bool") 

400 self_module = cast(nn.Module, self) 

401 for _, module in self_module.named_modules() if recurse else (("", self),): 

402 if isinstance(module, HSDPModule): 

403 module.hsdp_scheduler.set_reshard_after_forward(reshard_after_forward) 

404 

405 def set_reshard_after_backward(self, reshard_after_backward: bool, recurse: bool = True) -> None: 

406 """Set backward resharding for this module and optionally its descendants.""" 

407 if not isinstance(reshard_after_backward, bool): 

408 raise ValueError("reshard_after_backward must be bool") 

409 if not isinstance(recurse, bool): 

410 raise ValueError("recurse must be bool") 

411 self_module = cast(nn.Module, self) 

412 for _, module in self_module.named_modules() if recurse else (("", self),): 

413 if isinstance(module, HSDPModule): 

414 module.hsdp_scheduler.set_reshard_after_backward(reshard_after_backward) 

415 

416 def set_reduce_op_type(self, reduce_op_type, recurse: bool = True) -> None: 

417 """ 

418 set reduce_op_type for all reduce operations in HSDP 

419 support reduce_op_type "avg" and "sum", default is "avg" 

420 """ 

421 self_module = cast(nn.Module, self) 

422 if recurse: 

423 sub_modules = [m for _, m in self_module.named_modules()] 

424 else: 

425 sub_modules = [self_module] 

426 for module in sub_modules: 

427 if isinstance(module, HSDPModule): 

428 hsdp_state = module.hsdp_scheduler.hsdp_state 

429 if hsdp_state: 

430 hsdp_state.set_reduce_op_type(reduce_op_type) 

431 

432 def set_gradient_scaling_factor(self, factor=None): 

433 """ 

434 Set a multiplicative scaling factor applied to gradients after 

435 reduce-scatter / all-reduce and before they are written into 

436 ``sharded_param.grad``. 

437 

438 ``factor`` may be ``None`` (disable scaling), a Python ``float``/``int``, 

439 or a 0-dim/1-element tensor. Setting ``factor`` to ``None`` (the default 

440 on construction) skips the scaling op entirely so no extra device-side 

441 ``mul_`` is launched on the hot path. 

442 

443 Args: 

444 factor (None | float | int | torch.Tensor): Scaling coefficient. 

445 Use ``None`` to disable scaling. 

446 

447 Raises: 

448 ValueError: If ``factor`` is not one of the supported types or is a 

449 tensor with more than one element. 

450 """ 

451 if factor is not None: 

452 if isinstance(factor, bool): 

453 raise ValueError( 

454 f"gradient_scaling_factor must be None, float, int or a 1-element Tensor, " 

455 f"but got bool {factor}." 

456 ) 

457 if isinstance(factor, Tensor): 

458 if factor.numel() != 1: 

459 raise ValueError( 

460 f"gradient_scaling_factor tensor must have exactly 1 element, " 

461 f"but got shape {tuple(factor.shape)}." 

462 ) 

463 elif not isinstance(factor, (float, int)): 

464 raise ValueError( 

465 f"gradient_scaling_factor must be None, float, int or a 1-element Tensor, " 

466 f"but got {type(factor).__name__}." 

467 ) 

468 hsdp_state = self.hsdp_scheduler.hsdp_state 

469 if hsdp_state: 

470 hsdp_state.set_gradient_scaling_factor(factor) 

471 

472 

473def _extend_module_with_hsdp_interface(module): 

474 """Dynamically extend module's class to inherit from HSDPModule, adding HSDP capabilities.""" 

475 origin_class = module.__class__ 

476 extend_class = origin_class_to_extend_class.get(origin_class, None) 

477 if extend_class is None: 

478 extend_class = type(f"HSDP{origin_class.__name__}", (HSDPModule, origin_class), {}) 

479 origin_class_to_extend_class[origin_class] = extend_class 

480 module.__class__ = extend_class 

481 

482 

483def _get_root_modules(modules: List[nn.Module]) -> List[nn.Module]: 

484 """ 

485 Returns the modules in ``modules`` that are root modules (i.e. parent-less) 

486 with respect to the set ``modules``. In other words, these are the modules 

487 in ``modules`` that are not the child of any other module in ``modules``. 

488 

489 Aligned with PyTorch torch.distributed.utils._get_root_modules. 

490 """ 

491 root_modules: List[nn.Module] = [] 

492 

493 def _get_submodules(mod): 

494 return set(mod.modules()) 

495 

496 module_to_modules: dict[nn.Module, set] = { 

497 m: _get_submodules(m) for m in modules 

498 } 

499 for candidate in modules: 

500 is_root = True 

501 for mod, submodules in module_to_modules.items(): 

502 if candidate is not mod and candidate in submodules: 

503 is_root = False 

504 break 

505 if is_root: 

506 root_modules.append(candidate) 

507 return root_modules 

508 

509 

510def _check_module_valid(module): 

511 """check module valid""" 

512 if not isinstance(module, nn.Module): 

513 raise ValueError(f"module's type must be nn.Module but got {type(module)}.") 

514 

515 

516def _validate_module_for_fully_shard( 

517 module: Union[nn.Module, List[nn.Module]] 

518) -> None: 

519 """Validate module(s) for fully_shard.""" 

520 if isinstance(module, list): 

521 if len(module) == 0: 

522 raise ValueError("fully_shard does not support empty list of modules.") 

523 for i, m in enumerate(module): 

524 try: 

525 _check_module_valid(m) 

526 except ValueError: 

527 raise ValueError( 

528 f"fully_shard expects nn.Module or list[nn.Module], " 

529 f"but got list with {type(m).__name__} at index {i}." 

530 ) from None 

531 else: 

532 _check_module_valid(module) 

533 

534 

535HsdpValidationOptions = namedtuple( 

536 "HsdpValidationOptions", 

537 [ 

538 "shard_size", 

539 "threshold", 

540 "optimizer_level", 

541 "enable_grad_accumulation", 

542 "grad_scale", 

543 "reduce_dtype", 

544 "comm_async", 

545 "comm_fusion", 

546 "bucket_size", 

547 ], 

548) 

549 

550 

551def _validate_hsdp_shard_size(shard_size: int) -> None: 

552 if not isinstance(shard_size, int) or (shard_size <= 0 and shard_size != -1): 

553 raise ValueError(f"shard_size must be a positive integer, but got {shard_size}.") 

554 

555 

556def _validate_hsdp_threshold(threshold: int) -> None: 

557 if not isinstance(threshold, int) or threshold < 0: 

558 raise ValueError(f"threshold must be a positive integer or 0, but got {threshold}.") 

559 

560 

561def _validate_hsdp_optimizer_level(optimizer_level: str) -> None: 

562 if optimizer_level not in ["level1", "level2", "level3"]: 

563 raise ValueError( 

564 f"Optimizer level should in ['level1', 'level2', 'level3'], but got {optimizer_level}." 

565 ) 

566 

567 

568def _validate_hsdp_reduce_dtype(reduce_dtype) -> None: 

569 """Check ``reduce_dtype`` is a torch dtype or ``None``.""" 

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

571 raise ValueError(f"reduce_dtype must be torch.dtype but got {reduce_dtype}.") 

572 

573 

574def _check_hsdp_input_valid(module, options: HsdpValidationOptions): 

575 """check hsdp input valid""" 

576 _check_module_valid(module) 

577 _validate_hsdp_shard_size(options.shard_size) 

578 _validate_hsdp_threshold(options.threshold) 

579 _validate_hsdp_optimizer_level(options.optimizer_level) 

580 if not isinstance(options.enable_grad_accumulation, bool): 

581 raise ValueError( 

582 f"enable_grad_accumulation must be bool but got {options.enable_grad_accumulation}." 

583 ) 

584 if not isinstance(options.grad_scale, float): 

585 raise ValueError(f"grad_scale must be float but got {options.grad_scale}.") 

586 _validate_hsdp_reduce_dtype(options.reduce_dtype) 

587 if not isinstance(options.comm_async, bool): 

588 raise ValueError(f"comm_async must be bool but got {options.comm_async}.") 

589 if not isinstance(options.comm_fusion, bool): 

590 raise ValueError(f"comm_fusion must be bool but got {options.comm_fusion}.") 

591 if not isinstance(options.bucket_size, int) or ( 

592 options.bucket_size < 0 and options.bucket_size != -1 

593 ): 

594 raise ValueError( 

595 f"bucket_size must be a positive integer or 0, but got {options.bucket_size}." 

596 ) 

597 

598 

599def _get_device_from_mesh(mesh: DeviceMesh): 

600 """Extract and validate the torch device from the device mesh.""" 

601 device = None 

602 device_type = mesh.device_type 

603 if device_type not in ("npu", "cuda"): 

604 raise AssertionError( 

605 f"hyper_parallel.fully_shard support device in [torch.npu, torch.cuda], " 

606 f"but got '{device_type}'" 

607 ) 

608 device_handle = get_device_handle(device_type) 

609 if device_handle is None: 

610 raise ValueError( 

611 f"hyper_parallel.fully_shard can't find device_handle of " 

612 f"'torch.{device_type}', check the environment." 

613 ) 

614 if device_handle.is_available(): 

615 device = torch.device(device_handle.current_device()) 

616 return device 

617 

618 

619def _normalize_replicate_params( 

620 replicate_params: Optional[set[nn.Parameter]], 

621) -> set[nn.Parameter]: 

622 """ 

623 Normalize replicate_params for fully_shard 

624 Args: 

625 replicate_params (Optional[set[nn.Parameter]]): Set of parameters to exclude from sharding. 

626 Returns: 

627 set[nn.Parameter]: Set of parameters to exclude from sharding. 

628 """ 

629 if replicate_params is None: 

630 return set() 

631 out = set(replicate_params) 

632 for p in out: 

633 if not isinstance(p, (nn.Parameter, DTensor)): 

634 raise TypeError( 

635 "replicate_params must contain only nn.Parameter or DTensor, " 

636 f"got {type(p).__name__}." 

637 ) 

638 return out 

639 

640 

641def _get_modules_parameters(modules, ignored_params=None): 

642 """Collect deduplicated parameters from module roots.""" 

643 return get_managed_modules_parameters(modules, ignored_params) 

644 

645 

646def _validate_managed_params_source_shard_infos( 

647 managed_parameters: set[nn.Parameter], 

648 source_shard_infos: Optional[Mapping[nn.Parameter, SourceShardMetaInfo]], 

649) -> None: 

650 """Validate the parameter-identity metadata consumed by one fully_shard unit.""" 

651 if source_shard_infos is None: 

652 return 

653 if not isinstance(source_shard_infos, Mapping): 

654 raise ValueError("source_shard_infos must be a mapping from Parameter to SourceShardMetaInfo") 

655 

656 managed_parameters = set(managed_parameters) 

657 

658 if any(isinstance(parameter, DTensor) for parameter in managed_parameters): 

659 raise ValueError( 

660 "source_shard_infos cannot be provided when fully_shard manages a native DTensor parameter" 

661 ) 

662 

663 invalid_values = [ 

664 parameter 

665 for parameter, metadata in source_shard_infos.items() 

666 if not isinstance(metadata, SourceShardMetaInfo) 

667 ] 

668 if invalid_values: 

669 raise ValueError("source_shard_infos values must be SourceShardMetaInfo instances") 

670 

671 invalid_origins = [ 

672 parameter 

673 for parameter, metadata in source_shard_infos.items() 

674 if metadata.origin_is_dtensor and not isinstance(parameter, DTensor) 

675 ] 

676 if invalid_origins: 

677 raise ValueError( 

678 "source_shard_infos origin_is_dtensor=True requires a native DTensor parameter" 

679 ) 

680 

681 missing_parameters = managed_parameters.difference(source_shard_infos) 

682 if missing_parameters: 

683 raise ValueError( 

684 "source_shard_infos must cover every parameter managed by this fully_shard call" 

685 ) 

686 unexpected_parameters = set(source_shard_infos).difference(managed_parameters) 

687 if unexpected_parameters: 

688 raise ValueError( 

689 "source_shard_infos contains a parameter not managed by this fully_shard call" 

690 ) 

691 

692 

693def fully_shard( 

694 module: Union[nn.Module, List[nn.Module]], 

695 *, 

696 mesh: Optional[DeviceMesh] = None, 

697 reshard_after_forward: bool = True, 

698 shard_placement_fn: None = None, 

699 mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(), 

700 offload_policy: OffloadPolicy = OffloadPolicy(), 

701 ignored_params: Optional[set[nn.Parameter]] = None, 

702 replicate_params: Optional[set[nn.Parameter]] = None, 

703 comm_fusion: bool = False, 

704 comm_fusion_zero_copy: Optional[bool] = None, 

705 source_shard_infos: Optional[Mapping[nn.Parameter, SourceShardMetaInfo]] = None, 

706) -> Union[nn.Module, List[nn.Module]]: 

707 

708 """ 

709 Apply fully_shard to a module (or list of modules) for distributed training with parameter sharding. 

710 

711 This interface provides PyTorch-compatible HSDP (Hybrid Sharded Data Parallelism) 

712 functionality, enabling efficient training of large models by sharding parameters 

713 across multiple devices. The module is automatically enhanced with distributed 

714 capabilities including parameter sharding, gradient synchronization, and memory 

715 management. 

716 

717 When a list of modules is passed, they are treated as one FSDP unit (parameters 

718 grouped together). 

719 

720 Parameters: 

721 module (nn.Module or List[nn.Module]): 

722 The module(s) to apply fully_shard to. Modified in-place. When a list 

723 is passed, parameters from all modules are grouped as one FSDP unit. 

724 

725 mesh (Optional[DeviceMesh], default=None): 

726 The device mesh defining the process topology for distributed training. 

727 If None, fully_shard creates a default 1D mesh for local parameters. 

728 Native DTensor parameters require an explicit DP submesh. 

729 

730 reshard_after_forward (bool, default=True): 

731 Whether to automatically reshard parameters after forward. When True, 

732 parameters are resharded immediately after they are no longer needed, 

733 freeing memory for subsequent operations. Set to False if you want to 

734 keep parameters unsharded for backward pass or manual control. 

735 

736 shard_placement_fn (Callable, default=None): 

737 A callable that determines how to shard each parameter. The function 

738 should accept a parameter and return a Shard object specifying the 

739 sharding dimension, or None to use default sharding (dimension 0) 

740 

741 mp_policy (MixedPrecisionPolicy, default=MixedPrecisionPolicy()): 

742 Mixed precision training policy controlling data type conversions. 

743 

744 offload_policy (OffloadPolicy, default=OffloadPolicy()): 

745 Memory offload policy for reducing device memory usage. 

746 

747 ignored_params (Optional[set[nn.Parameter]], default=None): 

748 Set of parameters to exclude from fully_shard management entirely. 

749 These parameters are left on the original module as regular parameters, 

750 are not sharded, and do not participate in fully_shard gradient 

751 synchronization. Use this for parameters that should remain outside 

752 the fully_shard lifecycle. 

753 

754 replicate_params (Optional[set[nn.Parameter]], default=None): 

755 Set of parameters to keep replicated while still managing them under 

756 fully_shard. These parameters are not sharded, but their gradients 

757 are still synchronized with DDP-style all-reduce over the current 

758 fully_shard communication domain. This differs from ``ignored_params``, 

759 which skips fully_shard management and gradient synchronization 

760 entirely for the selected parameters. 

761 

762 comm_fusion (bool, default=False): 

763 Whether enable all_gather fusion and reduce_scatter fusion. 

764 

765 comm_fusion_zero_copy (Optional[bool], default=None): 

766 Whether allow the experimental zero-copy path for 

767 ``comm_fusion``. When set to ``None``, fully_shard enables it 

768 automatically whenever ``comm_fusion=True``. 

769 When enabled, fully_shard may rebase sharded local parameter storage 

770 into one shared flat buffer so fused all-gather can read directly from 

771 contiguous memory. This path depends on optimizer compatibility with 

772 view-backed parameters. 

773 source_shard_infos (Optional[Mapping[nn.Parameter, SourceShardMetaInfo]]): 

774 Source TP/EP mesh and placements for the plain-parameter dual mode. 

775 

776 Returns: 

777 nn.Module or List[nn.Module]: The input module(s) with HSDP capabilities added. 

778 """ 

779 _validate_module_for_fully_shard(module) 

780 

781 arg_module = module 

782 if isinstance(module, list): 

783 modules = tuple(_get_root_modules(module)) 

784 else: 

785 modules = (module,) 

786 

787 for mod in modules: 

788 _extend_module_with_hsdp_interface(mod) 

789 

790 params = _get_modules_parameters(modules, ignored_params) 

791 has_dtensor_param = any(isinstance(param, DTensor) for param in params) 

792 _validate_managed_params_source_shard_infos(set(params), source_shard_infos) 

793 

794 replicate_params = _normalize_replicate_params(replicate_params) 

795 

796 if mesh is None: 

797 mesh = init_device_mesh(device_type="npu", mesh_shape=(dist.get_world_size(),)) 

798 if has_dtensor_param: 

799 raise ValueError( 

800 "fully_shard does not support mesh=None with a native DTensor parameter; " 

801 "pass an explicit DP submesh instead." 

802 ) 

803 device = _get_device_from_mesh(mesh) 

804 

805 init_modules = modules 

806 modules[0].hsdp_init( 

807 init_modules, 

808 mesh, 

809 reshard_after_forward, 

810 shard_placement_fn, 

811 mp_policy, 

812 offload_policy, 

813 ignored_params, 

814 replicate_params, 

815 device, 

816 comm_fusion, 

817 comm_fusion_zero_copy, 

818 source_shard_infos=source_shard_infos, 

819 ) 

820 # Share the same scheduler handle with other roots so mods[i].unshard()/prefetch work 

821 if len(modules) > 1: 

822 for mod in modules[1:]: 

823 mod.hsdp_scheduler = modules[0].hsdp_scheduler 

824 return arg_module 

825 

826 

827def get_model_state_dict(model: Any, *, options: Any = None) -> dict[str, Any]: 

828 """Get the model state dict of a fully_shard-managed model. 

829 

830 Args: 

831 model: The model whose state dict to retrieve. 

832 options: Optional :class:`StateDictOptions` controlling gathering 

833 (``full_state_dict``), offloading (``cpu_offload``) and frozen 

834 parameter filtering (``ignore_frozen_params``). 

835 

836 Returns: 

837 The model state dict. By default values are sharded DTensors; when 

838 ``full_state_dict=True`` values are full Tensors (CPU on rank 0 only 

839 when ``cpu_offload=True``). 

840 """ 

841 return get_model_state_dict_impl(model, options=options) 

842 

843 

844def set_model_state_dict(model: Any, model_state_dict: dict[str, Any], *, options: Any = None) -> None: 

845 """Load ``model_state_dict`` into a fully_shard-managed model. 

846 

847 Full tensors are scattered into DTensor shards matching the model's layout 

848 before the in-place load. 

849 

850 Args: 

851 model: The model to load state into. 

852 model_state_dict: State dict to load. Values may be plain (global) 

853 tensors when ``full_state_dict=True`` or sharded DTensors otherwise. 

854 options: Optional :class:`StateDictOptions` controlling scattering 

855 (``full_state_dict``), device placement (``cpu_offload``) and 

856 strictness (``strict``). 

857 

858 Returns: 

859 None. 

860 """ 

861 return set_model_state_dict_impl(model, model_state_dict, options=options) 

862 

863 

864def hsdp_sync_stream(): 

865 """Wait for hsdp gradient handle to be completed.""" 

866 wait_grad_handle()