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

597 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# Adapted from https://github.com/pytorch/pytorch/blob/release/2.6/torch/distributed/fsdp/_fully_shard/_fsdp_param.py 

16# enhanced with fully_shard parameter management 

17# ============================================================================ 

18"""HSDP parameter""" 

19# pylint: disable=W0212 

20from dataclasses import dataclass 

21from typing import Callable, List, Optional, cast 

22 

23import torch 

24import torch.distributed as dist 

25from torch import nn 

26from torch._prims_common import make_contiguous_strides_for 

27 

28from hyper_parallel.core.dtensor.device_mesh import DeviceMesh 

29from hyper_parallel.core.dtensor.dtensor import DTensor 

30from hyper_parallel.core.dtensor.layout import Layout 

31from hyper_parallel.core.dtensor.placement_types import Replicate, Shard, StridedShard 

32from hyper_parallel.core.fully_shard.hsdp_utils import ( 

33 ParamModuleInfo, 

34 ShardedState, 

35 apply_gradient_scaling_factor, 

36) 

37from hyper_parallel.core.fully_shard.utils import ( 

38 CPUOffloadPolicy, 

39 DataParallelMeshInfo, 

40 DDPMeshInfo, 

41 FSDPMeshInfo, 

42 HSDPMeshInfo, 

43 MixedPrecisionPolicy, 

44 OffloadPolicy, 

45 SourceShardMetaInfo, 

46 resolve_param_dtypes, 

47) 

48 

49 

50def _copy_without_bumping_version(dst: torch.Tensor, src: torch.Tensor) -> None: 

51 """Copy into ``dst`` while preserving its autograd version counter.""" 

52 # pylint: disable=W0212 

53 with torch.autograd._unsafe_preserve_version_counter(dst): 

54 dst.copy_(src) 

55 

56 

57def _same_storage_location(left: torch.Tensor, right: torch.Tensor) -> bool: 

58 """Return whether two tensors start at the same storage location. 

59 

60 Args: 

61 left: First tensor to compare. 

62 right: Second tensor to compare. 

63 

64 Returns: 

65 Whether both tensors address the same storage bytes. 

66 """ 

67 if hasattr(left, "fake_mode") or hasattr(right, "fake_mode"): 

68 # Dry-run path: FakeTensors share no address, so compare storage objects. 

69 return left.untyped_storage() is right.untyped_storage() 

70 # Real path: the address includes the storage offset, so views at different 

71 # offsets within one storage are told apart. 

72 return left.data_ptr() == right.data_ptr() 

73 

74 

75@dataclass 

76class ReduceScatterCommCtx: 

77 """Per-parameter reduce-scatter output and asynchronous work.""" 

78 

79 reduce_scatter_output: Optional[torch.Tensor] = None 

80 reduce_scatter_handle: Optional[dist.Work] = None 

81 

82 

83@dataclass 

84class AllReduceCommCtx: 

85 """Per-parameter all-reduce output and asynchronous work.""" 

86 

87 all_reduce_output: Optional[torch.Tensor] = None 

88 all_reduce_handle: Optional[dist.Work] = None 

89 

90 

91@dataclass 

92class AllGatherCommCtx: 

93 """Per-parameter all-gather output and asynchronous work.""" 

94 

95 allgather_output: Optional[torch.Tensor] = None 

96 allgather_handle: Optional[dist.Work] = None 

97 

98 

99class ParameterHookMigrator: 

100 """Preserve parameter backward hooks across HSDP parameter replacement.""" 

101 

102 def __init__(self) -> None: 

103 self._orig_param_hooks: List[Callable] = [] 

104 self._saved_hook_ids: set[int] = set() 

105 

106 def _save_backward_hooks(self, param: nn.Parameter) -> None: 

107 """Save backward hooks from a parameter, deduplicated by hook identity.""" 

108 if not hasattr(param, "_backward_hooks") or param._backward_hooks is None: 

109 return 

110 

111 for _, hook_func in param._backward_hooks.items(): 

112 hook_func_id = id(hook_func) 

113 if hook_func_id not in self._saved_hook_ids: 

114 self._orig_param_hooks.append(hook_func) 

115 self._saved_hook_ids.add(hook_func_id) 

116 

117 def _migrate_backward_hooks(self, new_param: nn.Parameter) -> None: 

118 """Register saved backward hooks on a replacement parameter once.""" 

119 if not self._orig_param_hooks or hasattr(new_param, "migrate_backward_hooks_run_once"): 

120 return 

121 

122 for hook_func in self._orig_param_hooks: 

123 try: 

124 if new_param.requires_grad: 

125 new_param.register_hook(hook_func) 

126 except RuntimeError: 

127 # Skip hook registration if the parameter does not require gradients. 

128 pass 

129 new_param.migrate_backward_hooks_run_once = True 

130 

131 

132class HSDPParamV2: 

133 """ 

134 HSDP parameter. 

135 """ 

136 

137 def __repr__(self) -> str: 

138 """Stable debug name used in log lines. 

139 

140 Prefers the parameter FQN (assigned by the root forward pre-hook); before 

141 that, falls back to the owning module class plus param name and object id. 

142 Logging's ``%s`` calls this lazily -- only when a record is emitted. 

143 """ 

144 fqn = getattr(self, "_param_fqn", None) 

145 if fqn: 

146 return str(fqn) 

147 module_info = getattr(self, "_module_info", None) 

148 if module_info is not None: 

149 return f"{module_info.module.__class__.__name__}.{module_info.param_name}@{id(self):x}" 

150 return f"{self.__class__.__name__}@{id(self):x}" 

151 

152 def __init__( 

153 self, 

154 param: nn.Parameter, 

155 module_info: ParamModuleInfo, 

156 mesh_info: DataParallelMeshInfo, 

157 shard_placement_fn: Optional[Callable[[nn.Parameter], Optional[Shard]]] = None, 

158 mp_policy: MixedPrecisionPolicy = MixedPrecisionPolicy(), 

159 offload_policy: Optional[OffloadPolicy] = None, 

160 device: Optional[torch.device] = None, 

161 source_shard_info: Optional[SourceShardMetaInfo] = None, 

162 ) -> None: 

163 """ 

164 Initialize HSDPParamV2 and shard the parameter. 

165 

166 Args: 

167 param (nn.Parameter): The original full parameter to shard. 

168 module_info (ParamModuleInfo): Ownership and shared-weight metadata. 

169 mesh_info (DataParallelMeshInfo): Mesh topology for shard/replicate dimensions. 

170 shard_placement_fn (Callable, optional): Returns a Shard placement for the parameter, 

171 or None to use default (Shard(0)). 

172 mp_policy (MixedPrecisionPolicy, optional): Mixed precision dtype policy. 

173 offload_policy (OffloadPolicy, optional): CPU offload policy. 

174 device (torch.device, optional): Target device for the sharded parameter. 

175 source_shard_info (SourceShardMetaInfo, optional): Source TP/EP layout metadata, built by 

176 the owning ``HSDPStateV2``. Must be supplied (with ``origin_is_dtensor=True``) 

177 whenever ``param`` is a native DTensor, and omitted otherwise. 

178 

179 Raises: 

180 ValueError: If ``source_shard_info.origin_is_dtensor`` disagrees with whether 

181 ``param`` is a native DTensor. 

182 """ 

183 self._module_info: ParamModuleInfo = module_info 

184 self.mesh_info = mesh_info 

185 self._src_parameter_id = id(param) 

186 self.device = device 

187 self.orig_dtype = None 

188 self.param_dtype = None 

189 self.reduce_dtype = None 

190 self.apply_grad_on_fp32_main_grad = mp_policy.apply_grad_on_fp32_main_grad 

191 self.offload_to_cpu: bool = isinstance(offload_policy, CPUOffloadPolicy) 

192 self.pin_memory = ( 

193 self.offload_to_cpu and cast(CPUOffloadPolicy, offload_policy).pin_memory 

194 ) 

195 self._parameter_hook_migrator = ParameterHookMigrator() 

196 # ``source_shard_info`` is built and validated by the owning state 

197 # (``_build_param_source_shard_info``): for a native DTensor parameter it always 

198 # describes that parameter's own mesh/placements. Only the agreement 

199 # between the two is re-checked here, because it is the invariant the 

200 # sharding math below depends on. 

201 if isinstance(param, DTensor) != ( 

202 source_shard_info is not None and source_shard_info.origin_is_dtensor 

203 ): 

204 raise ValueError( 

205 "source_shard_info.origin_is_dtensor must be True exactly for native DTensor parameters, " 

206 f"got parameter type {type(param).__name__} and source_shard_info={source_shard_info}" 

207 ) 

208 self.source_shard_info = source_shard_info 

209 self._orig_param_is_dtensor = ( 

210 source_shard_info is not None and source_shard_info.origin_is_dtensor 

211 ) 

212 self._orig_dtensor_mesh = source_shard_info.mesh if self._orig_param_is_dtensor else None 

213 self._orig_dtensor_placements = ( 

214 tuple(source_shard_info.placements) if self._orig_param_is_dtensor else None 

215 ) 

216 self._storage_source_layout = self._build_storage_source_layout() 

217 self._spmd_shard_mesh_dim = self.mesh_info.shard_mesh_dim 

218 self._spmd_replicate_mesh_dim = self.mesh_info.replicate_mesh_dim 

219 self._init_sharded_param(param, shard_placement_fn) 

220 self.unsharded_accumulated_grad = None 

221 self._param_fqn: Optional[str] = None 

222 self.unsharded_param_buffers: List[torch.Tensor] = [] 

223 self.allgather_comm_ctx = AllGatherCommCtx() 

224 self._post_load_hook_handle = ( 

225 module_info.module.register_load_state_dict_post_hook( 

226 lambda *args, **kwargs: self.reset_sharded_param() 

227 ) 

228 ) 

229 self.reduce_scatter_comm_ctx = ReduceScatterCommCtx() 

230 self.all_reduce_comm_ctx = AllReduceCommCtx() 

231 self._parameter_hook_migrator._save_backward_hooks(param) 

232 self._grad = None 

233 # Keep reduce-scatter accumulation in reduce_dtype until the final 

234 # micro-step performs the optional replicate all-reduce. 

235 self._reduce_partial_output = None 

236 self.gradient_scaling_factor = None 

237 

238 def _get_base_spmd_placements(self) -> tuple: 

239 if self.source_shard_info is not None: 

240 # Preserve the source distributed layout and prefix the explicit 

241 # DP/FSDP mesh dimensions on the unified mesh. 

242 source_mesh, source_placements = self._storage_source_layout 

243 self._spmd_mesh = DeviceMesh.concatenate([self.mesh_info.mesh, source_mesh]) 

244 dp_prefix_placements = tuple(Replicate() for _ in range(self.mesh_info.mesh.ndim)) 

245 return dp_prefix_placements + source_placements 

246 

247 self._spmd_mesh = self.mesh_info.mesh 

248 return tuple(Replicate() for _ in range(self._spmd_mesh.ndim)) 

249 

250 def _build_storage_source_layout(self) -> tuple[Optional[DeviceMesh], tuple]: 

251 """Build the immutable source layout used by FSDP storage and reduction. 

252 

253 Native DTensor parameters may already describe data-parallel axes that 

254 are also covered by ``mesh_info.mesh``. Exclude those axes from the 

255 concatenated storage mesh without changing ``source_shard_info``, whose 

256 mesh and placements always retain the original compute-layout meaning. 

257 Explicit metadata for plain production-mode parameters already contains 

258 only its TP/EP source layout and must remain unchanged. 

259 

260 Ownership is derived from rank topology rather than dimension names: 

261 a source axis is redundant exactly when varying it at this rank's own 

262 coordinate never leaves the FSDP domain's rank set. Name matching 

263 cannot express this because trainer meshes rename flattened data 

264 axes (e.g. ``dp``/``cp`` become ``fsdp_replicate``/``fsdp_shard``). 

265 

266 Returns: 

267 Source mesh and placements to append to the FSDP mesh, or an empty 

268 layout when this parameter has no source-layout metadata. 

269 """ 

270 if self.source_shard_info is None: 

271 return None, () 

272 source_mesh = self.source_shard_info.mesh 

273 source_placements = tuple(self.source_shard_info.placements) 

274 if not self.source_shard_info.origin_is_dtensor: 

275 return source_mesh, source_placements 

276 

277 source_mesh_dim_names = source_mesh.mesh_dim_names or () 

278 fsdp_ranks = self._fsdp_domain_ranks() 

279 coordinate = source_mesh.get_coordinate() if fsdp_ranks is not None else None 

280 if coordinate is None: 

281 # Rank topology is unavailable (e.g. a topology-only mesh), so no 

282 # axis can be proven redundant. Keep the full layout, matching the 

283 # pre-dedup behavior. 

284 return source_mesh, source_placements 

285 

286 storage_dim_names = [] 

287 for dim_index, dim_name in enumerate(source_mesh_dim_names): 

288 if not self._source_dim_covered_by_fsdp( 

289 source_mesh, dim_index, coordinate, fsdp_ranks 

290 ): 

291 storage_dim_names.append(dim_name) 

292 storage_dim_names = tuple(storage_dim_names) 

293 if not storage_dim_names or storage_dim_names == source_mesh_dim_names: 

294 return source_mesh, source_placements 

295 

296 placement_by_dim = dict(zip(source_mesh_dim_names, source_placements)) 

297 return ( 

298 source_mesh[storage_dim_names], 

299 tuple(placement_by_dim[dim_name] for dim_name in storage_dim_names), 

300 ) 

301 

302 def _fsdp_domain_ranks(self) -> Optional[frozenset]: 

303 """Ranks owned by this FSDP unit's data-parallel domain. 

304 

305 Returns ``None`` when the mesh carries no usable rank topology, in 

306 which case no source axis can be proven redundant. 

307 """ 

308 mesh = getattr(self.mesh_info, "mesh", None) 

309 mesh_tensor = getattr(mesh, "mesh", None) 

310 if not isinstance(mesh_tensor, torch.Tensor): 

311 return None 

312 return frozenset(int(rank) for rank in mesh_tensor.flatten().tolist()) 

313 

314 @staticmethod 

315 def _source_dim_covered_by_fsdp(source_mesh, dim_index, coordinate, fsdp_ranks) -> bool: 

316 """Whether varying one source dim stays inside the FSDP rank domain. 

317 

318 The fiber is taken at this rank's own coordinate: peer ranks reached 

319 by varying a data-parallel axis share this rank's other coordinates 

320 (e.g. its TP slot), which is exactly the population FSDP reduces over. 

321 """ 

322 index = list(coordinate) 

323 mesh_tensor = source_mesh.mesh 

324 for extent in range(source_mesh.size(dim_index)): 

325 index[dim_index] = extent 

326 if int(mesh_tensor[tuple(index)]) not in fsdp_ranks: 

327 return False 

328 return True 

329 

330 def _apply_data_parallel_placements(self, placements: list, shard_placement: Shard) -> tuple: 

331 if len(placements) != self._spmd_mesh.ndim: 

332 raise AssertionError( 

333 f"Expected {self._spmd_mesh.ndim} unified placements, got {len(placements)}: {placements}" 

334 ) 

335 if ( 

336 isinstance(self.mesh_info, DDPMeshInfo) 

337 and self._spmd_replicate_mesh_dim is not None 

338 and not self._orig_param_is_dtensor 

339 ): 

340 placements[self._spmd_replicate_mesh_dim] = Replicate() 

341 if ( 

342 isinstance(self.mesh_info, FSDPMeshInfo) 

343 and self._spmd_shard_mesh_dim is not None 

344 ): 

345 # If TP/EP already shards the same tensor dimension, fully_shard must 

346 # use StridedShard so the unified placement preserves the intended 

347 # shard order on the concatenated mesh. 

348 split_factor = 1 

349 for mesh_idx, placement in enumerate(placements): 

350 if mesh_idx == self._spmd_shard_mesh_dim: 

351 continue 

352 if placement.is_shard(shard_placement.dim): 

353 split_factor *= self._spmd_mesh.mesh_shape[mesh_idx] 

354 placements[self._spmd_shard_mesh_dim] = ( 

355 StridedShard(shard_placement.dim, split_factor=split_factor) 

356 if split_factor > 1 

357 else shard_placement 

358 ) 

359 return tuple(placements) 

360 

361 def _build_sharding_spec( 

362 self, 

363 source_param: nn.Parameter, 

364 source_local_tensor: torch.Tensor, 

365 ) -> Layout: 

366 """Build the final layout after data and model parallel sharding. 

367 

368 A dual-mode parameter is a plain tensor containing only its TP/EP-local 

369 shard, so its local shape cannot represent the final logical shape. 

370 Source distribution metadata restores that shape before the FSDP 

371 placements are applied. This method only constructs the layout and has 

372 no parameter lifecycle side effects. 

373 

374 Args: 

375 source_param: Parameter received before FSDP partitioning. 

376 source_local_tensor: Local tensor partitioned by FSDP. 

377 

378 Returns: 

379 Layout containing all FSDP, TP, and EP placements. 

380 """ 

381 logical_global_stride = None 

382 if isinstance(source_param, DTensor): 

383 logical_global_size = source_param.size() 

384 logical_global_stride = source_param.layout.tensor_stride 

385 elif self.source_shard_info is not None: 

386 source_sharding_spec = Layout.from_device_mesh(self.source_shard_info.mesh) 

387 source_sharding_spec.set_placements(self.source_shard_info.placements) 

388 source_sharding_spec.placement_to_tensor_map(source_local_tensor.ndim) 

389 logical_global_size = source_sharding_spec.get_global_shape( 

390 source_local_tensor.size() 

391 ) 

392 else: 

393 logical_global_size = source_local_tensor.size() 

394 

395 if logical_global_stride is None: 

396 logical_global_stride = make_contiguous_strides_for(logical_global_size) 

397 

398 sharding_spec = Layout.from_device_mesh(self._spmd_mesh) 

399 sharding_spec.set_placements(self._spmd_placements) 

400 sharding_spec.placement_to_tensor_map(source_local_tensor.ndim) 

401 sharding_spec.set_tensor_meta( 

402 logical_global_size, 

403 logical_global_stride, 

404 source_local_tensor.dtype, 

405 ) 

406 return sharding_spec 

407 

408 @property 

409 def reduce_partial_output(self) -> Optional[torch.Tensor]: 

410 """Return reduce-scatter results accumulated before the final micro-step.""" 

411 return self._reduce_partial_output 

412 

413 @reduce_partial_output.setter 

414 def reduce_partial_output(self, value: Optional[torch.Tensor]) -> None: 

415 self._reduce_partial_output = value 

416 

417 def reduce_comm_dtype(self, grad: Optional[torch.Tensor] = None) -> torch.dtype: 

418 """Resolve the communication dtype owned by this parameter. 

419 

420 Args: 

421 grad: Optional gradient used when no mixed-precision reduction dtype 

422 is configured. 

423 

424 Returns: 

425 The dtype used by reduce-scatter and all-reduce buffers. 

426 """ 

427 if self.reduce_dtype is not None: 

428 return self.reduce_dtype 

429 if grad is not None: 

430 return grad.dtype 

431 if self.unsharded_accumulated_grad is not None: 

432 return self.unsharded_accumulated_grad_data.dtype 

433 if self.unsharded_param.grad is not None: 

434 return self.unsharded_grad_data.dtype 

435 return self.param_dtype or self.orig_dtype 

436 

437 def wait_reduce_scatter(self) -> None: 

438 """Wait before reading the result or releasing the transferred input. 

439 

440 The current gradient slots belong to a later backward and must remain 

441 untouched. Results stay in ``reduce_scatter_comm_ctx`` until consumed. 

442 """ 

443 if self.reduce_scatter_comm_ctx.reduce_scatter_handle is not None: 

444 self.reduce_scatter_comm_ctx.reduce_scatter_handle.wait() 

445 self._grad.untyped_storage().resize_(0) 

446 self._grad = None 

447 self.reduce_scatter_comm_ctx.reduce_scatter_handle = None 

448 

449 def reduce_scatter_output(self) -> Optional[torch.Tensor]: 

450 """Return the sharded gradient after waiting for its reduction.""" 

451 self.wait_reduce_scatter() 

452 return self.reduce_scatter_comm_ctx.reduce_scatter_output 

453 

454 def clear_reduce_scatter_output(self) -> None: 

455 """Clear the reduce-scatter output tensor to free memory.""" 

456 self.wait_reduce_scatter() 

457 self.reduce_scatter_comm_ctx.reduce_scatter_output = None 

458 self._grad = None 

459 

460 def all_reduce_output(self) -> Optional[torch.Tensor]: 

461 """ 

462 Get the all-reduce output tensor and wait for asynchronous operation to complete. 

463 

464 Returns: 

465 torch.Tensor: The reduced gradient tensor after all-reduce operation. 

466 """ 

467 if self.all_reduce_comm_ctx.all_reduce_handle is not None: 

468 self.all_reduce_comm_ctx.all_reduce_handle.wait() 

469 self.all_reduce_comm_ctx.all_reduce_handle = None 

470 return self.all_reduce_comm_ctx.all_reduce_output 

471 

472 def clear_all_reduce_output(self) -> None: 

473 """Clear the all-reduce output tensor to free memory.""" 

474 self.all_reduce_comm_ctx.all_reduce_output = None 

475 

476 def clear_unsharded_source_grad(self) -> None: 

477 """Clear the live unsharded gradient or its accumulated buffer.""" 

478 if self.unsharded_accumulated_grad_data is not None: 

479 self.unsharded_accumulated_grad = None 

480 elif self.unsharded_param.grad is not None: 

481 self.unsharded_param.grad = None 

482 

483 def apply_reduced_grad(self, reduced_grad: torch.Tensor) -> bool: 

484 """ 

485 Apply reduced gradient to the sharded parameter. 

486 

487 Reshapes ``reduced_grad`` to match the local shard, optionally 

488 offloads to CPU, then accumulates or assigns onto 

489 ``hsdp_param.sharded_param.grad``. 

490 

491 Args: 

492 reduced_grad (torch.Tensor): Gradient after reduce-scatter 

493 and/or all-reduce. 

494 

495 Returns: 

496 Whether the current stream must synchronize for CPU offload. 

497 """ 

498 sharded_grad = None 

499 if not self.apply_grad_on_fp32_main_grad: 

500 sharded_grad = self.sharded_param.grad 

501 else: 

502 if not hasattr(self.sharded_param, "main_grad"): 

503 self.sharded_param.main_grad = None 

504 sharded_grad = self.sharded_param.main_grad 

505 reduced_grad = ( 

506 reduced_grad.reshape(-1) 

507 .narrow(0, 0, self.sharded_size.numel()) 

508 .view(self.sharded_size) 

509 ) 

510 if ( 

511 not self.apply_grad_on_fp32_main_grad 

512 and reduced_grad.dtype != self.orig_dtype 

513 ): 

514 reduced_grad = reduced_grad.to(self.orig_dtype) 

515 to_accumulate_grad = sharded_grad is not None 

516 need_synchronize = False 

517 if self.offload_to_cpu: 

518 non_blocking = self.pin_memory and not to_accumulate_grad 

519 reduced_grad = reduced_grad.to( 

520 torch.device("cpu"), non_blocking=non_blocking 

521 ) 

522 need_synchronize = True 

523 if sharded_grad is None: 

524 if not self.apply_grad_on_fp32_main_grad: 

525 self.sharded_param.grad = self.to_sharded_dtensor(reduced_grad) 

526 else: 

527 self.sharded_param.main_grad = self.to_sharded_dtensor(reduced_grad) 

528 self.sharded_param.grad = None 

529 else: 

530 if not self.apply_grad_on_fp32_main_grad: 

531 self.sharded_param.grad._local_tensor += reduced_grad 

532 else: 

533 self.sharded_param.main_grad._local_tensor += reduced_grad 

534 self.sharded_param.grad = None 

535 return need_synchronize 

536 

537 def _resolve_hsdp_placement( 

538 self, 

539 param: nn.Parameter, 

540 shard_placement_fn: Optional[Callable], 

541 ) -> Shard: 

542 """Validate and normalize the fully_shard placement for one parameter.""" 

543 if param.device != self.device and param.device.type != "meta": 

544 raise AssertionError( 

545 f"Expects the parameter to already be moved to device {self.device} but got {param.device}" 

546 ) 

547 

548 hsdp_placement = shard_placement_fn(param) if shard_placement_fn else None 

549 if hsdp_placement is None: 

550 hsdp_placement = Shard(0) 

551 elif hsdp_placement.dim < 0: 

552 # if dim is negative, add the number of dimensions of the parameter 

553 hsdp_placement = Shard(hsdp_placement.dim + param.ndim) 

554 

555 if not isinstance(hsdp_placement, Shard): 

556 raise AssertionError( 

557 f"Expected Shard, got {type(hsdp_placement)}: {hsdp_placement}" 

558 ) 

559 return hsdp_placement 

560 

561 def _init_shard_placements( 

562 self, 

563 param_data: torch.Tensor, 

564 shard_dim: int, 

565 base_placements: list, 

566 ) -> None: 

567 """Build data-parallel placements for the local shard.""" 

568 if shard_dim != 0 and param_data.size(shard_dim) % self.shard_world_size != 0: 

569 raise NotImplementedError( 

570 f"fully_shard only supports uneven sharding on dim=0, but parameter " 

571 f"{self._module_info.param_name} has shape {tuple(param_data.shape)}, " 

572 f"shard dim {shard_dim}, and world size {self.shard_world_size}" 

573 ) 

574 spmd_placements = list( 

575 self._apply_data_parallel_placements( 

576 base_placements, 

577 self.hsdp_placement, 

578 ) 

579 ) 

580 if param_data.size(shard_dim) % self.shard_world_size != 0: 

581 if self._spmd_shard_mesh_dim is None: 

582 raise AssertionError("Uneven FSDP sharding requires a shard mesh dimension") 

583 fsdp_placement = spmd_placements[self._spmd_shard_mesh_dim] 

584 if isinstance(fsdp_placement, StridedShard): 

585 fsdp_placement = StridedShard( 

586 fsdp_placement.dim, 

587 fsdp_placement.split_factor, 

588 uneven_shard=True, 

589 ) 

590 else: 

591 fsdp_placement = Shard(fsdp_placement.dim, uneven_shard=True) 

592 spmd_placements[self._spmd_shard_mesh_dim] = fsdp_placement 

593 self._spmd_placements = tuple(spmd_placements) 

594 

595 @torch.no_grad() 

596 def _init_sharded_param( 

597 self, 

598 param: nn.Parameter, 

599 shard_placement_fn: Optional[Callable], 

600 ) -> None: 

601 """Initialize the persistent sharded parameter and communication storage.""" 

602 hsdp_placement = self._resolve_hsdp_placement(param, shard_placement_fn) 

603 self.hsdp_placement = hsdp_placement 

604 base_placements = list(self._get_base_spmd_placements()) 

605 param_data = param.to_local() if self._orig_param_is_dtensor else param 

606 shard_dim = hsdp_placement.dim 

607 if param_data.ndim == 0: 

608 raise ValueError("fully_shard does not support scalar parameters") 

609 if shard_dim < 0 or shard_dim >= param_data.ndim: 

610 raise ValueError( 

611 f"Invalid fully_shard dim {shard_dim} for parameter " 

612 f"{self._module_info.param_name} with shape {tuple(param_data.shape)}" 

613 ) 

614 self._orig_size = param_data.size() 

615 self._contiguous_orig_stride = make_contiguous_strides_for(self._orig_size) 

616 

617 if isinstance(self.mesh_info, FSDPMeshInfo): 

618 self.shard_rank = self.mesh_info.shard_mesh_rank 

619 self.shard_world_size = self.mesh_info.shard_mesh_size 

620 else: 

621 self.shard_rank = 0 

622 self.shard_world_size = 1 

623 if isinstance(self.mesh_info, DDPMeshInfo): 

624 self.replicate_world_size = self.mesh_info.replicate_mesh_size 

625 else: 

626 self.replicate_world_size = 1 

627 self.is_replicate_param = ( 

628 isinstance(self.mesh_info, DDPMeshInfo) 

629 and not isinstance(self.mesh_info, HSDPMeshInfo) 

630 ) 

631 

632 self._init_shard_placements( 

633 param_data, 

634 shard_dim, 

635 base_placements, 

636 ) 

637 

638 chunks = torch.chunk(param_data, self.shard_world_size, dim=shard_dim) 

639 if self.shard_rank < len(chunks): 

640 local_shard = chunks[self.shard_rank] 

641 else: 

642 empty_slice = [slice(None)] * param_data.ndim 

643 empty_slice[shard_dim] = slice(param_data.size(shard_dim), None) 

644 local_shard = param_data[tuple(empty_slice)] 

645 sharded_param = local_shard.clone().contiguous() 

646 self.sharded_size = sharded_param.size() 

647 self.contiguous_sharded_stride = make_contiguous_strides_for(self.sharded_size) 

648 self.padded_sharded_param_size = chunks[0].size() 

649 if self.offload_to_cpu and not sharded_param.is_meta: 

650 sharded_param = sharded_param.cpu() 

651 if self.pin_memory: 

652 sharded_param = sharded_param.pin_memory() 

653 

654 if self.sharded_size == self.padded_sharded_param_size: 

655 self._sharded_param_data = sharded_param.view(-1) 

656 else: 

657 padded_sharded_param = sharded_param.new_zeros(self.padded_sharded_param_size) 

658 if self.pin_memory and not padded_sharded_param.is_meta: 

659 padded_sharded_param = padded_sharded_param.pin_memory() 

660 if sharded_param.numel() > 0: 

661 padded_sharded_param.narrow( 

662 shard_dim, 

663 0, 

664 self.sharded_size[shard_dim], 

665 ).copy_(sharded_param) 

666 self._sharded_param_data = padded_sharded_param.view(-1) 

667 sharded_param = padded_sharded_param.narrow( 

668 shard_dim, 

669 0, 

670 self.sharded_size[shard_dim], 

671 ) 

672 

673 self._sharding_spec = self._build_sharding_spec(param, param_data) 

674 

675 self.sharded_param = nn.Parameter(self.to_sharded_dtensor(sharded_param)) 

676 self.sharded_param._layout = self._sharding_spec 

677 self.sharded_param._placements = tuple(self._sharding_spec.placements) 

678 self.sharded_param.requires_grad_(param.requires_grad) 

679 self._setattr_on_modules(self.sharded_param) 

680 # after init, self.sharded_param replaces original param, gradients must accumulate to this Parameter's grad 

681 self.sharded_param._hsdp_param_initialized = True 

682 self.sharded_state = ShardedState.SHARDED 

683 self.param_dtype = None 

684 self.reduce_dtype = None 

685 

686 def init_dtype_attrs(self, mp_policy: MixedPrecisionPolicy) -> None: 

687 """Initialize dtype attributes, applying source-parameter overrides before policy defaults.""" 

688 self.orig_dtype = self.sharded_param.dtype 

689 self.param_dtype, self.reduce_dtype = resolve_param_dtypes(mp_policy, self._src_parameter_id, self.orig_dtype) 

690 self.apply_grad_on_fp32_main_grad = mp_policy.apply_grad_on_fp32_main_grad 

691 

692 def init_unsharded_param_buffers( 

693 self, 

694 all_gather_input_numels: list[int], 

695 all_gather_input_dtypes: list[torch.dtype], 

696 world_size: int, 

697 device: torch.device, 

698 force_recreate: bool = False, 

699 ): 

700 """ 

701 Allocate buffers that hold unsharded parameter data. 

702 

703 Args: 

704 all_gather_input_numels: Number of elements per input shard. 

705 all_gather_input_dtypes: Dtype of each input shard. 

706 world_size: Number of ranks in the shard process group. 

707 device: Device on which to allocate the output buffers. 

708 force_recreate: If True, always recreate buffers even if already initialized. 

709 """ 

710 if not force_recreate and len(self.unsharded_param_buffers) > 0: 

711 return # already initialized 

712 if force_recreate and hasattr(self, "_unsharded_param"): 

713 raise RuntimeError( 

714 "Cannot recreate unsharded_param_buffers after initializing the stable " 

715 "unsharded parameter." 

716 ) 

717 self.unsharded_param_buffers = [ 

718 torch.empty(torch.Size([numel * world_size]), dtype=dtype, device=device) 

719 for numel, dtype in zip(all_gather_input_numels, all_gather_input_dtypes) 

720 ] 

721 

722 def init_unsharded_param(self) -> None: 

723 """Initialize the stable unsharded parameter from its final output storage.""" 

724 if len(self.unsharded_param_buffers) != 1: 

725 raise AssertionError( 

726 f"Expected 1 unsharded_param_buffer, got {len(self.unsharded_param_buffers)}" 

727 ) 

728 

729 if self.allgather_comm_ctx.allgather_output is not None: 

730 packed_shape = list(self.sharded_size) 

731 packed_shape[0] *= self.shard_world_size 

732 chunks = torch.chunk( 

733 self.allgather_comm_ctx.allgather_output.view(packed_shape), 

734 self.shard_world_size, 

735 dim=0, 

736 ) 

737 # pylint: disable=W0212 

738 with torch.autograd._unsafe_preserve_version_counter( 

739 self.unsharded_param_buffers[0] 

740 ): 

741 torch.cat( 

742 chunks, 

743 dim=self.hsdp_placement.dim, 

744 out=self.unsharded_param_buffers[0].view(self._orig_size), 

745 ) 

746 self.allgather_comm_ctx.allgather_output.untyped_storage().resize_(0) 

747 self.allgather_comm_ctx.allgather_output = None 

748 

749 if hasattr(self, "_unsharded_param"): 

750 # Autograd attaches gradients to the parameter object captured in forward. 

751 # Keep that Parameter and its .data binding for its lifetime. Refresh 

752 # values by writing into its existing storage at each unshard. 

753 return 

754 

755 unsharded_param = torch.as_strided( 

756 self.unsharded_param_buffers[0], 

757 size=self._orig_size, 

758 stride=self._contiguous_orig_stride, 

759 storage_offset=0, 

760 ) 

761 if self.source_shard_info is not None and self.source_shard_info.origin_is_dtensor: 

762 unsharded_param = DTensor.from_local( 

763 unsharded_param, 

764 self.source_shard_info.mesh, 

765 self.source_shard_info.placements, 

766 ) 

767 self._unsharded_param = nn.Parameter( 

768 unsharded_param, 

769 requires_grad=self.sharded_param.requires_grad, 

770 ) 

771 

772 def to_sharded(self) -> None: 

773 """Install the sharded parameter on managed modules and update state.""" 

774 self._setattr_on_modules(self.sharded_param) 

775 if self.unsharded_param_buffers[0] is not self._sharded_param_data: 

776 self.free_unsharded_param() 

777 self.sharded_state = ShardedState.SHARDED 

778 

779 def to_unsharded(self) -> None: 

780 """Install the unsharded parameter on managed modules and update state.""" 

781 set_requires_grad_if_needed(self.sharded_param, self._unsharded_param) 

782 self._setattr_on_modules(self._unsharded_param) 

783 self.sharded_state = ShardedState.UNSHARDED 

784 

785 def _setattr_on_modules(self, param: nn.Parameter) -> None: 

786 """Set parameter on module and shared modules, preserving pointer consistency.""" 

787 if getattr(self._module_info.module.__setattr__, "__func__", None) is nn.Module.__setattr__: 

788 # fast path 

789 self._module_info.module._parameters[self._module_info.param_name] = param 

790 else: 

791 # slow path 

792 setattr(self._module_info.module, self._module_info.param_name, param) 

793 self._parameter_hook_migrator._save_backward_hooks(self.sharded_param) 

794 self._parameter_hook_migrator._migrate_backward_hooks(param) 

795 # Iterate through all modules that share this parameter to prevent pointer desync. 

796 for shared_module, shared_param_name in zip( 

797 self._module_info.shared_modules, self._module_info.shared_param_names 

798 ): 

799 if getattr(shared_module.__setattr__, "__func__", None) is nn.Module.__setattr__: 

800 shared_module._parameters[shared_param_name] = param 

801 else: 

802 setattr(shared_module, shared_param_name, param) 

803 

804 def to_sharded_dtensor(self, tensor: torch.Tensor) -> DTensor: 

805 """ 

806 Converts a local tensor representing either the sharded parameter or 

807 sharded gradient to DTensor. 

808 

809 The parameter-owned sharding specification already contains the 

810 logical shape, stride, dtype, and placements. Reusing it avoids the 

811 metadata deepcopy performed by ``DTensor.from_local`` when explicit 

812 shape and stride are supplied. The returned DTensor intentionally 

813 shares this layout with the sharded parameter. 

814 """ 

815 return DTensor.from_local_with_layout( 

816 tensor, 

817 self._sharding_spec, 

818 shape=self._sharding_spec.tensor_shape, 

819 ) 

820 

821 def to_accumulated_grad_if_needed(self) -> None: 

822 """Move the current unsharded gradient into the accumulation buffer.""" 

823 if not hasattr(self, "_unsharded_param") or self._unsharded_param.grad is None: 

824 return 

825 # Keep local gradients alive across no-sync / delayed-sync steps even 

826 # after the parameter transitions back to the sharded view. 

827 unsharded_grad = self._unsharded_param.grad 

828 self._unsharded_param.grad = None 

829 if self.reduce_dtype is not None and unsharded_grad.dtype != self.reduce_dtype: 

830 unsharded_grad = unsharded_grad.to(self.reduce_dtype) 

831 if self.unsharded_accumulated_grad is None: 

832 self.unsharded_accumulated_grad = unsharded_grad 

833 else: 

834 self.unsharded_accumulated_grad += unsharded_grad 

835 

836 def accumulate_unsharded_grad_if_needed(self) -> None: 

837 """Add the current unsharded gradient to an existing accumulation buffer.""" 

838 if not hasattr(self, "_unsharded_param"): 

839 return 

840 if ( 

841 self.unsharded_accumulated_grad is not None 

842 and self.unsharded_param.grad is not None 

843 ): 

844 grad = self.unsharded_param.grad 

845 if self.reduce_dtype is not None and grad.dtype != self.reduce_dtype: 

846 grad = grad.to(self.reduce_dtype) 

847 self.unsharded_param.grad = None 

848 self.unsharded_accumulated_grad += grad 

849 

850 def alloc_unsharded_param_buffers(self) -> None: 

851 """ 

852 Restore unsharded parameter buffers to their full capacity. 

853 unsharded_param_buffer is the final storage which should be reffereced by self._unsharded_param 

854 """ 

855 for tensor in self.unsharded_param_buffers: 

856 expected_size = tensor.numel() * tensor.itemsize 

857 storage = tensor.untyped_storage() 

858 if storage.size() != expected_size: 

859 storage.resize_(expected_size) 

860 

861 def free_unsharded_param(self) -> None: 

862 """Release storage of the unsharded parameter buffers.""" 

863 for tensor in self.unsharded_param_buffers: 

864 storage = tensor.untyped_storage() 

865 if storage.size() != 0: 

866 storage.resize_(0) 

867 

868 @property 

869 def all_gather_inputs(self) -> list[torch.Tensor]: 

870 """Return the local sharded tensor to use as input for all-gather, applying dtype cast if needed.""" 

871 self._assert_in_states(ShardedState.SHARDED) 

872 sharded_param_data = self._sharded_param_data 

873 if self.offload_to_cpu: 

874 sharded_param_data = sharded_param_data.to( 

875 self.device, non_blocking=True 

876 ) 

877 if self.param_dtype is not None and self.param_dtype != sharded_param_data.dtype: 

878 return [sharded_param_data.to(self.param_dtype)] 

879 return [sharded_param_data] 

880 

881 @property 

882 def unsharded_param(self) -> nn.Parameter: 

883 """Return the full unsharded parameter after all-gather.""" 

884 return self._unsharded_param 

885 

886 @property 

887 def unsharded_grad_data(self) -> torch.Tensor: 

888 """ 

889 Get the unsharded gradient data as a local tensor. 

890 """ 

891 return self._unsharded_param.grad 

892 

893 @property 

894 def unsharded_accumulated_grad_data(self) -> torch.Tensor: 

895 """ 

896 Get the unsharded accumulated gradient data as a local tensor. 

897 """ 

898 return self.unsharded_accumulated_grad 

899 

900 def _assert_in_states(self, *states: ShardedState) -> None: 

901 """Assert current state is one of expected states.""" 

902 if self.sharded_state not in states: 

903 raise AssertionError( 

904 f"Expected sharded_state in {states}, got {self.sharded_state}" 

905 ) 

906 

907 def _resolve_reset_param(self): 

908 """Resolve the (possibly swapped) module param for ``reset_sharded_param``. 

909 

910 Refreshes ``self.sharded_param`` for the DTensor case and returns the 

911 current module parameter for the caller to re-shard. 

912 """ 

913 module_info = self._module_info 

914 new_param = getattr(module_info.module, module_info.param_name) 

915 if new_param is self.sharded_param: 

916 return new_param 

917 # Ensure object identity is preserved after parameter conversion. 

918 if torch.__future__.get_swap_module_params_on_conversion(): 

919 raise AssertionError( 

920 f"Expects swap_tensors to preserve object but got {new_param} " 

921 f"instead of {self.sharded_param}" 

922 ) 

923 if isinstance(new_param, DTensor): 

924 self.sharded_param = new_param 

925 if not getattr(self.sharded_param, "_hsdp_param_initialized", None): 

926 # reset _hsdp_param_initialized flag. 

927 self.sharded_param._hsdp_param_initialized = True 

928 # If new_param is a plain Tensor, keep the existing 'self.sharded_param' ref; 

929 # only its _local_tensor / _sharded_param_data are refreshed below. 

930 return new_param 

931 

932 def _is_same_sharded_local_tensor(self, local_tensor: torch.Tensor) -> bool: 

933 """Return whether communication storage already aliases the local tensor.""" 

934 if not isinstance(self._sharded_param_data, torch.Tensor): 

935 return False 

936 # Storage identity keeps empty shards and FakeTensors distinct. 

937 return ( 

938 self._sharded_param_data.untyped_storage() 

939 is local_tensor.untyped_storage() 

940 ) 

941 

942 def _validate_reset_local_tensor( 

943 self, 

944 local_tensor: torch.Tensor, 

945 ) -> torch.Tensor: 

946 """Validate the actual local shape after parameter conversion.""" 

947 if local_tensor.size() != self.sharded_size: 

948 raise AssertionError( 

949 f"Expected sharded_size to be {self.sharded_size}, got {local_tensor.size()}" 

950 ) 

951 return local_tensor 

952 

953 def _pin_reset_local_tensor_if_needed( 

954 self, 

955 local_tensor: torch.Tensor, 

956 ) -> tuple[torch.Tensor, bool]: 

957 """Move reset storage to pinned CPU memory when the policy requires it.""" 

958 if self.pin_memory and not local_tensor.is_pinned(): 

959 return local_tensor.cpu().pin_memory(), True 

960 return local_tensor, False 

961 

962 def _refresh_sharded_local_tensor( 

963 self, 

964 local_tensor: torch.Tensor, 

965 shard_dim: int, 

966 ) -> None: 

967 """Rebuild padded communication storage and refresh the DTensor local view.""" 

968 # A converted parameter may still reference the forward graph through 

969 # DTensor's local TensorImpl. Storage owned by HSDP must be an 

970 # off-graph leaf so this reference cannot retain the previous device 

971 # allocation after an offload or parameter conversion. 

972 local_tensor = local_tensor.detach() 

973 actual_shard_length = self.sharded_size[shard_dim] 

974 if self.sharded_size == self.padded_sharded_param_size: 

975 local_tensor = local_tensor.contiguous() 

976 self._sharded_param_data = local_tensor.view(-1) 

977 # Keep the communication view's base non-trainable while the 

978 # local shard has its own requires_grad flag and shared storage. 

979 local_view = local_tensor.detach() 

980 else: 

981 padded_local_tensor = local_tensor.new_zeros(self.padded_sharded_param_size) 

982 if self.pin_memory: 

983 padded_local_tensor = padded_local_tensor.pin_memory() 

984 if local_tensor.numel() > 0: 

985 padded_local_tensor.narrow( 

986 shard_dim, 

987 0, 

988 actual_shard_length, 

989 ).copy_(local_tensor) 

990 self._sharded_param_data = padded_local_tensor.view(-1) 

991 local_view = padded_local_tensor.narrow( 

992 shard_dim, 

993 0, 

994 actual_shard_length, 

995 ).detach() 

996 set_requires_grad_if_needed(self.sharded_param, local_view) 

997 self.sharded_param._local_tensor = local_view 

998 self._update_shardedparam_storage_forcely() 

999 if not self.sharded_param._local_tensor.is_contiguous(): 

1000 raise AssertionError( 

1001 "Expected sharded_param._local_tensor to be contiguous" 

1002 ) 

1003 

1004 def reset_sharded_param(self) -> None: 

1005 """Reset sharded param after load_state_dict. 

1006 

1007 This method may replace the DTensor local storage. It intentionally 

1008 detaches the rebuilt persistent storage from autograd because it is 

1009 not part of a forward computation. 

1010 """ 

1011 new_param = self._resolve_reset_param() 

1012 local_tensor = new_param._local_tensor if isinstance(new_param, DTensor) else new_param 

1013 if local_tensor.is_meta: 

1014 return 

1015 # local_tensor can be padded twice 

1016 # 1st time in fully_shard(model) 

1017 # 2nd time in model(input) lazy_init 

1018 # 2nd time should be no-op if parameters remain unchanged 

1019 # 2nd time shouldn't be no-op if people call model.load_state_dict(...) before lazy_init 

1020 # this makes it possible for trainer to call `sd = model.state_dict()` before the training loop 

1021 # and use `sd` without calling .state_dict() per iteration 

1022 same_local_tensor = self._is_same_sharded_local_tensor(local_tensor) 

1023 shard_dim = self.hsdp_placement.dim 

1024 if not same_local_tensor: 

1025 local_tensor = self._validate_reset_local_tensor(local_tensor) 

1026 local_tensor, pinned_local_tensor = self._pin_reset_local_tensor_if_needed(local_tensor) 

1027 if not isinstance(self.sharded_param, DTensor): 

1028 raise AssertionError(f"Expected DTensor, got {type(self.sharded_param)}") 

1029 if not same_local_tensor or pinned_local_tensor: 

1030 self._refresh_sharded_local_tensor(local_tensor, shard_dim) 

1031 self._sharding_spec.set_tensor_meta( 

1032 self._sharding_spec.tensor_shape, 

1033 self._sharding_spec.tensor_stride, 

1034 local_tensor.dtype, 

1035 ) 

1036 self.sharded_param._layout = self._sharding_spec 

1037 self.sharded_param._placements = tuple(self._sharding_spec.placements) 

1038 # After ``to_empty`` replaces the module parameter with a plain tensor, 

1039 # re-install the DTensor ``nn.Parameter`` so the optimizer and forward 

1040 # hooks see the correct object. Idempotent when the module already 

1041 # holds ``self.sharded_param`` (same data_ptr → no-op in practice). 

1042 self._setattr_on_modules(self.sharded_param) 

1043 

1044 def _update_shardedparam_storage_forcely(self,): 

1045 sharded_param_data = self.sharded_param.data 

1046 local_tensor_data = self.sharded_param._local_tensor.data 

1047 if ( 

1048 sharded_param_data.device != local_tensor_data.device 

1049 or not _same_storage_location(sharded_param_data, local_tensor_data) 

1050 ): 

1051 local_tensor_data.requires_grad_(self.sharded_param.requires_grad) 

1052 # TensorImpl keeps storage_ptr, storage_offset, sizes, strides, dtype and metadatas 

1053 # so swap TensorImpl can make self.sharded_param ref the self.sharded_param._local_tensor's TensorImpl 

1054 # local_tensor_data TensorImpl will deconstruct after this function finish. 

1055 torch._C._swap_tensor_impl(self.sharded_param, local_tensor_data) # pylint: disable=W0212 

1056 

1057 @torch.no_grad() 

1058 def _get_unsharded_param_data(self, async_op: bool = False) -> None: 

1059 """ 

1060 Perform all-gather to get unsharded parameter data. 

1061 

1062 Args: 

1063 async_op: Whether to execute asynchronously. 

1064 

1065 The output buffer and optional asynchronous handle are stored in the 

1066 parameter communication context. 

1067 """ 

1068 all_gather_input = self.all_gather_inputs[0] 

1069 

1070 if self.shard_world_size <= 1 or self.mesh_info.shard_process_group is None: 

1071 if len(self.unsharded_param_buffers) == 0: 

1072 self.unsharded_param_buffers = [all_gather_input] 

1073 elif self.unsharded_param_buffers[0] is not all_gather_input: 

1074 # if param_dtype cast or tensor.to caused by cpu_offload 

1075 self.alloc_unsharded_param_buffers() 

1076 _copy_without_bumping_version(self.unsharded_param_buffers[0], all_gather_input) 

1077 self.allgather_comm_ctx.allgather_output = None 

1078 self.allgather_comm_ctx.allgather_handle = None 

1079 return 

1080 

1081 self.init_unsharded_param_buffers( 

1082 all_gather_input_numels=[all_gather_input.numel()], 

1083 all_gather_input_dtypes=[all_gather_input.dtype], 

1084 world_size=self.shard_world_size, 

1085 device=self.device, 

1086 ) 

1087 self.alloc_unsharded_param_buffers() 

1088 

1089 self.allgather_comm_ctx.allgather_output = self.unsharded_param_buffers[0] 

1090 if self.hsdp_placement.dim != 0: 

1091 # Non-dim-0 sharding uses an extra all-gather buffer before 

1092 # restoring the original dimension with chunk + cat. 

1093 self.allgather_comm_ctx.allgather_output = torch.empty_like( 

1094 self.unsharded_param_buffers[0] 

1095 ) 

1096 # pylint: disable=W0212 

1097 with torch.autograd._unsafe_preserve_version_counter( 

1098 self.allgather_comm_ctx.allgather_output 

1099 ): 

1100 self.allgather_comm_ctx.allgather_handle = dist.all_gather_into_tensor( 

1101 self.allgather_comm_ctx.allgather_output, 

1102 all_gather_input, 

1103 group=self.mesh_info.shard_process_group, 

1104 async_op=async_op, 

1105 ) 

1106 

1107 if self.allgather_comm_ctx.allgather_output is self.unsharded_param_buffers[0]: 

1108 self.allgather_comm_ctx.allgather_output = None 

1109 

1110 

1111 def unshard(self, async_op: bool = False) -> None: 

1112 """Start gathering the full parameter when no gather is already pending. 

1113 

1114 Args: 

1115 async_op: Whether to launch the all-gather asynchronously. 

1116 """ 

1117 if self.allgather_comm_ctx.allgather_handle is not None: 

1118 # Already triggered by HSDPState.prefetch(), so return directly. 

1119 return # no-op 

1120 self._get_unsharded_param_data(async_op=async_op) 

1121 

1122 

1123 def wait_for_unshard(self) -> None: 

1124 """Wait for the parameter all-gather and expose the unsharded parameter.""" 

1125 self._assert_in_states(ShardedState.SHARDED) 

1126 

1127 if self.allgather_comm_ctx.allgather_handle is not None: 

1128 self.allgather_comm_ctx.allgather_handle.wait() 

1129 self.allgather_comm_ctx.allgather_handle = None 

1130 

1131 self.init_unsharded_param() 

1132 self.to_unsharded() 

1133 

1134 def shard(self) -> None: 

1135 """ 

1136 Transition parameter from unsharded back to sharded state. 

1137 """ 

1138 self._assert_in_states(ShardedState.UNSHARDED) 

1139 self.to_sharded() 

1140 

1141 def reduce_scatter_grad( 

1142 self, 

1143 async_op: bool = True, 

1144 reduce_op: Optional[dist.ReduceOp] = dist.ReduceOp.AVG, 

1145 output_buffer: Optional[torch.Tensor] = None, 

1146 ) -> None: 

1147 """ 

1148 Perform reduce-scatter on gradient to reduce and shard the full gradient. 

1149 

1150 Args: 

1151 async_op: Whether to execute asynchronously. 

1152 reduce_op: do reduce-scatter avg or sum. 

1153 output_buffer: Optional pre-allocated output buffer for fused all-reduce. 

1154 When provided, reduce_scatter writes directly into this buffer, 

1155 enabling zero-copy fusion with subsequent all_reduce operations. 

1156 The buffer must have ``padded_sharded_param_size.numel()`` elements 

1157 and the reduction dtype. 

1158 """ 

1159 if ( 

1160 self.reduce_scatter_comm_ctx.reduce_scatter_handle is not None 

1161 or self.reduce_scatter_comm_ctx.reduce_scatter_output is not None 

1162 ): 

1163 raise RuntimeError("Consume the previous ReduceScatter before reusing its communication slot") 

1164 if self.unsharded_accumulated_grad is not None: 

1165 self._grad = self.unsharded_accumulated_grad_data 

1166 self.unsharded_accumulated_grad = None 

1167 else: 

1168 self._grad = self.unsharded_grad_data 

1169 self.unsharded_param.grad = None 

1170 self._grad = self._grad.to(self.reduce_comm_dtype(self._grad)) 

1171 shard_dim = self.hsdp_placement.dim 

1172 if self.shard_world_size <= 1: 

1173 self._grad = self._grad.contiguous().view(-1) 

1174 elif shard_dim != 0: 

1175 grad_chunks = torch.chunk(self._grad, self.shard_world_size, dim=shard_dim) 

1176 self._grad = torch.cat(grad_chunks, dim=0).contiguous().view(-1) 

1177 grad_chunks = None 

1178 else: 

1179 padded_unsharded_dim0 = self.padded_sharded_param_size[0] * self.shard_world_size 

1180 if self._grad.size(0) != padded_unsharded_dim0: 

1181 padded_unsharded_size = torch.Size((padded_unsharded_dim0, *self._grad.shape[1:])) 

1182 padded_grad = self._grad.new_zeros(padded_unsharded_size) 

1183 padded_grad.narrow(0, 0, self._grad.size(0)).copy_(self._grad) 

1184 self._grad = padded_grad 

1185 self._grad = self._grad.contiguous().view(-1) 

1186 apply_gradient_scaling_factor(self._grad, self.gradient_scaling_factor) 

1187 

1188 shard_process_group = self.mesh_info.shard_process_group if isinstance(self.mesh_info, FSDPMeshInfo) else None 

1189 if shard_process_group is None or self.shard_world_size <= 1: 

1190 if output_buffer is not None: 

1191 output_buffer.copy_(self._grad) 

1192 self.reduce_scatter_comm_ctx.reduce_scatter_output = output_buffer 

1193 else: 

1194 self.reduce_scatter_comm_ctx.reduce_scatter_output = self._grad 

1195 self.reduce_scatter_comm_ctx.reduce_scatter_handle = None 

1196 self._grad = None 

1197 return 

1198 

1199 # Calculate output size 

1200 output_numel = self._grad.numel() // self.shard_world_size 

1201 # Use provided output buffer or allocate a new one 

1202 if output_buffer is not None: 

1203 if output_buffer.numel() != output_numel: 

1204 raise ValueError( 

1205 f"output_buffer size mismatch: expected {output_numel}, got {output_buffer.numel()}" 

1206 ) 

1207 if output_buffer.dtype != self._grad.dtype: 

1208 raise ValueError( 

1209 f"output_buffer dtype mismatch: expected {self._grad.dtype}, got {output_buffer.dtype}" 

1210 ) 

1211 self.reduce_scatter_comm_ctx.reduce_scatter_output = output_buffer 

1212 else: 

1213 self.reduce_scatter_comm_ctx.reduce_scatter_output = torch.empty( 

1214 output_numel, 

1215 dtype=self._grad.dtype, 

1216 device=self._grad.device, 

1217 ) 

1218 # Execute reduce_scatter_tensor 

1219 self.reduce_scatter_comm_ctx.reduce_scatter_handle = dist.reduce_scatter_tensor( 

1220 self.reduce_scatter_comm_ctx.reduce_scatter_output, 

1221 self._grad, 

1222 op=reduce_op, 

1223 group=shard_process_group, 

1224 async_op=async_op, 

1225 ) 

1226 if not async_op: 

1227 self._grad = None 

1228 

1229 def all_reduce_grad( 

1230 self, 

1231 async_op: bool = True, 

1232 reduce_op: Optional[dist.ReduceOp] = dist.ReduceOp.AVG, 

1233 ) -> None: 

1234 """ 

1235 All-reduce the current reduce-scatter output across the replicate mesh. 

1236 

1237 Args: 

1238 async_op: Whether to execute asynchronously. 

1239 reduce_op: Reduction operation for the replicate dimension. 

1240 

1241 The output and optional asynchronous work are stored in 

1242 ``all_reduce_comm_ctx``. 

1243 """ 

1244 grad = self.reduce_scatter_comm_ctx.reduce_scatter_output 

1245 if grad is None: 

1246 raise RuntimeError("all_reduce_grad requires a completed reduce-scatter output.") 

1247 reduce_dtype = self.reduce_comm_dtype(grad) 

1248 if grad.dtype != reduce_dtype: 

1249 grad = grad.to(reduce_dtype) 

1250 

1251 replicate_process_group = ( 

1252 self.mesh_info.replicate_process_group if isinstance(self.mesh_info, DDPMeshInfo) else None 

1253 ) 

1254 if replicate_process_group is None or self.replicate_world_size <= 1: 

1255 self.all_reduce_comm_ctx.all_reduce_output = grad 

1256 self.all_reduce_comm_ctx.all_reduce_handle = None 

1257 return 

1258 

1259 self.all_reduce_comm_ctx.all_reduce_handle = dist.all_reduce( 

1260 grad, 

1261 op=reduce_op, 

1262 group=replicate_process_group, 

1263 async_op=async_op, 

1264 ) 

1265 self.all_reduce_comm_ctx.all_reduce_output = grad 

1266 

1267 def all_reduce_source_replicate_grad_inplace( 

1268 self, 

1269 reduced_grad: torch.Tensor, 

1270 reduce_op: dist.ReduceOp, 

1271 ) -> None: 

1272 """All-reduce gradients over non-FSDP replicated axes, in place. 

1273 

1274 ``reduced_grad`` is modified in place; the caller keeps using its own 

1275 reference and must not expect a returned tensor. No-op when the source 

1276 layout has no replicated mesh axis, so callers may invoke it 

1277 unconditionally. 

1278 

1279 The auto_models Trainer needs this reduction for FSDP+TP Norm/Gate 

1280 gradients, which require SUM over TP regardless of FSDP's reduction. 

1281 If a source axis needs AVG in the future, carry its reduce_op in 

1282 source_shard_info instead of reusing the FSDP reduce_op. 

1283 

1284 Args: 

1285 reduced_grad: Gradient to reduce. 

1286 reduce_op: Reduction operation for the non-FSDP source axes. 

1287 """ 

1288 group = self.get_source_replicate_process_group() 

1289 if group is not None: 

1290 dist.all_reduce(reduced_grad, op=reduce_op, group=group, async_op=False) 

1291 

1292 def get_source_replicate_process_group(self) -> Optional[dist.ProcessGroup]: 

1293 """Return the group for replicated source axes outside the FSDP mesh.""" 

1294 if self.source_shard_info is None or not self.source_shard_info.placements: 

1295 return None 

1296 # Use the same deduplicated source layout as sharded storage. Native 

1297 # DTensor compute metadata can include DP/CP axes already reduced by 

1298 # FSDP; reducing those axes again would multiply validate-mode grads. 

1299 source_mesh, source_placements = self._storage_source_layout 

1300 replicate_mesh_dims = tuple( 

1301 mesh_dim 

1302 for mesh_dim, placement in enumerate(source_placements) 

1303 if placement.is_replicate() 

1304 ) 

1305 if not replicate_mesh_dims: 

1306 return None 

1307 mesh_dim_names = source_mesh.mesh_dim_names 

1308 if mesh_dim_names is None: 

1309 raise ValueError( 

1310 "TP shard mesh must define mesh_dim_names to all-reduce replicated gradients." 

1311 ) 

1312 replicate_mesh_dim_names = tuple(mesh_dim_names[mesh_dim] for mesh_dim in replicate_mesh_dims) 

1313 replicate_mesh = source_mesh[replicate_mesh_dim_names].flatten() 

1314 return replicate_mesh.get_group() if replicate_mesh.size() > 1 else None 

1315 

1316 

1317def set_requires_grad_if_needed( 

1318 src_tensor: torch.Tensor, dst_tensor: torch.Tensor 

1319) -> None: 

1320 """set dst_tensor requires_grads from src_tensor if needed.""" 

1321 if src_tensor.requires_grad != dst_tensor.requires_grad: 

1322 dst_tensor.requires_grad_(src_tensor.requires_grad)