Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / dtensor / dtensor.py: 90%

461 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"""dtensor""" 

16# pylint: disable=C9006,C9007 

17import copy as cp 

18import inspect 

19import logging 

20import warnings 

21from typing import Any, Callable, Optional, Sequence, Set, Tuple, Union 

22 

23import numpy as np 

24import torch 

25from torch import Tensor 

26from torch.optim.optimizer import _foreach_supported_types as _optimizer_foreach_supported_types 

27from torch.utils._foreach_utils import _foreach_supported_types as _torch_foreach_supported_types 

28 

29from hyper_parallel.core.dtensor import _utils 

30from hyper_parallel.core.dtensor._collective_utils import mesh_broadcast, mesh_scatter 

31from hyper_parallel.high_availability.group_registry import is_recovery_bootstrapping 

32from hyper_parallel.core.dtensor._ragged_utils import ( 

33 _compute_ragged_slice, 

34 _layout_has_ragged_shard, 

35 _normalize_global_shape, 

36 _scatter_ragged_tensor, 

37 _slice_ragged_tensor, 

38) 

39from hyper_parallel.core.dtensor.device_mesh import _mesh_resources 

40from hyper_parallel.core.dtensor.layout import ( 

41 DeviceMesh, 

42 Layout, 

43 _get_slice_tensor_by_layout, 

44) 

45from hyper_parallel.core.dtensor.placement_types import Partial, Placement, Replicate, StridedShard 

46from hyper_parallel.core.utils import compute_local_shape_and_global_offset 

47from hyper_parallel.core.dtensor.dtensor_base import DTensorBase 

48 

49logger = logging.getLogger(__name__) 

50 

51 

52def _device_meshes_are_compatible(lhs: Any, rhs: Any) -> bool: 

53 """Return whether two mesh objects describe the same device topology.""" 

54 if lhs is rhs: 

55 return True 

56 if not isinstance(lhs, DeviceMesh) or not isinstance(rhs, DeviceMesh): 

57 return False 

58 return lhs.device_type == rhs.device_type and lhs.to_hash() == rhs.to_hash() 

59 

60 

61class SkipDTensorDispatch(): 

62 """Context manager that disables DTensor op dispatch for the enclosed block. 

63 

64 Args: 

65 no_skip: Optional set of op callables or canonical op name strings that 

66 should still be dispatched through DTensor even within this context. 

67 All other ops bypass DTensor dispatch and operate on local tensors. 

68 

69 Example: 

70 >>> import torch 

71 >>> with SkipDTensorDispatch(no_skip={torch.zeros_like}): 

72 ... # zeros_like still goes through DTensor dispatch; 

73 ... # everything else uses the local tensor path. 

74 ... result = torch.zeros_like(dtensor) 

75 """ 

76 

77 def __init__(self, no_skip: Optional[Set] = None): 

78 self._no_skip_names: frozenset = frozenset() 

79 if no_skip: 

80 names = set() 

81 for op in no_skip: 

82 if isinstance(op, str): 

83 names.add(op) 

84 else: 

85 names.add(_utils.get_op_name(op)) 

86 self._no_skip_names = frozenset(names) 

87 self._dispatch_token = None 

88 self._ops_token = None 

89 

90 def __enter__(self): 

91 # pylint: disable=C0415 

92 from hyper_parallel.core.shard._op_dispatch import _dtensor_dispatch_disabled, _no_skip_ops 

93 self._dispatch_token = _dtensor_dispatch_disabled.set(True) 

94 if self._no_skip_names: 

95 self._ops_token = _no_skip_ops.set(_no_skip_ops.get() | self._no_skip_names) 

96 

97 def __exit__(self, exc_type, exc_val, exc_tb): 

98 # pylint: disable=C0415 

99 from hyper_parallel.core.shard._op_dispatch import _dtensor_dispatch_disabled, _no_skip_ops 

100 if self._ops_token is not None: 

101 _no_skip_ops.reset(self._ops_token) 

102 self._ops_token = None 

103 _dtensor_dispatch_disabled.reset(self._dispatch_token) 

104 self._dispatch_token = None 

105 

106 

107# Cache for _build_layout to avoid redundant Layout computations 

108# Key: (device_mesh.to_hash(), tuple(placements), tensor_dim) 

109# Value: Layout 

110_LAYOUT_CACHE = {} 

111 

112 

113def _is_alias_placements(placements) -> bool: 

114 """ 

115 Check if placements use alias strings rather than Placement objects. 

116 

117 Alias placements use mesh dimension names (strings) to specify 

118 the sharding strategy, e.g., ("dp", "tp") or (("dp", "tp"), "None"). 

119 All elements must be strings or tuples of strings for the sequence 

120 to be recognized as alias-style. 

121 

122 Args: 

123 placements: A sequence of placement specifications. 

124 

125 Returns: 

126 bool: True if all elements are alias strings or tuples of strings. 

127 """ 

128 if len(placements) == 0: 

129 return False 

130 for p in placements: 

131 if isinstance(p, str): 

132 continue 

133 if isinstance(p, tuple) and len(p) > 0 and all(isinstance(x, str) for x in p): 

134 continue 

135 return False 

136 return True 

137 

138 

139def _build_layout( 

140 device_mesh: DeviceMesh, 

141 placements: Union[Sequence[Placement], Sequence[Union[str, Tuple[str, ...]]]], 

142 tensor_dim: int 

143) -> Layout: 

144 """ 

145 Build Layout from device_mesh and placements. 

146 

147 This function uses a cache to avoid redundant Layout computations 

148 for the same (device_mesh, placements, tensor_dim) combination. 

149 

150 Args: 

151 device_mesh: The device mesh describing the device topology. 

152 placements: Supports two styles: 

153 - Placement objects (Shard, Replicate, etc.) 

154 - Alias strings ("dp", "None", ("dp", "tp"), etc.), length must 

155 equal the number of tensor dimensions (``tensor_dim``). 

156 tensor_dim: Number of dimensions in the tensor. 

157 

158 Returns: 

159 Layout: The built layout object. 

160 

161 Raises: 

162 ValueError: If alias placements length does not match tensor dimensions. 

163 """ 

164 mesh_key = device_mesh.to_hash() 

165 placements_key = tuple(placements) 

166 cache_key = (mesh_key, placements_key, tensor_dim) 

167 

168 if cache_key in _LAYOUT_CACHE: 

169 return _LAYOUT_CACHE[cache_key] 

170 

171 layout = Layout.from_device_mesh(device_mesh) 

172 

173 if _is_alias_placements(placements): 

174 if len(placements) != tensor_dim: 

175 raise ValueError( 

176 f"Alias placements length ({len(placements)}) must equal " 

177 f"tensor dimensions ({tensor_dim})." 

178 ) 

179 result = layout(*placements) 

180 else: 

181 result = layout(placements) 

182 result.placement_to_tensor_map(tensor_dim) 

183 

184 _LAYOUT_CACHE[cache_key] = result 

185 

186 return result 

187 

188 

189def _is_broadcastable(src_shape: Sequence[int], dst_shape: Sequence[int]) -> bool: 

190 """Return True iff ``src_shape`` is broadcastable to ``dst_shape``. 

191 

192 Standard NumPy / PyTorch right-aligned broadcast rule: ``src`` cannot 

193 have more dimensions than ``dst``; each right-aligned dimension pair 

194 must be equal, or ``src``'s dimension must be 1. 

195 """ 

196 src_shape = tuple(src_shape) 

197 dst_shape = tuple(dst_shape) 

198 if len(src_shape) > len(dst_shape): 

199 return False 

200 for i in range(1, len(src_shape) + 1): 

201 s, d = src_shape[-i], dst_shape[-i] 

202 if s not in (d, 1): 

203 return False 

204 return True 

205 

206 

207def _device_spec(device: Any) -> Tuple[str, Optional[int]]: 

208 """Return normalised ``(device_type, device_index)``. 

209 

210 Handles device objects and strings such as ``"npu:0"``. 

211 """ 

212 device_type = getattr(device, "type", None) 

213 # Only read .index from objects that also have a .type attribute 

214 # (i.e. torch.device). Avoids capturing str.index on plain strings. 

215 device_index = ( 

216 getattr(device, "index", None) if device_type is not None else None 

217 ) 

218 device_text = str(device).lower() 

219 

220 if device_type is None: 

221 parts = device_text.split(":", maxsplit=1) 

222 device_type = parts[0] 

223 if len(parts) == 2 and parts[1].isdigit(): 

224 device_index = int(parts[1]) 

225 

226 return str(device_type).lower(), device_index 

227 

228 

229class DTensor(DTensorBase): 

230 """ 

231 DTensor - Distributed Tensor 

232 

233 A DTensor represents a tensor that is distributed across multiple devices 

234 according to a DeviceMesh and placement specifications. 

235 

236 Args: 

237 local_tensor (Tensor): The local tensor shard on this device. 

238 device_mesh (DeviceMesh): The device mesh describing the device topology. 

239 placements: The placement strategy. Supports two styles: 

240 - Placement objects (e.g., ``[Shard(0), Replicate()]``). 

241 - Alias strings (e.g., ``("dp", "None")`` or 

242 ``(("dp", "tp"), "None")``), length must equal the number of 

243 tensor dimensions. 

244 

245 Example: 

246 >>> mesh = init_device_mesh(device_type="npu", mesh_shape=(2, 2), mesh_dim_names=("dp", "tp")) 

247 >>> local_tensor = Tensor(np.ones((4, 4))) 

248 >>> # Placement style 

249 >>> dtensor = DTensor.from_local(local_tensor, mesh, [Shard(0), Replicate()]) 

250 >>> # Alias style — length matches tensor dims 

251 >>> dtensor = DTensor.from_local(local_tensor, mesh, ("dp", "None")) 

252 """ 

253 _local_tensor: Tensor 

254 _device_mesh: DeviceMesh 

255 _placements: Sequence[Placement] 

256 

257 def __init_data__( 

258 self, 

259 local_tensor: Tensor, 

260 device_mesh: DeviceMesh, 

261 placements: Union[Sequence[Placement], Sequence[Union[str, Tuple[str, ...]]]], 

262 layout: Optional[Layout] = None, 

263 shape: Optional[Tuple[int, ...]] = None, 

264 ): 

265 self._local_tensor = local_tensor 

266 self._device_mesh = device_mesh 

267 tensor_dim = len(shape) if shape is not None else len(local_tensor.shape) 

268 # Fast path: when an already-built Layout is supplied (e.g. output layouts 

269 # cached by infer_layout and passed straight through wrap_output), reuse it 

270 # directly and skip _build_layout (which otherwise recomputes device_mesh.to_hash(), 

271 # tuple(placements) and a cache lookup on every single output construction). 

272 self._layout = layout if layout is not None else _build_layout( 

273 device_mesh, placements, tensor_dim 

274 ) 

275 self._placements = tuple(self._layout.placements) 

276 is_ragged = _layout_has_ragged_shard(self._layout) 

277 if is_ragged and shape is None: 

278 raise ValueError( 

279 "DTensor.from_local with RaggedShard requires an explicit global shape" 

280 ) 

281 if shape is not None: 

282 self._global_shape = _normalize_global_shape(shape) 

283 else: 

284 self._global_shape = tuple(self._layout.get_global_shape(local_tensor.shape)) 

285 if ( 

286 shape is not None 

287 and ( 

288 self._layout.tensor_map is None 

289 or len(self._layout.tensor_map) != len(self._global_shape) 

290 ) 

291 ): 

292 raise ValueError( 

293 "DTensor global shape rank must match layout tensor_map rank, " 

294 f"got global_shape={self._global_shape!r}, tensor_map={self._layout.tensor_map!r}" 

295 ) 

296 if is_ragged: 

297 if hasattr(local_tensor, "is_contiguous") and not local_tensor.is_contiguous(): 

298 raise ValueError("RaggedShard local tensor must be contiguous") 

299 if len(local_tensor.shape) != 1: 

300 raise ValueError( 

301 "RaggedShard local tensor must use one-dimensional flat storage, " 

302 f"got local_shape={tuple(local_tensor.shape)!r}" 

303 ) 

304 expected = _compute_ragged_slice(self._global_shape, self._layout) 

305 if local_tensor.numel() != expected.local_numel: 

306 raise ValueError( 

307 "RaggedShard local tensor numel does not match its allocation, " 

308 f"got actual={local_tensor.numel()}, expected={expected.local_numel}, " 

309 f"global_shape={self._global_shape!r}, placement={self._layout.ragged_shard.placement!r}" 

310 ) 

311 

312 @property 

313 def device_mesh(self) -> DeviceMesh: 

314 """The device mesh of this DTensor.""" 

315 return self._device_mesh 

316 

317 @property 

318 def placements(self) -> Sequence[Placement]: 

319 """The placements of this DTensor.""" 

320 return self._placements 

321 

322 @property 

323 def layout(self) -> Layout: 

324 """Internal layout for redistribution (for backward compatibility).""" 

325 if not hasattr(self, '_layout'): 

326 return None 

327 return self._layout 

328 

329 @staticmethod 

330 def from_local( 

331 local_tensor: Tensor, 

332 device_mesh: DeviceMesh, 

333 placements: Union[Sequence[Placement], Sequence[Union[str, Tuple[str, ...]]]], 

334 *, 

335 run_check: bool = False, 

336 shape: Optional[Tuple[int, ...]] = None, 

337 stride: Optional[Tuple[int, ...]] = None, 

338 ) -> 'DTensor': 

339 """ 

340 Create a DTensor from a local tensor with device mesh and placements. 

341 

342 Args: 

343 local_tensor (Tensor): The local tensor shard on this device. For 

344 ``RaggedShard``, the input may use its natural rank-local shape; 

345 construction stores it as a one-dimensional view internally. 

346 device_mesh (DeviceMesh): The device mesh describing the device topology. 

347 placements: The placement strategy. Supports two styles: 

348 - Placement objects (e.g., ``[Shard(0), Replicate()]``). 

349 - Alias strings (e.g., ``("dp", "None")`` or 

350 ``(("dp", "tp"), "None")``), length must equal the number 

351 of tensor dimensions. 

352 run_check (bool, optional): When ``True``, perform cross-rank metadata 

353 checks and broadcast replicate placements from the mesh source rank. 

354 Forced to ``False`` with a warning during replacement worker 

355 bootstrap before recovery state is attached. Default: ``False``. 

356 shape (tuple[int, ...], optional): Explicit logical global shape. 

357 Required for RaggedShard. 

358 stride (tuple[int, ...], optional): Explicit logical global stride. 

359 Requires ``shape``. Normal layouts also retain compatibility 

360 with shape-only construction. 

361 

362 Returns: 

363 DTensor: A new DTensor instance. 

364 

365 Example: 

366 >>> mesh = init_device_mesh(device_type="npu", mesh_shape=(2, 2), mesh_dim_names=("dp", "tp")) 

367 >>> local_tensor = Tensor(np.ones((4, 4))) 

368 >>> dtensor = DTensor.from_local(local_tensor, mesh, [Shard(0), Replicate()]) 

369 >>> dtensor = DTensor.from_local(local_tensor, mesh, ("dp", "None")) 

370 """ 

371 tensor_dim = len(shape) if shape is not None else len(local_tensor.shape) 

372 layout = _build_layout(device_mesh, placements, tensor_dim) 

373 is_ragged = _layout_has_ragged_shard(layout) 

374 if is_ragged: 

375 if stride is not None and shape is None: 

376 raise ValueError("stride requires an explicit shape") 

377 if hasattr(local_tensor, "is_contiguous") and not local_tensor.is_contiguous(): 

378 raise ValueError("RaggedShard local tensor must be contiguous") 

379 local_tensor = local_tensor.view(-1) 

380 elif stride is not None and shape is None: 

381 raise ValueError("stride requires an explicit shape") 

382 if run_check and is_recovery_bootstrapping(): 

383 logger.warning("DTensor.from_local: overriding run_check=True with False during replacement bootstrap " 

384 "to avoid cross-rank checks while peers may be waiting for recovery") 

385 run_check = False 

386 if run_check: 

387 # pylint: disable=C0415 

388 from hyper_parallel.core.dtensor._from_local_utils import run_from_local_checks 

389 run_from_local_checks( 

390 local_tensor, 

391 device_mesh, 

392 layout.placements, 

393 shape=shape, 

394 ) 

395 if shape is not None and stride is not None: 

396 layout = cp.deepcopy(layout) 

397 layout.set_tensor_meta(shape, stride, local_tensor.dtype) 

398 return DTensor( 

399 local_tensor, 

400 device_mesh, 

401 layout.placements, 

402 layout, 

403 shape=shape, 

404 ) 

405 

406 @staticmethod 

407 def from_local_with_layout( 

408 local_tensor: Tensor, 

409 layout: Layout, 

410 *, 

411 shape: Optional[Tuple[int, ...]] = None, 

412 ) -> 'DTensor': 

413 """Fast DTensor construction from a local tensor and a pre-built Layout. 

414 

415 Unlike :meth:`from_local`, this does NOT rebuild the layout via 

416 ``_build_layout`` — it hands the already-built ``layout`` straight to 

417 ``__init_data__``. Intended for hot paths (e.g. ``wrap_output``) where the 

418 output Layout was already inferred and cached by ``infer_layout``, so 

419 recomputing ``device_mesh.to_hash()`` / ``tuple(placements)`` / the layout 

420 cache lookup on every output is pure waste. 

421 

422 ``layout.placements`` (a plain attribute) is passed only to satisfy the 

423 constructor's non-None check; ``__init_data__`` ignores it when ``layout`` 

424 is supplied. 

425 """ 

426 return DTensor( 

427 local_tensor, 

428 layout.mesh, 

429 layout.placements, 

430 layout, 

431 shape=shape, 

432 ) 

433 

434 def _alias_placements(self) -> Sequence[Placement]: 

435 """Return alias_placements from layout, falling back to _placements.""" 

436 if hasattr(self, '_layout') and self._layout: 

437 return self._layout.alias_placements 

438 return self._placements 

439 

440 def _new_with_same_layout(self, local_tensor: Tensor) -> 'DTensor': 

441 """Create a DTensor from a local shard while retaining the logical layout. 

442 

443 The shard must retain its logical shape. Layout metadata is copied so 

444 updating its dtype cannot mutate the source. Parameter inputs produce 

445 plain DTensors. This method does not copy tensor data or communicate. 

446 """ 

447 tensor_type = DTensor if isinstance(self, torch.nn.Parameter) else self.__class__ 

448 if not isinstance(self._layout, Layout): 

449 constructor_kwargs = { 

450 "device_mesh": self._device_mesh, 

451 "placements": self._alias_placements(), 

452 } 

453 if hasattr(self, "_global_shape"): 

454 constructor_kwargs["shape"] = self._global_shape 

455 return tensor_type(local_tensor, **constructor_kwargs) 

456 layout = cp.deepcopy(self._layout) 

457 if layout.tensor_shape is not None: 

458 layout.set_tensor_meta( 

459 layout.tensor_shape, 

460 layout.tensor_stride, 

461 local_tensor.dtype, 

462 ) 

463 return tensor_type( 

464 local_tensor, 

465 device_mesh=self._device_mesh, 

466 placements=layout.placements, 

467 layout=layout, 

468 shape=self._global_shape, 

469 ) 

470 

471 def detach(self) -> "DTensor": 

472 """Detach autograd while retaining the complete logical layout. 

473 

474 The result shares local storage and owns its layout metadata so dtype 

475 conversions cannot change the source. Uneven shards need this metadata 

476 when optimizer moments are initialized with ``zeros_like`` during resume. 

477 """ 

478 if self.layout is None: 

479 return super().detach() 

480 return self._new_with_same_layout(self._local_tensor.detach()) 

481 

482 def to(self, *args, **kwargs): 

483 """Move the DTensor to a different device or dtype. 

484 

485 Delegates to the underlying local tensor's ``to`` method and 

486 reconstructs a DTensor preserving device_mesh and placements. 

487 

488 Args: 

489 *args (tuple): Arguments passed to the underlying tensor's ``to`` 

490 method (e.g., device or dtype). 

491 **kwargs (dict): Keyword arguments for the tensor conversion 

492 (e.g., dtype, device, non_blocking). 

493 

494 Returns: 

495 DTensor: A new DTensor with the converted local tensor. 

496 """ 

497 new_local = self._local_tensor.to(*args, **kwargs) 

498 return self._new_with_same_layout(new_local) 

499 

500 def float(self): 

501 """Convert the DTensor to float dtype. 

502 

503 Returns: 

504 DTensor: A new DTensor with float32 local tensor. 

505 """ 

506 new_local = self._local_tensor.float() 

507 return self._new_with_same_layout(new_local) 

508 

509 def type_as(self, other: Tensor) -> "DTensor": 

510 """Cast this DTensor to the dtype of ``other``. 

511 

512 This is a **local** operation — no communication. Each shard 

513 independently casts its elements to the target dtype. 

514 

515 Only the **dtype** of ``other`` is read; its shape, values, and 

516 layout are ignored. The returned DTensor preserves the 

517 device-mesh and placements of ``self`` unchanged. 

518 

519 Args: 

520 other (Tensor): A tensor whose ``.dtype`` will be used as the 

521 target type. May be a plain :class:`Tensor` or a 

522 :class:`DTensor`. Must reside on the same device as 

523 ``self``. 

524 

525 Returns: 

526 DTensor: A new DTensor with the converted local tensor. When 

527 ``self.dtype == other.dtype`` the method returns ``self`` 

528 unchanged (no-op). 

529 

530 Raises: 

531 ValueError: If ``other`` is not a Tensor. 

532 ValueError: If ``self`` has Partial placement (cast does not 

533 commute with reduction). 

534 ValueError: If ``self`` and ``other`` are on different devices. 

535 

536 Note: 

537 This implementation intentionally covers **dtype-only** 

538 conversion. PyTorch's native ``type_as`` may also handle 

539 cross-device transfers, but a DTensor cannot silently change 

540 its backend device while retaining the old ``DeviceMesh``. 

541 Use :meth:`to` for explicit device + dtype conversion. 

542 

543 Example: 

544 >>> # x is a DTensor of float16, y is a plain float32 Tensor 

545 >>> # on the same device. 

546 >>> z = x.type_as(y) 

547 >>> z.dtype == y.dtype 

548 True 

549 """ 

550 if not isinstance(other, Tensor): 

551 raise ValueError( 

552 f"type_as() argument must be a Tensor, but got " 

553 f"{type(other).__name__}." 

554 ) 

555 if hasattr(self, '_layout') and self._layout is not None: 

556 if self._layout.is_partial(): 

557 raise ValueError( 

558 "DTensor.type_as does not support Partial input; " 

559 "call reduce_partial() first." 

560 ) 

561 

562 other_local = other.to_local() if isinstance(other, DTensor) else other 

563 if self._local_tensor.device != other_local.device: 

564 raise ValueError( 

565 "DTensor.type_as requires self and other to be on the " 

566 "same device. Use to() for explicit device + dtype " 

567 "conversion." 

568 ) 

569 

570 target_dtype = other.dtype 

571 if self.dtype == target_dtype: 

572 return self 

573 new_local = self._local_tensor.to(dtype=target_dtype) 

574 return self._new_with_same_layout(new_local) 

575 

576 def _validate_factory_device(self, device: Any) -> None: 

577 """Raise :class:`ValueError` if ``device`` does not match the DTensor's device.""" 

578 requested_type, requested_index = _device_spec(device) 

579 local_type, local_index = _device_spec(self._local_tensor.device) 

580 if ( 

581 requested_type != local_type 

582 or ( 

583 requested_index is not None 

584 and requested_index != local_index 

585 ) 

586 ): 

587 raise ValueError( 

588 f"DTensor requires device to match the input DTensor " 

589 f"device {self._local_tensor.device}, but got {device}." 

590 ) 

591 

592 def _new_const_tensor_op( 

593 self, 

594 method_name: str, 

595 size: Union[int, Sequence[int]], 

596 *, 

597 dtype: Optional[Any] = None, 

598 device: Optional[Any] = None, 

599 requires_grad: bool = False, 

600 layout: Optional[Any] = None, 

601 pin_memory: bool = False, 

602 ) -> 'DTensor': 

603 """Create an all-``Replicate`` constant DTensor. 

604 

605 Shared implementation for ``new_zeros`` and ``new_ones``. 

606 

607 ``self`` is only used as a dtype/device reference and mesh source; 

608 its values are ignored. The output is always **all-Replicate** 

609 because every device produces identical data independently. 

610 

611 Args: 

612 method_name: 

613 ``"new_zeros"`` or ``"new_ones"`` — the local tensor 

614 factory method to call. 

615 size: 

616 Output shape — an int or a sequence of ints. 

617 dtype: 

618 Desired dtype. Defaults to ``self.dtype`` on Torch. 

619 device: 

620 Must match ``self``'s device. 

621 requires_grad: 

622 If true, the new tensor requires gradient. 

623 layout: 

624 Desired layout of the new tensor. 

625 pin_memory: 

626 If true, the new tensor is allocated in pinned memory. 

627 

628 Returns: 

629 DTensor: A new DTensor with all-``Replicate`` placements on 

630 ``self``'s ``DeviceMesh``. 

631 

632 Raises: 

633 ValueError: If ``device`` does not match the DTensor's device. 

634 """ 

635 if isinstance(size, int): 

636 size = (size,) 

637 

638 local_kwargs = {} 

639 if dtype is not None: 

640 local_kwargs["dtype"] = dtype 

641 if device is not None: 

642 self._validate_factory_device(device) 

643 # An unindexed device such as "cuda" resolves to the framework's 

644 # current device, which may differ from this DTensor's local device. 

645 local_kwargs["device"] = self._local_tensor.device 

646 if requires_grad: 

647 local_kwargs["requires_grad"] = True 

648 if layout is not None: 

649 local_kwargs["layout"] = layout 

650 if pin_memory: 

651 local_kwargs["pin_memory"] = True 

652 

653 factory = getattr(self._local_tensor, method_name) 

654 local_result = factory(size, **local_kwargs) 

655 

656 replicated_placements = [Replicate()] * self._device_mesh.ndim 

657 return DTensor.from_local( 

658 local_result, self._device_mesh, replicated_placements, 

659 ) 

660 

661 def new_zeros( 

662 self, 

663 size: Union[int, Sequence[int]], 

664 *, 

665 dtype: Optional[Any] = None, 

666 device: Optional[Any] = None, 

667 requires_grad: bool = False, 

668 layout: Optional[Any] = None, 

669 pin_memory: bool = False, 

670 ) -> 'DTensor': 

671 """Create an all-Replicate DTensor filled with zeros. 

672 

673 The output is always **fully replicated** across every device in 

674 ``self``'s ``DeviceMesh``, regardless of how ``self`` is sharded. 

675 

676 Args: 

677 size: 

678 Output shape — an int or a sequence of ints. 

679 dtype: 

680 Desired dtype. Defaults to ``self.dtype``. 

681 device: 

682 Must match ``self``'s device. 

683 requires_grad: 

684 If true, the new tensor requires gradient. 

685 layout: 

686 Desired layout of the new tensor. 

687 pin_memory: 

688 If true, the new tensor is allocated in pinned memory. 

689 

690 Returns: 

691 DTensor: A new all-Replicate DTensor filled with zeros. 

692 """ 

693 return self._new_const_tensor_op( 

694 "new_zeros", size, 

695 dtype=dtype, 

696 device=device, 

697 requires_grad=requires_grad, 

698 layout=layout, 

699 pin_memory=pin_memory, 

700 ) 

701 

702 def new_ones( 

703 self, 

704 size: Union[int, Sequence[int]], 

705 *, 

706 dtype: Optional[Any] = None, 

707 device: Optional[Any] = None, 

708 requires_grad: bool = False, 

709 layout: Optional[Any] = None, 

710 pin_memory: bool = False, 

711 ) -> 'DTensor': 

712 """Create an all-Replicate DTensor filled with ones. 

713 

714 The output is always **fully replicated** across every device in 

715 ``self``'s ``DeviceMesh``, regardless of how ``self`` is sharded. 

716 

717 Args: 

718 size: 

719 Output shape — an int or a sequence of ints. 

720 dtype: 

721 Desired dtype. Defaults to ``self.dtype``. 

722 device: 

723 Must match ``self``'s device. 

724 requires_grad: 

725 If true, the new tensor requires gradient. 

726 layout: 

727 Desired layout of the new tensor. 

728 pin_memory: 

729 If true, the new tensor is allocated in pinned memory. 

730 

731 Returns: 

732 DTensor: A new all-Replicate DTensor filled with ones. 

733 """ 

734 return self._new_const_tensor_op( 

735 "new_ones", size, 

736 dtype=dtype, 

737 device=device, 

738 requires_grad=requires_grad, 

739 layout=layout, 

740 pin_memory=pin_memory, 

741 ) 

742 

743 def to_local(self) -> Tensor: 

744 """ 

745 Convert DTensor to local tensor. 

746 

747 Returns: 

748 Tensor: The local tensor shard on this device. 

749 """ 

750 return self._local_tensor 

751 

752 def tolist(self): 

753 """ 

754 Convert the DTensor to a nested Python list or number. 

755 

756 This operation gathers the complete tensor on every participating rank 

757 before converting it to Python values. It is an **implicit collective**: 

758 all ranks in the DeviceMesh must participate. 

759 

760 Returns: 

761 Union[list, int, float, bool]: A nested Python list, or a Python 

762 number for a scalar DTensor. 

763 

764 Note: 

765 This triggers ``full_tensor()`` under the hood, which performs 

766 all-gather communication. For large tensors, prefer slicing or 

767 index-based access to avoid materialising the full tensor. 

768 

769 If you only need the **local shard** as a list, use 

770 ``dtensor.to_local().tolist()`` instead — that path has zero 

771 communication overhead. 

772 

773 Example: 

774 >>> mesh = init_device_mesh("npu", (2,), ("dp",)) 

775 >>> x = distribute_tensor(torch.arange(8).reshape(4, 2), mesh, [Shard(0)]) 

776 >>> x.tolist() # full data: [[0,1],[2,3],[4,5],[6,7]] 

777 >>> x.to_local().tolist() # local shard only (no comm) 

778 """ 

779 return self.full_tensor().tolist() 

780 

781 def copy_(self, src: "DTensor", non_blocking: bool = False) -> "DTensor": 

782 """In-place copy of ``src`` into this DTensor's local shard. 

783 

784 Delegates to ``Tensor.copy_`` on the underlying local tensors. 

785 Follows standard ``Tensor.copy_`` semantics: version counter is 

786 bumped and autograd edges are created when grad is enabled. 

787 

788 Constraints on ``src``: 

789 * must be a ``DTensor`` on the same or an equivalent ``DeviceMesh`` topology as ``self``; 

790 * its placements must equal ``self.placements``, OR 

791 ``src._local_tensor.numel() == 1`` (single-element broadcast); 

792 * its local shape must equal or be broadcastable to 

793 ``self._local_tensor.shape``. 

794 

795 No redistribute / implicit slicing is performed; src dtype is cast 

796 to self dtype in-place. 

797 

798 Args: 

799 src (DTensor): Source DTensor satisfying the constraints above. 

800 non_blocking (bool): Forwarded to the underlying ``copy_``. 

801 

802 Returns: 

803 DTensor: ``self``. 

804 

805 Raises: 

806 TypeError: if ``src`` is not a ``DTensor``. 

807 ValueError: if mesh, placement, or shape constraint is violated. 

808 """ 

809 if not isinstance(src, DTensor): 

810 raise TypeError( 

811 f"For DTensor.copy_, src should be a DTensor, but got {type(src).__name__}." 

812 ) 

813 src_local = src.to_local() 

814 if not _device_meshes_are_compatible(src.device_mesh, self._device_mesh): 

815 raise ValueError( 

816 f"For DTensor.copy_, src and self should share the same DeviceMesh, " 

817 f"but got src.device_mesh={src.device_mesh!r}, " 

818 f"self._device_mesh={self._device_mesh!r}." 

819 ) 

820 

821 placement_eq = tuple(src.placements) == tuple(self._placements) 

822 shape_eq = src_local.shape == self._local_tensor.shape 

823 src_is_scalar = src_local.numel() == 1 

824 

825 if not placement_eq and not src_is_scalar: 

826 raise ValueError( 

827 f"For DTensor.copy_, src.placements should equal self.placements " 

828 f"or src.numel() should be 1, but got " 

829 f"src.placements={src.placements}, " 

830 f"self.placements={self._placements}, " 

831 f"src.numel()={src_local.numel()}." 

832 ) 

833 if not shape_eq and not src_is_scalar and not _is_broadcastable( 

834 src_local.shape, self._local_tensor.shape 

835 ): 

836 raise ValueError( 

837 f"For DTensor.copy_, src local shape should be broadcastable to " 

838 f"self local shape, but got " 

839 f"src.shape={tuple(src_local.shape)}, " 

840 f"self.shape={tuple(self._local_tensor.shape)}." 

841 ) 

842 

843 self._local_tensor.copy_(src_local, non_blocking=non_blocking) 

844 return self 

845 

846 def zero_(self) -> "DTensor": 

847 """In-place fill with zeros. Returns ``self``.""" 

848 self._local_tensor.zero_() 

849 return self 

850 

851 def fill_(self, value) -> "DTensor": 

852 """In-place fill with ``value``. Returns ``self``.""" 

853 self._local_tensor.fill_(value) 

854 return self 

855 

856 @property 

857 def shape(self) -> Tuple[int, ...]: 

858 """ 

859 The global shape of this DTensor. 

860 

861 Returns: 

862 Tuple[int, ...]: The global tensor shape. 

863 """ 

864 return self._global_shape 

865 

866 def size(self, dim=None): 

867 """Return the global shape, consistent with .shape. 

868 

869 Without ``dim`` returns a tuple matching ``self.shape``. 

870 With ``dim`` returns the size of that dimension. 

871 """ 

872 global_shape = self.shape 

873 if dim is not None: 

874 return global_shape[dim] 

875 return global_shape 

876 

877 def numel(self) -> int: 

878 """Return the number of elements in this DTensor.""" 

879 return int(np.prod(self.shape)) 

880 

881 @property 

882 def ndim(self) -> int: 

883 """Return the logical global tensor rank.""" 

884 return len(self._global_shape) 

885 

886 def dim(self) -> int: 

887 """Return the logical global tensor rank.""" 

888 return len(self._global_shape) 

889 

890 @property 

891 def local_shape(self) -> Tuple[int, ...]: 

892 """ 

893 The local shape of this DTensor on this device. 

894 

895 Returns: 

896 Tuple[int, ...]: The local tensor shape. 

897 """ 

898 return self._local_tensor.shape 

899 

900 def redistribute( 

901 self, 

902 device_mesh: DeviceMesh, 

903 placements: Union[Sequence[Placement], Sequence[Union[str, Tuple[str, ...]]]] 

904 ) -> 'DTensor': 

905 """ 

906 Redistribute this DTensor to a new device mesh and placements. 

907 

908 Args: 

909 device_mesh (DeviceMesh): The target device mesh. 

910 placements: The target placements. Supports Placement objects 

911 or alias strings. 

912 

913 Returns: 

914 DTensor: A new DTensor with the specified distribution. 

915 

916 Example: 

917 >>> new_dtensor = dtensor.redistribute(mesh, [Replicate(), Shard(1)]) 

918 >>> new_dtensor = dtensor.redistribute(mesh, ("None", "tp")) 

919 """ 

920 logger.debug( 

921 "redistribute: shape=%s, src_placements=%s -> dst_placements=%s, " 

922 "mesh_shape=%s, local_shape=%s", 

923 tuple(self.shape), 

924 tuple(self._placements), 

925 tuple(placements), 

926 tuple(device_mesh.shape), 

927 tuple(self._local_tensor.shape), 

928 ) 

929 

930 # Build dst_layout from device_mesh and placements 

931 dst_layout = _build_layout( 

932 device_mesh, placements, len(self._global_shape) 

933 ) 

934 

935 # pylint: disable=C0415 

936 from hyper_parallel.core.dtensor.tensor_redistribution import _tensor_redistribution 

937 out = _tensor_redistribution.redistribution(self, dst_layout) 

938 return out 

939 

940 def reduce_partial(self) -> 'DTensor': 

941 """ 

942 Reduce partial sharding state for this DTensor. 

943 

944 Returns: 

945 DTensor: A new DTensor with partial state reduced. 

946 """ 

947 if not self._layout: 

948 return self 

949 to_layout = cp.deepcopy(self._layout) 

950 to_layout.reset_partial() 

951 # pylint: disable=C0415 

952 from hyper_parallel.core.dtensor.tensor_redistribution import _tensor_redistribution 

953 out = _tensor_redistribution.reduce_partial(self, to_layout) 

954 return out 

955 

956 def full_tensor(self) -> Tensor: 

957 """ 

958 Return the full tensor of this DTensor. 

959 

960 Returns: 

961 Tensor: A Tensor object that represents the full tensor of this DTensor. 

962 The returned tensor contains the complete data gathered from 

963 all ranks. 

964 

965 Note: 

966 This operation involves communication across all ranks in the DeviceMesh, 

967 which may be expensive for large tensors. Use with caution in 

968 performance-critical code paths. 

969 

970 Example: 

971 >>> # Assume dtensor is sharded across multiple devices 

972 >>> local_tensor = dtensor.to_local() # Returns only the local shard 

973 >>> full_tensor = dtensor.full_tensor() # Returns the complete tensor 

974 """ 

975 if not self._layout: 

976 return self._local_tensor 

977 

978 # Create a fully replicated layout 

979 replicated_layout = cp.deepcopy(self._layout) 

980 

981 # Set all placements to Replicate and convert to tensor_map 

982 replicated_placements = [Replicate()] * len(replicated_layout.mesh_shape) 

983 replicated_layout.set_placements(replicated_placements) 

984 replicated_layout.placement_to_tensor_map(len(self._global_shape)) 

985 

986 # Clear partial status from original layout since Replicate has no partial 

987 replicated_layout.reset_partial() 

988 

989 # Redistribute to the replicated layout and return local tensor 

990 # pylint: disable=C0415 

991 from hyper_parallel.core.dtensor.tensor_redistribution import _tensor_redistribution 

992 out = _tensor_redistribution.redistribution(self, replicated_layout) 

993 return out.to_local() 

994 

995 

996def _register_optimizer_tensor_type() -> None: 

997 """Enable PyTorch optimizer and foreach selection for DTensor.""" 

998 for supported_types in (_optimizer_foreach_supported_types, _torch_foreach_supported_types): 

999 if DTensor not in supported_types: 

1000 supported_types.append(DTensor) 

1001 

1002 

1003_register_optimizer_tensor_type() 

1004 

1005 

1006def _normalize_shard_dim(dim: int, ndim: int) -> int: 

1007 return dim + ndim if dim < 0 else dim 

1008 

1009 

1010def _distribute_tensor_with_communication( 

1011 tensor: Tensor, 

1012 device_mesh: DeviceMesh, 

1013 placements: Sequence[Placement], 

1014 src_data_rank: int, 

1015) -> Tensor: 

1016 """Scatter/broadcast a logical global tensor along mesh dimensions (PyTorch parity).""" 

1017 local = tensor 

1018 if len(placements) < device_mesh.ndim: 

1019 raise ValueError( 

1020 f"placements length ({len(placements)}) must be at least device_mesh.ndim " 

1021 f"({device_mesh.ndim}) when src_data_rank is set" 

1022 ) 

1023 for mesh_dim in range(device_mesh.ndim): 

1024 placement = placements[mesh_dim] 

1025 if isinstance(placement, StridedShard): 

1026 raise NotImplementedError( 

1027 "distribute_tensor with src_data_rank does not support StridedShard yet; " 

1028 "pass src_data_rank=None for local-only sharding." 

1029 ) 

1030 if placement.is_shard(): 

1031 shard_dim = _normalize_shard_dim(placement.dim, local.ndim) 

1032 num_chunks = device_mesh.size(mesh_dim) 

1033 if num_chunks <= 0: 

1034 raise ValueError(f"invalid mesh dim size {num_chunks} on mesh_dim={mesh_dim}") 

1035 chunks = tuple(local.chunk(num_chunks, dim=shard_dim)) 

1036 if not chunks: 

1037 raise ValueError(f"cannot shard dim {shard_dim} into {num_chunks} chunks") 

1038 output = torch.empty_like(chunks[0]) 

1039 local = mesh_scatter(output, chunks, device_mesh, mesh_dim, group_src=src_data_rank) 

1040 elif placement.is_replicate() or placement.is_partial(): 

1041 local = mesh_broadcast(local, device_mesh, mesh_dim, group_src=src_data_rank) 

1042 if isinstance(placement, Partial): 

1043 warnings.warn( 

1044 f"Partial placement {placement} during distribute_tensor: " 

1045 "broadcast only; partial partition is not applied yet.", 

1046 stacklevel=3, 

1047 ) 

1048 else: 

1049 raise RuntimeError( 

1050 f"unsupported placement {placement} on device mesh dimension {mesh_dim}" 

1051 ) 

1052 return local 

1053 

1054 

1055def distribute_tensor( 

1056 tensor: Tensor, 

1057 device_mesh: DeviceMesh, 

1058 placements: Union[Sequence[Placement], Sequence[Union[str, Tuple[str, ...]]]], 

1059 *, 

1060 src_data_rank: Optional[int] = None, 

1061) -> DTensor: 

1062 """ 

1063 Distribute a global tensor to the device mesh according to the placements. 

1064 

1065 Args: 

1066 tensor (Tensor): The global tensor to be distributed. All ranks 

1067 should have the same tensor data. 

1068 device_mesh (DeviceMesh): The device mesh describing the device topology. 

1069 placements: The placement strategy. Supports two styles: 

1070 - Placement objects (e.g., ``[Shard(0), Replicate()]``). 

1071 - Alias strings (e.g., ``("dp", "None")`` or 

1072 ``(("dp", "tp"), "None")``), length must equal the number of 

1073 tensor dimensions. 

1074 

1075 Returns: 

1076 DTensor: A new DTensor with the local shard on each rank. 

1077 

1078 Note: 

1079 When ``src_data_rank`` is an ``int`` (e.g. ``0``), shard/replicate 

1080 placements use scatter/broadcast from the source rank on each mesh axis, 

1081 using source-rank distribution. When ``src_data_rank=None`` 

1082 (default), each rank slices its local tensor without communication 

1083 (legacy Hyper behavior; all ranks must hold the same global data). 

1084 During replacement bootstrap, an explicit source rank is overridden 

1085 with ``None`` and a warning is emitted to avoid initialization collectives. 

1086 

1087 Example: 

1088 >>> mesh = init_device_mesh(device_type="npu", mesh_shape=(2, 2), mesh_dim_names=("dp", "tp")) 

1089 >>> global_tensor = Tensor(np.arange(16).reshape(4, 4)) 

1090 >>> dtensor = distribute_tensor(global_tensor, mesh, [Shard(0), Replicate()]) 

1091 >>> dtensor = distribute_tensor(global_tensor, mesh, ("dp", "None")) 

1092 """ 

1093 if is_recovery_bootstrapping(): 

1094 # A replacement constructs local storage while peers are parked. 

1095 # Replica repair supplies device values after communication rebuild. 

1096 if src_data_rank is not None: 

1097 logger.warning("distribute_tensor: overriding src_data_rank=%s with None " 

1098 "during worker recovery to avoid source-rank communication", src_data_rank) 

1099 src_data_rank = None 

1100 layout = _build_layout(device_mesh, placements, len(tensor.shape)) 

1101 if _layout_has_ragged_shard(layout): 

1102 if src_data_rank is None: 

1103 local_tensor = _slice_ragged_tensor(tensor, layout) 

1104 else: 

1105 local_tensor = _scatter_ragged_tensor(tensor, layout, src_data_rank) 

1106 elif src_data_rank is None: 

1107 local_tensor = _get_slice_tensor_by_layout(tensor, layout) 

1108 else: 

1109 local_tensor = _distribute_tensor_with_communication( 

1110 tensor, device_mesh, layout.placements, src_data_rank 

1111 ) 

1112 return DTensor.from_local_with_layout( 

1113 local_tensor, 

1114 layout, 

1115 shape=tuple(tensor.shape), 

1116 ) 

1117 

1118 

1119def _distribute_module_param_source(param: Any) -> Tensor: 

1120 """Tensor data used as the global tensor for :func:`distribute_tensor`.""" 

1121 return param.data 

1122 

1123 

1124def _distribute_module_new_parameter(key: str, dtensor: DTensor, requires_grad: bool) -> Any: 

1125 """Build a :class:`torch.nn.Parameter` holding *dtensor*.""" 

1126 del key 

1127 return torch.nn.Parameter(dtensor, requires_grad=requires_grad) 

1128 

1129 

1130def _distribute_module_set_param(module: Any, key: str, new_param: Any) -> None: 

1131 """Register or assign a parameter on *module* (``nn.Module``-like).""" 

1132 if hasattr(module, "register_parameter"): 

1133 module.register_parameter(key, new_param) 

1134 return 

1135 if hasattr(module, "_params"): 

1136 module._params[key] = new_param 

1137 if hasattr(module, "_params_list"): 

1138 module._params_list[key] = new_param 

1139 if key in module.__dict__: 

1140 module.__dict__[key] = new_param 

1141 return 

1142 raise TypeError( 

1143 f"distribute_module expects nn.Module-like objects with register_parameter or _params; " 

1144 f"got {type(module)}." 

1145 ) 

1146 

1147 

1148def _distribute_module_iter_params(module: Any) -> list: 

1149 """Return ``[(name, param), ...]`` for direct parameters (``_parameters`` or ``_params``).""" 

1150 if hasattr(module, "_parameters"): 

1151 return list(module._parameters.items()) 

1152 if hasattr(module, "_params"): 

1153 return list(module._params.items()) 

1154 return [] 

1155 

1156 

1157def _distribute_module_iter_buffers(module: Any) -> list: 

1158 """Return ``[(name, buffer), ...]`` if the module has ``_buffers`` (PyTorch ``nn.Module``).""" 

1159 if hasattr(module, "_buffers"): 

1160 return list(module._buffers.items()) 

1161 return [] 

1162 

1163 

1164def _distribute_module_named_modules(module: Any): 

1165 """``nn.Module.named_modules`` (submodule FQNs).""" 

1166 if hasattr(module, "named_modules"): 

1167 return module.named_modules() 

1168 raise TypeError( 

1169 f"distribute_module expects a module-like object with named_modules; " 

1170 f"got {type(module)}." 

1171 ) 

1172 

1173 

1174def _distribute_module_named_parameters(module: Any): 

1175 """``nn.Module.named_parameters(recurse=False)``.""" 

1176 if hasattr(module, "named_parameters"): 

1177 return module.named_parameters(recurse=False) 

1178 raise TypeError( 

1179 f"distribute_module expects a module-like object with named_parameters; " 

1180 f"got {type(module)}." 

1181 ) 

1182 

1183 

1184def _replicate_submodule_params_buffers( 

1185 sub_mod: Any, 

1186 device_mesh: DeviceMesh, 

1187 *, 

1188 module_prefix: str = "", 

1189) -> None: 

1190 """Convert plain params/buffers on *sub_mod* to fully replicated :class:`DTensor`.""" 

1191 full_replicate = [Replicate()] * device_mesh.ndim 

1192 for key, param in _distribute_module_iter_params(sub_mod): 

1193 if param is None or isinstance(param, DTensorBase): 

1194 continue 

1195 src = _distribute_module_param_source(param) 

1196 requires_grad = bool(getattr(param, "requires_grad", True)) 

1197 dt = distribute_tensor(src, device_mesh, full_replicate) 

1198 param_name = f"{module_prefix}.{key}" if module_prefix else key 

1199 new_param = _distribute_module_new_parameter(param_name, dt, requires_grad) 

1200 _distribute_module_set_param(sub_mod, key, new_param) 

1201 for key, buffer in _distribute_module_iter_buffers(sub_mod): 

1202 if buffer is None or isinstance(buffer, DTensorBase): 

1203 continue 

1204 sub_mod._buffers[key] = distribute_tensor(buffer, device_mesh, full_replicate) 

1205 

1206 

1207def _distribute_module_run_partition_and_replicate( 

1208 module: Any, 

1209 device_mesh: DeviceMesh, 

1210 partition_fn: Optional[Callable[[str, Any, DeviceMesh], None]], 

1211) -> None: 

1212 """Call optional ``partition_fn`` per ``named_modules`` and replicate remaining tensors.""" 

1213 if partition_fn is None: 

1214 for mod_name, submod in _distribute_module_named_modules(module): 

1215 _replicate_submodule_params_buffers(submod, device_mesh, module_prefix=mod_name) 

1216 return 

1217 for mod_name, submod in _distribute_module_named_modules(module): 

1218 partition_fn(mod_name, submod, device_mesh) 

1219 _replicate_submodule_params_buffers(submod, device_mesh, module_prefix=mod_name) 

1220 

1221 

1222def _distribute_module_register_input_fn( 

1223 module: Any, 

1224 device_mesh: DeviceMesh, 

1225 input_fn: Callable[..., Any], 

1226) -> None: 

1227 """Register *input_fn* as a forward pre-hook on *module* (2- or 3-arg, PyTorch-compatible).""" 

1228 num_args = len(inspect.signature(input_fn).parameters) 

1229 if num_args == 2: 

1230 warnings.warn( 

1231 "Deprecating input_fn that takes two arguments (inputs, device_mesh), " 

1232 "please use input_fn that takes in (module, inputs, device_mesh) instead!", 

1233 FutureWarning, 

1234 stacklevel=3, 

1235 ) 

1236 module.register_forward_pre_hook( 

1237 lambda _, inputs: input_fn(inputs, device_mesh) 

1238 ) 

1239 elif num_args == 3: 

1240 module.register_forward_pre_hook( 

1241 lambda mod, inputs: input_fn(mod, inputs, device_mesh) 

1242 ) 

1243 else: 

1244 raise ValueError( 

1245 f"input_fn should take in 2 or 3 arguments, but got {num_args} arguments!" 

1246 ) 

1247 

1248 

1249def _distribute_module_register_output_fn( 

1250 module: Any, 

1251 device_mesh: DeviceMesh, 

1252 output_fn: Callable[..., Any], 

1253) -> None: 

1254 """Register *output_fn* as a forward hook on *module* (2- or 3-arg, PyTorch-compatible).""" 

1255 num_args = len(inspect.signature(output_fn).parameters) 

1256 if num_args == 2: 

1257 warnings.warn( 

1258 "Deprecating output_fn that takes two arguments (outputs, device_mesh), " 

1259 "please use output_fn that takes in (module, outputs, device_mesh) instead!", 

1260 FutureWarning, 

1261 stacklevel=3, 

1262 ) 

1263 module.register_forward_hook( 

1264 lambda mod, inputs, outputs: output_fn(outputs, device_mesh) 

1265 ) 

1266 elif num_args == 3: 

1267 module.register_forward_hook( 

1268 lambda mod, inputs, outputs: output_fn(mod, outputs, device_mesh) 

1269 ) 

1270 else: 

1271 raise ValueError( 

1272 f"output_fn should take in 2 or 3 arguments, but got {num_args} arguments!" 

1273 ) 

1274 

1275 

1276def distribute_module( 

1277 module: Any, 

1278 device_mesh: Optional[DeviceMesh] = None, 

1279 partition_fn: Optional[Callable[[str, Any, DeviceMesh], None]] = None, 

1280 input_fn: Optional[Callable[..., Any]] = None, 

1281 output_fn: Optional[Callable[..., Any]] = None, 

1282) -> Any: 

1283 """PyTorch ``distribute_module`` parity: shard/replicate params and optional I/O hooks. 

1284 

1285 Unsharded parameters and buffers become fully replicated :class:`DTensor` after 

1286 ``partition_fn``. ``input_fn`` / ``output_fn`` attach only to the root *module*. 

1287 

1288 Args: 

1289 module: Root ``nn.Module``. 

1290 device_mesh: Placement mesh; if ``None``, uses ``_mesh_resources.get_current_mesh()``. 

1291 partition_fn: Per ``named_modules`` callback before replicate pass; ``None`` replicates all. 

1292 input_fn: ``(module, inputs, mesh)`` or deprecated ``(inputs, mesh)`` pre-hook. 

1293 output_fn: ``(module, outputs, mesh)`` or deprecated ``(outputs, mesh)`` forward hook. 

1294 

1295 Returns: 

1296 *module* in place, with distributed tensors where applied. 

1297 

1298 Raises: 

1299 RuntimeError: If called twice on the same *module*. 

1300 ValueError: If ``input_fn`` / ``output_fn`` arity is not 2 or 3. 

1301 

1302 Note: 

1303 XLA / ``torch_xla`` is not supported; strided device :class:`DTensor` only. 

1304 """ 

1305 if getattr(module, "_distribute_module_applied", False): 

1306 raise RuntimeError( 

1307 "distribute_module should only be called once on a module, " 

1308 "but it has already been called on this module!" 

1309 ) 

1310 device_mesh = device_mesh or _mesh_resources.get_current_mesh() 

1311 _distribute_module_run_partition_and_replicate(module, device_mesh, partition_fn) 

1312 if input_fn is not None: 

1313 _distribute_module_register_input_fn(module, device_mesh, input_fn) 

1314 if output_fn is not None: 

1315 _distribute_module_register_output_fn(module, device_mesh, output_fn) 

1316 module._distribute_module_applied = True 

1317 return module 

1318 

1319 

1320def _dtensor_init_helper( 

1321 init_op, 

1322 size, 

1323 device_mesh, 

1324 placements, 

1325 *, 

1326 rng_tracked: bool = False, 

1327 **kwargs, 

1328) -> DTensor: 

1329 """ 

1330 Helper function to create and initialize a distributed tensor. 

1331 

1332 Args: 

1333 size: Shape of the tensor. 

1334 dtype: Data type of the tensor. 

1335 device: Target device for the tensor. 

1336 requires_grad: Whether the tensor requires gradient. 

1337 rng_tracked: When ``True``, initialize via :class:`OffsetBasedRNGTracker` 

1338 so shard/replicate random semantics match PyTorch DTensor factories. 

1339 

1340 Returns: 

1341 DTensor: The initialized distributed tensor. 

1342 """ 

1343 global_shape = (size,) if isinstance(size, int) else tuple(size) 

1344 layout = _build_layout(device_mesh, placements, len(global_shape)) 

1345 if _layout_has_ragged_shard(layout): 

1346 raise NotImplementedError( 

1347 "RaggedShard tensor factories are not implemented in the DTensor metadata phase" 

1348 ) 

1349 

1350 # get local tensor shape 

1351 local_shape = compute_local_shape_and_global_offset( 

1352 size, device_mesh, placements 

1353 ) 

1354 

1355 # initialize the local tensor 

1356 if init_op is torch.full: 

1357 fill_value = kwargs.pop("fill_value", 0) 

1358 local_tensor = init_op(local_shape, fill_value, **kwargs) 

1359 elif rng_tracked: 

1360 # pylint: disable=C0415 

1361 from hyper_parallel.core.dtensor.random import is_rng_supported_mesh, OffsetBasedRNGTracker 

1362 from hyper_parallel.core.shard._op_dispatch import _OP_DISPATCHER 

1363 

1364 layout = _build_layout(device_mesh, placements, len(local_shape)) 

1365 if is_rng_supported_mesh(device_mesh): 

1366 if _OP_DISPATCHER._rng_tracker is None: 

1367 _OP_DISPATCHER._rng_tracker = OffsetBasedRNGTracker(run_state_sync=False) 

1368 with _OP_DISPATCHER._rng_tracker._distribute_region( 

1369 device_mesh, 

1370 layout.placements, 

1371 global_shape, 

1372 ): 

1373 local_tensor = init_op(local_shape, **kwargs) 

1374 else: 

1375 local_tensor = init_op(local_shape, **kwargs) 

1376 else: 

1377 local_tensor = init_op(local_shape, **kwargs) 

1378 

1379 return DTensor.from_local( 

1380 local_tensor, 

1381 device_mesh, 

1382 placements, 

1383 ) 

1384 

1385 

1386def ones( 

1387 size, 

1388 device_mesh, 

1389 placements, 

1390) -> DTensor: 

1391 """ 

1392 Returns a :class:`DTensor` filled with the scalar value 1, with the shape defined 

1393 by the variable argument ``size``. 

1394 

1395 Args: 

1396 size (Union[tuple[int], list[int], int, Tensor]): The specified shape of output tensor. Only positive integer or 

1397 tuple or Tensor containing positive integers are allowed. If it is a Tensor, 

1398 it must be a 0-D or 1-D Tensor with int32 or int64 dtypes. 

1399 

1400 Keyword args: 

1401 device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks 

1402 placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate`` 

1403 

1404 Returns: 

1405 A :class:`DTensor` object on each rank 

1406 """ 

1407 ones_ = torch.ones 

1408 return _dtensor_init_helper( 

1409 ones_, 

1410 size, 

1411 device_mesh=device_mesh, 

1412 placements=placements, 

1413 ) 

1414 

1415 

1416def empty( 

1417 size, 

1418 device_mesh, 

1419 placements, 

1420) -> DTensor: 

1421 """ 

1422 Returns a :class:`DTensor` filled with uninitialized data. The shape of the :class:`DTensor` 

1423 is defined by the variable argument ``size``. 

1424 

1425 Args: 

1426 size (Union[tuple[int], list[int], int]): The specified shape of output tensor. Can be variable numbers of 

1427 positive integers or tuple or list containing positive integers. 

1428 

1429 Keyword args: 

1430 device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks 

1431 placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate`` 

1432 

1433 Returns: 

1434 A :class:`DTensor` object on each rank 

1435 """ 

1436 empty_ = torch.empty 

1437 return _dtensor_init_helper( 

1438 empty_, 

1439 size, 

1440 device_mesh=device_mesh, 

1441 placements=placements, 

1442 ) 

1443 

1444 

1445def full( 

1446 size, 

1447 fill_value, 

1448 *, 

1449 device_mesh, 

1450 placements, 

1451) -> DTensor: 

1452 """ 

1453 Returns a :class:`DTensor` filled with ``fill_value`` according to ``device_mesh`` and 

1454 ``placements``, with the shape defined by the argument ``size``. 

1455 

1456 Args: 

1457 size (Union[tuple[int], list[int]]): The specified shape of output tensor. 

1458 fill_value (Union[numbers.Number, Tensor]): Value to fill the returned tensor. It can be a scalar number, a 0-D 

1459 Tensor, or a 1-D Tensor with only one element. 

1460 

1461 Keyword args: 

1462 device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks. 

1463 placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate`` 

1464 

1465 Returns: 

1466 A :class:`DTensor` object on each rank 

1467 """ 

1468 full_ = torch.full 

1469 return _dtensor_init_helper( 

1470 full_, 

1471 size, 

1472 fill_value=fill_value, 

1473 device_mesh=device_mesh, 

1474 placements=placements, 

1475 ) 

1476 

1477 

1478def zeros( 

1479 size, 

1480 device_mesh, 

1481 placements, 

1482) -> DTensor: 

1483 """ 

1484 Returns a :class:`DTensor` filled with the scalar value 0. 

1485 

1486 Args: 

1487 size (Union[tuple[int], list[int], int, Tensor]): The specified shape of output tensor. Only positive integer or 

1488 tuple or Tensor containing positive integers are allowed. If it is a Tensor, 

1489 it must be a 0-D or 1-D Tensor with int32 or int64 dtypes. 

1490 Keyword args: 

1491 device_mesh: :class:`DeviceMesh` type, contains the mesh info of ranks 

1492 placements: a sequence of :class:`Placement` type: ``Shard``, ``Replicate`` 

1493 

1494 Returns: 

1495 A :class:`DTensor` object on each rank 

1496 """ 

1497 zeros_ = torch.zeros 

1498 return _dtensor_init_helper( 

1499 zeros_, 

1500 size, 

1501 device_mesh=device_mesh, 

1502 placements=placements, 

1503 ) 

1504 

1505 

1506def rand( 

1507 size, 

1508 device_mesh, 

1509 placements, 

1510 **kwargs, 

1511) -> DTensor: 

1512 """ 

1513 Returns a :class:`DTensor` filled with random numbers from a uniform 

1514 distribution on ``[0, 1)``. 

1515 

1516 Args: 

1517 size: Global output shape. 

1518 device_mesh: :class:`DeviceMesh` for the distributed layout. 

1519 placements: Per-mesh-dimension :class:`Placement` values. 

1520 **kwargs: Forwarded to :func:`torch.rand` (for example ``dtype``). 

1521 

1522 Returns: 

1523 A :class:`DTensor` object on each rank. 

1524 """ 

1525 return _dtensor_init_helper( 

1526 torch.rand, 

1527 size, 

1528 device_mesh=device_mesh, 

1529 placements=placements, 

1530 rng_tracked=True, 

1531 **kwargs, 

1532 ) 

1533 

1534 

1535def randn( 

1536 size, 

1537 device_mesh, 

1538 placements, 

1539 **kwargs, 

1540) -> DTensor: 

1541 """ 

1542 Returns a :class:`DTensor` filled with random numbers from a normal 

1543 distribution with mean ``0`` and variance ``1``. 

1544 

1545 Args: 

1546 size: Global output shape. 

1547 device_mesh: :class:`DeviceMesh` for the distributed layout. 

1548 placements: Per-mesh-dimension :class:`Placement` values. 

1549 **kwargs: Forwarded to :func:`torch.randn` (for example ``dtype``). 

1550 

1551 Returns: 

1552 A :class:`DTensor` object on each rank. 

1553 """ 

1554 return _dtensor_init_helper( 

1555 torch.randn, 

1556 size, 

1557 device_mesh=device_mesh, 

1558 placements=placements, 

1559 rng_tracked=True, 

1560 **kwargs, 

1561 )