Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / dtensor / dtensor_base.py: 78%
153 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2025-2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""Torch ``DTensorBase``: the platform-agnostic base of :class:`DTensor`."""
16from typing import Tuple, Dict, Any, Optional
17import torch
18from torch import Tensor
19from torch._subclasses.fake_tensor import FakeTensor, unset_fake_temporarily
22def _make_shell_subclass(cls, local_tensor: Tensor) -> Tensor:
23 """Wrap ``local_tensor`` in subclass ``cls``, aliasing or shadowing its storage.
25 Real local tensors share their storage with the wrapper (the normal path,
26 byte-identical to a plain ``_make_subclass``). ``Tensor._make_subclass``
27 cannot re-wrap a FakeTensor because a FakeTensor is already a Tensor
28 subclass, so storage-less locals get a meta shell with identical metadata
29 instead — built as a :func:`_fake_local_variant` of ``cls`` so every
30 FakeTensor-specific accessor lives on that variant class and the real
31 training path never executes a fake-aware branch.
33 Args:
34 cls: The DTensor subclass to instantiate.
35 local_tensor: The local shard the wrapper represents.
37 Returns:
38 Tensor: An uninitialized ``cls`` instance (``__init_data__`` pending).
39 """
40 if isinstance(local_tensor, FakeTensor):
41 # Inside an active FakeTensorMode even meta factories return
42 # FakeTensors, which _make_subclass rejects; build the shell outside.
43 with unset_fake_temporarily():
44 shell = torch.empty_strided(
45 local_tensor.size(),
46 local_tensor.stride(),
47 dtype=local_tensor.dtype,
48 device="meta",
49 )
50 return Tensor._make_subclass(
51 _fake_local_variant(cls), shell, local_tensor.requires_grad
52 )
53 return Tensor._make_subclass(cls, local_tensor, local_tensor.requires_grad)
56_FAKE_LOCAL_VARIANTS: Dict[type, type] = {}
59def _fake_local_variant(cls: type) -> type:
60 """Return the meta-shell variant of DTensor subclass ``cls``.
62 The variant overrides exactly the accessors whose base implementation
63 assumes the wrapper owns real storage. A dedicated class isolates that
64 behaviour, so real-tensor instances resolve the unmodified base methods
65 and the hot ``grad``/``data``/``zero_grad`` paths cost nothing extra. Variants are cached per subclass and are
66 idempotent (a variant is its own variant), so ``self.__class__(...)``
67 reconstruction in ``detach``/``to``/``type`` stays type-stable, which
68 ``nn.Parameter`` requires of ``detach``.
69 """
70 if getattr(cls, "_is_fake_local_variant", False):
71 return cls
72 variant = _FAKE_LOCAL_VARIANTS.get(cls)
73 if variant is None:
74 variant = type(f"_FakeLocal{cls.__name__}", (cls,), {
75 "_is_fake_local_variant": True,
76 "is_meta_shell": _variant_is_meta_shell,
77 "grad": property(_variant_grad_get, _variant_grad_set),
78 "data": property(_variant_data_get, _variant_data_set),
79 })
80 _FAKE_LOCAL_VARIANTS[cls] = variant
81 return variant
84def _variant_is_meta_shell(self) -> bool:
85 """Meta-shell wrappers have no storage of their own."""
86 del self
87 return True
90def _variant_grad_get(self) -> Optional[Tensor]:
91 """Return the stored DTensor gradient wrapper while it owns the leaf's grad."""
92 local_grad = self._local_tensor.grad
93 wrapper = getattr(self, "_grad_dtensor_wrapper", None)
94 if wrapper is not None and wrapper._local_tensor is local_grad:
95 return wrapper
96 return local_grad
99def _variant_grad_set(self, value: Optional[Tensor]) -> None:
100 """Store DTensor gradients on the local leaf; autograd rejects meta-device grads."""
101 if isinstance(value, DTensorBase) and value.is_meta_shell():
102 self._local_tensor.grad = value._local_tensor
103 self._grad_dtensor_wrapper = value
104 return
105 self._local_tensor.grad = value
106 if getattr(self, "_grad_dtensor_wrapper", None) is not None:
107 self._grad_dtensor_wrapper = None
110def _variant_data_get(self):
111 """A meta shell owns no storage; the local tensor's data is the payload."""
112 with torch._C.DisableTorchFunctionSubclass(): # pylint: disable=not-context-manager
113 return self._local_tensor.data
116def _variant_data_set(self, value) -> None:
117 """Rebind only the local tensor; the meta shell cannot adopt device storage."""
118 local_value = value.to_local() if isinstance(value, DTensorBase) else value
119 with torch._C.DisableTorchFunctionSubclass(): # pylint: disable=not-context-manager
120 Tensor.data.__set__(self._local_tensor, local_value)
123class DTensorBase(Tensor):
124 """Base class of :class:`DTensor`: a ``torch.Tensor`` subclass that owns a local shard.
126 Holds the local shard plus the ``DeviceMesh``/``Placements`` describing how that shard
127 maps onto the global tensor, and routes every op through the distributed dispatcher.
128 """
130 def __new__(cls, local_tensor, device_mesh=None, placements=None, layout=None, shape=None):
131 """
132 Create a new DTensorBase instance.
134 Args:
135 local_tensor: The local tensor shard or another DTensorBase instance.
136 device_mesh: The device mesh describing the device topology.
137 placements: The placement strategy for each mesh dimension.
138 layout: Optional pre-built Layout reused directly by ``__init_data__``
139 (skips ``_build_layout``; see ``DTensor.from_local_with_layout``).
140 shape: Optional logical global tensor shape.
141 """
142 if isinstance(local_tensor, DTensorBase):
143 # Copy from existing DTensorBase — use alias_placements to preserve multi-axis ordering
144 t = _make_shell_subclass(cls, local_tensor._local_tensor)
145 copy_placements = local_tensor.layout.alias_placements if local_tensor.layout else local_tensor.placements
146 t.__init_data__(
147 local_tensor._local_tensor,
148 local_tensor.device_mesh,
149 copy_placements,
150 shape=getattr(local_tensor, "_global_shape", None),
151 )
152 return t
154 if device_mesh is None:
155 raise ValueError("device_mesh is None, must provide a DeviceMesh instance")
156 if placements is None:
157 raise ValueError("placements is None, must provide placements")
159 # Create Tensor subclass instance, sharing local_tensor's underlying storage
160 # (or shadowing it with a meta shell when the local is a FakeTensor).
161 t = _make_shell_subclass(cls, local_tensor)
162 t.__init_data__(local_tensor, device_mesh, placements, layout, shape)
163 return t
165 # pylint: disable=W0613
166 @classmethod
167 def __torch_function__(
168 cls,
169 func: torch._C._FunctionBase,
170 types: Tuple[type, ...],
171 args: Tuple[Any, ...] = (),
172 kwargs: Optional[Dict[str, Any]] = None
173 ) -> Any:
174 """
175 Override PyTorch's __torch_function__ to intercept tensor operations.
177 This method dispatches operations through the distributed operator dispatcher
178 to handle DTensor-specific layout inference and redistribution.
180 Args:
181 func (torch._C._FunctionBase): The PyTorch function being called.
182 types (Tuple[type, ...]): The types of tensors involved in the operation.
183 args (Tuple[Any, ...]): Positional arguments passed to the function.
184 kwargs (Optional[Dict[str, Any]]): Keyword arguments passed to the function.
186 Returns:
187 Any: The result of the dispatched operation, typically a DTensor or tuple of DTensors.
188 """
189 kwargs = kwargs or {}
190 # pylint: disable=C0415
191 from hyper_parallel.core.shard._op_dispatch import _OP_DISPATCHER
192 out = _OP_DISPATCHER.dispatch(func, args, kwargs)
193 return out
195 @property
196 def grad(self) -> Optional[Tensor]:
197 """
198 Get the gradient tensor of the local tensor.
200 Returns:
201 Optional[Tensor]: The gradient tensor, or None if no gradient is set.
202 """
203 return self._local_tensor.grad
205 @grad.setter
206 def grad(self, value: Optional[Tensor]) -> None:
207 """
208 Set the gradient tensor for the local tensor.
210 Args:
211 value (Optional[Tensor]): The gradient tensor to set, or None to clear.
212 """
213 self._local_tensor.grad = value
215 def is_meta_shell(self) -> bool:
216 """Return whether this wrapper is a storage-less meta shell.
218 Always False here; the ``_fake_local_variant`` subclass used for
219 FakeTensor locals overrides this (and the storage-touching accessors)
220 so the real-tensor path carries no fake-aware branches.
221 """
222 return False
224 @property
225 def requires_grad(self) -> bool:
226 """
227 Check if gradient computation is enabled for this tensor.
229 Returns:
230 bool: True if gradients should be computed for this tensor.
231 """
232 return self._local_tensor.requires_grad
234 @requires_grad.setter
235 def requires_grad(self, value: bool) -> None:
236 """
237 Enable or disable gradient computation for this tensor.
239 Args:
240 value (bool): True to enable gradient computation, False to disable.
241 """
242 self._local_tensor.requires_grad_(value)
243 # Sync DTensor wrapper's requires_grad
244 super().requires_grad_(value)
246 def requires_grad_(self, requires_grad: bool = True):
247 """
248 Enable or disable gradient computation in-place.
250 Args:
251 requires_grad (bool): True to enable gradient computation. Default: True.
253 Returns:
254 DTensorBase: Self for method chaining.
255 """
256 self._local_tensor.requires_grad_(requires_grad)
257 super().requires_grad_(requires_grad)
258 return self
260 @property
261 def grad_fn(self) -> Optional[torch.autograd.Function]:
262 """
263 Get the gradient function that created this tensor.
265 Returns:
266 Optional[torch.autograd.Function]: The gradient function, or None if not applicable.
267 """
268 return self._local_tensor.grad_fn
270 def grad_zero_(self):
271 """
272 Zero out the gradient tensor in-place.
274 Returns:
275 DTensorBase: Self for method chaining.
276 """
277 if self._local_tensor.grad is not None:
278 self._local_tensor.grad.zero_()
279 return self
281 def detach(self):
282 """
283 Create a detached DTensor that does not require gradient.
285 Returns:
286 DTensorBase: A new DTensor with the same data but detached from the computation graph.
287 """
288 detached_local = self._local_tensor.detach()
289 return self.__class__(
290 detached_local,
291 device_mesh=self._device_mesh,
292 placements=self._alias_placements(),
293 shape=getattr(self, "_global_shape", None),
294 )
296 def detach_(self):
297 """
298 Detach this tensor from the computation graph in-place.
300 Returns:
301 DTensorBase: Self for method chaining.
302 """
303 self._local_tensor.detach_()
304 super().detach_()
305 return self
307 # ====================== Computation graph related overrides ======================
308 @property
309 def is_leaf(self) -> bool:
310 """
311 Check if this tensor is a leaf node in the computation graph.
313 Returns:
314 bool: True if this is a leaf tensor (created by user, not by any operation).
315 """
316 return self._local_tensor.is_leaf
318 @property
319 def retains_grad(self) -> bool:
320 """
321 Check if this tensor retains its gradient during backward pass.
323 Returns:
324 bool: True if gradients are retained for non-leaf tensors.
325 """
326 return self._local_tensor.retains_grad
328 @retains_grad.setter
329 def retains_grad(self, value: bool) -> None:
330 """
331 Enable or disable gradient retention for this tensor.
333 Args:
334 value (bool): True to enable gradient retention.
335 """
336 self._local_tensor.retains_grad_(value)
338 def backward(self, gradient=None, retain_graph=None, create_graph=False) -> None:
339 """
340 Compute the gradients for this tensor.
342 Args:
343 gradient (Optional[Tensor]): The gradient of the loss w.r.t. this tensor.
344 retain_graph (Optional[bool]): Whether to retain the computation graph.
345 create_graph (bool): Whether to create a graph of the gradient computation.
346 """
347 self._local_tensor.backward(gradient, retain_graph, create_graph)
349 # ====================== Metadata related overrides (sync with local_tensor) ======================
350 @property
351 def device(self) -> torch.device:
352 """
353 Get the device on which this tensor is stored.
355 Returns:
356 torch.device: The device object (e.g., 'cuda:0', 'cpu').
357 """
358 return self._local_tensor.device
360 @property
361 # pylint: disable=C2801
362 def data(self):
363 """
364 Directory get Tensor.data relative storage.
365 After DTensor object created, there are two reference on underlying storage. (.data and ._local_tensor)
366 If not using DisableTorchFunctionSubclass, Tensor.__get__ will goto '__torch_function__',
367 and finally return '._local_tensor' storage.
368 """
369 with getattr(torch, "_C").DisableTorchFunctionSubclass(): # pylint: disable=not-context-manager
370 # Directory get Tensor.data relative storage.
371 # If not using DisableTorchFunctionSubclass, Tensor.__get__ will goto __torch_funtin
372 return Tensor.data.__get__(self, type(self))
374 @data.setter
375 # pylint: disable=C2801
376 def data(self, value):
377 """Set the underlying tensor data, extracting the local shard if a DTensor is given."""
378 local_value = value.to_local() if isinstance(value, DTensorBase) else value
379 # Tensor.data.__set__ on a Tensor subclass otherwise enters __torch_function__
380 # and only rebinds _local_tensor through DTensor dispatch.
381 with getattr(torch, "_C").DisableTorchFunctionSubclass(): # pylint: disable=not-context-manager
382 Tensor.data.__set__(self, local_value)
383 Tensor.data.__set__(self._local_tensor, local_value)
385 @property
386 def dtype(self) -> torch.dtype:
387 """
388 Get the data type of this tensor.
390 Returns:
391 torch.dtype: The data type (e.g., torch.float32, torch.int64).
392 """
393 return self._local_tensor.dtype
395 @property
396 def shape(self) -> torch.Size:
397 """
398 Get the shape of this tensor.
400 Returns:
401 torch.Size: The shape of the tensor.
402 """
403 return self._local_tensor.shape
405 def type(self, dtype=None, non_blocking=False):
406 """
407 Convert this tensor to the specified dtype.
409 Args:
410 dtype (Optional[torch.dtype]): The target dtype. If None, returns the current type string.
411 non_blocking (bool): Whether to perform the operation asynchronously. Default: False.
413 Returns:
414 Union[str, DTensorBase]: The type string if dtype is None, otherwise a new DTensor.
415 """
416 if dtype is None:
417 return self._local_tensor.type()
418 new_local = self._local_tensor.to(dtype=dtype, non_blocking=non_blocking)
419 return self.__class__(
420 new_local,
421 device_mesh=self._device_mesh,
422 placements=self._alias_placements(),
423 shape=getattr(self, "_global_shape", None),
424 )
426 def size(self, dim: Optional[int] = None):
427 """
428 Get the size of this tensor.
430 Args:
431 dim (Optional[int]): The dimension to query. If None, returns the full shape.
433 Returns:
434 Union[torch.Size, int]: The shape or size along a specific dimension.
435 """
436 return self._local_tensor.size(dim)
438 @property
439 def ndim(self) -> int:
440 """
441 Get the number of dimensions of this tensor.
443 Returns:
444 int: The number of dimensions.
445 """
446 return self._local_tensor.ndim
448 def data_ptr(self) -> int:
449 """
450 Get the pointer to the data storage of the local tensor.
452 Returns:
453 int: The memory address of the tensor's data.
454 """
455 # Force return local_tensor's data pointer (ensure address consistency)
456 return self._local_tensor.data_ptr()
458 def untyped_storage(self) -> torch.UntypedStorage:
459 """
460 Get the untyped storage of the local tensor.
462 Storage queries answer for the local shard: the wrapper either
463 aliases the same storage (real locals) or holds a storage-less meta
464 shell (FakeTensor locals).
466 Returns:
467 The local tensor's untyped storage.
468 """
469 return self._local_tensor.untyped_storage()
471 def numel(self) -> int:
472 """
473 Get the total number of elements in this tensor.
475 Returns:
476 int: The total number of elements.
477 """
478 return self._local_tensor.numel()
480 # ====================== Auxiliary print ======================
481 def _alias_placements(self):
482 """Return alias_placements from layout, falling back to _placements."""
483 if hasattr(self, '_layout') and self._layout is not None:
484 return self._layout.alias_placements
485 return self._placements
487 def to(self, *args, **kwargs):
488 """Move the DTensor to a different device or dtype.
490 This method overrides the base Tensor.to() to properly reconstruct
491 a DTensor with device_mesh and placements preserved. Uses _make_subclass
492 to avoid issues with Parameter subclasses that don't accept extra kwargs.
494 Args:
495 *args: Arguments passed to the underlying tensor's to() method.
496 **kwargs: Keyword arguments for the tensor conversion.
498 Returns:
499 DTensorBase: A new DTensor with the converted local tensor.
500 """
501 new_local = self._local_tensor.to(*args, **kwargs)
502 new_dt = _make_shell_subclass(type(self), new_local)
503 new_dt.__init_data__(
504 new_local,
505 self._device_mesh,
506 self._alias_placements(),
507 shape=getattr(self, "_global_shape", None),
508 )
509 return new_dt
511 def __repr__(self) -> str:
512 return (
513 f"DTensor(\n"
514 f" local_tensor={self._local_tensor},\n"
515 f" device_mesh={self._device_mesh},\n"
516 f" placements={self._placements},\n"
517 f" layout={getattr(self, '_layout', None)},\n"
518 f" device={self.device},\n"
519 f" dtype={self.dtype},\n"
520 f" requires_grad={self.requires_grad},\n"
521 f" grad={self.grad},\n"
522 f" is_leaf={self.is_leaf},\n"
523 f" data_ptr={self.data_ptr()}\n"
524 f")"
525 )