Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / execution / tensor.py: 100%
32 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 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"""Shadow tensor.
17This module provides: :class:`ShadowTensor` — a :class:`torch.Tensor` subclass that
18resolves a view of its :class:`PhysicalBuffer`'s storage on every dispatch.
19"""
21from __future__ import annotations
23from typing import Any
25import torch
26from torch.utils._pytree import tree_map
28from hyper_parallel.auto_parallel.hyper_offload.runtime.residency import PhysicalBuffer
31class ShadowTensor(torch.Tensor):
32 """Tensor subclass that resolves a device view on demand.
34 The shadow uses :meth:`PhysicalBuffer.device_storage` to obtain the
35 raw device storage on every :meth:`resolve` call and creates a
36 fresh tensor view from it. **No cached reference is kept**, so the
37 shadow never prevents the underlying storage from being freed.
39 Because :class:`ShadowTensor` is created via
40 :meth:`torch.Tensor._make_wrapper_subclass`, it carries all tensor
41 metadata ("dtype", "size", "stride", "storage_offset",
42 "device") directly.
43 """
45 @staticmethod
46 def __new__(
47 cls,
48 elem: torch.Tensor,
49 buffer: PhysicalBuffer,
50 storage_id: int,
51 ) -> "ShadowTensor":
52 """Create a new instance using *elem*'s metadata."""
53 return torch.Tensor._make_wrapper_subclass(
54 cls,
55 elem.size(),
56 strides=elem.stride(),
57 storage_offset=elem.storage_offset(),
58 dtype=elem.dtype,
59 layout=elem.layout,
60 device=elem.device,
61 requires_grad=elem.requires_grad,
62 )
64 def __init__( # pylint: disable=unused-argument
65 self,
66 elem: torch.Tensor,
67 buffer: PhysicalBuffer,
68 storage_id: int,
69 ) -> None:
70 """Bind a physical buffer and its tracked storage identity."""
71 self._buffer = buffer
72 self._storage_id = storage_id
74 # ------------------------------------------------------------------
75 # Public properties
76 # ------------------------------------------------------------------
78 @property
79 def storage_id(self) -> int:
80 """Storage ID of the underlying physical block."""
81 return self._storage_id
83 # ------------------------------------------------------------------
84 # Resolution (on every call)
85 # ------------------------------------------------------------------
87 def resolve(self) -> torch.Tensor:
88 """Return a device-resident view of the physical storage.
90 1. Calls :meth:`PhysicalBuffer.device_storage` to obtain the
91 raw device storage (demand-paging from host if needed).
92 2. Builds a fresh tensor view from the shadow's cached metadata.
93 3. Returns the view — no long-lived reference is kept.
94 """
95 storage = self._buffer.device_storage()
96 result = torch.empty(0, dtype=self.dtype, device=self.device)
97 result.set_(storage, self.storage_offset(), self.size(), self.stride())
98 return result
100 # ------------------------------------------------------------------
101 # PyTorch dispatch
102 # ------------------------------------------------------------------
104 @classmethod
105 def __torch_dispatch__(cls, func, types, args=(), kwargs=None): # pylint: disable=unused-argument
106 """Dispatch a torch operation."""
107 kwargs = kwargs or {}
108 resolved: dict[int, torch.Tensor] = {}
110 def unwrap(value: Any) -> Any:
111 if isinstance(value, ShadowTensor):
112 if id(value) not in resolved:
113 resolved[id(value)] = value.resolve()
114 return resolved[id(value)]
115 return value
117 with torch._C._DisableTorchDispatch(): # pylint: disable=protected-access
118 return func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs))