Coverage for  / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / execution / base.py: 100%

123 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"""Base executor definition.""" 

16 

17from __future__ import annotations 

18 

19import logging 

20import weakref 

21from abc import ABC, abstractmethod 

22from collections import defaultdict 

23from collections.abc import Callable 

24from typing import TYPE_CHECKING, Any 

25 

26import torch 

27from torch.utils._pytree import TreeSpec, tree_flatten, tree_unflatten 

28 

29from hyper_parallel.auto_parallel.hyper_offload.execution.tensor import ShadowTensor 

30 

31if TYPE_CHECKING: 

32 from hyper_parallel.auto_parallel.hyper_offload.runtime.residency import ResidencyManager 

33 

34logger = logging.getLogger(__name__) 

35 

36 

37class OpaqueRegionStart(torch.autograd.Function): 

38 """Autograd function to mark the start of an opaque region.""" 

39 

40 @staticmethod 

41 def forward(ctx: Any, executor: BaseExecutor, func_name: str, dummy: torch.Tensor, *inputs: Any) -> Any: 

42 """Forward pass for the start boundary.""" 

43 ctx.executor = executor 

44 ctx.func_name = func_name 

45 return (dummy,) + inputs 

46 

47 @staticmethod 

48 def backward(ctx: Any, grad_dummy: Any, *grad_inputs: Any) -> Any: # pylint: disable=unused-argument 

49 """Backward pass for the start boundary.""" 

50 executor = ctx.executor 

51 executor.exit_opaque_region() 

52 

53 # Reconstruct the backward op using on_op_end. 

54 # Outputs of the backward op are grad_inputs. 

55 # func/args/kwargs were cached by on_op_begin in OpaqueRegionEnd.backward. 

56 # on_op_end already shadows via apply_shadows and caches the bindings, 

57 # so we can use its return value directly. 

58 grad_inputs = executor.on_op_end(grad_inputs) 

59 

60 return (None, None, None) + tuple(grad_inputs) 

61 

62 

63class OpaqueRegionEnd(torch.autograd.Function): 

64 """Autograd function to mark the end of an opaque region.""" 

65 

66 @staticmethod 

67 def forward( # pylint: disable=unused-argument 

68 ctx: Any, executor: BaseExecutor, func_name: str, dummy: torch.Tensor, *outputs: Any, 

69 ) -> Any: 

70 """Forward pass for the end boundary. 

71 

72 Wraps raw tensors into :class:`ShadowTensor` **inside** the 

73 autograd boundary. This is required for the autograd engine to 

74 correctly link tensor-subclass outputs into the computation graph 

75 (subclass fixup). The wrapping happens here instead of in 

76 :meth:`execute_opaque_op` so that :meth:`on_op_end` always 

77 receives raw tensors regardless of execution path. 

78 """ 

79 ctx.executor = executor 

80 ctx.func_name = func_name 

81 # 'outputs' is a flat tuple of tensors passed via .apply(*flat_res). 

82 # on_op_end has already been called and cached output_bindings 

83 # via apply_shadows; use them to avoid a redundant traversal. 

84 # pylint: disable=protected-access 

85 return tuple(executor.apply_shadows(outputs, executor._last_output_bindings)) 

86 

87 @staticmethod 

88 def backward(ctx: Any, *grad_outputs: Any) -> Any: 

89 """Backward pass for the end boundary.""" 

90 executor = ctx.executor 

91 

92 def bwd_dummy(*_args: Any, **_kwargs: Any) -> Any: 

93 """Dummy backward function that records the op boundary.""" 

94 

95 bwd_dummy.__name__ = ctx.func_name + "_bwd" 

96 

97 executor.on_op_begin(bwd_dummy, grad_outputs, {}) 

98 

99 executor.enter_opaque_region() 

100 return (None, None, torch.zeros(1)) + grad_outputs 

101 

102 

103class BaseExecutor(ABC): 

104 """Abstract base class for execution phases (warmup or replay). 

105 

106 Executors implement phase-specific lifecycle callbacks. Raw PyTorch 

107 dispatch mechanics are handled by :class:`ActivationDispatchMode`. 

108 """ 

109 

110 def __init__( 

111 self, 

112 residency_manager: ResidencyManager, 

113 ) -> None: 

114 """Bind residency management and initialize operator tracing state.""" 

115 self.residency_manager = residency_manager 

116 #: sid -> WeakSet of alive shadows (used only for ``retained_sids`` 

117 #: computation at the end of warmup. 

118 self._alive_shadows: dict[int, weakref.WeakSet[ShadowTensor]] = defaultdict(weakref.WeakSet) 

119 self.op_idx: int = -1 

120 self._opaque_depth: int = 0 

121 

122 # Cached by on_op_begin for use in on_op_end. 

123 self._last_func = None 

124 self._last_args = None 

125 self._last_kwargs = None 

126 self._last_flat_inputs = None 

127 # Cached by apply_shadows for use in autograd boundaries. 

128 self._last_output_bindings: dict[int, int] | None = None 

129 

130 @property 

131 def in_opaque_region(self) -> bool: 

132 """Return True if the executor is currently inside an opaque region.""" 

133 return self._opaque_depth > 0 

134 

135 def enter_opaque_region(self) -> None: 

136 """Enter an opaque region where fine-grained tracing is suspended.""" 

137 self._opaque_depth += 1 

138 

139 def exit_opaque_region(self) -> None: 

140 """Exit an opaque region.""" 

141 self._opaque_depth -= 1 

142 

143 def execute_opaque_op(self, func_name: str, fn: Callable, args: tuple, kwargs: dict) -> Any: 

144 """Execute a function as a single virtual op. 

145 

146 Wraps the function execution into a single "virtual op" in the 

147 execution trace, while suspending fine-grained tracing for 

148 internal operations. 

149 

150 The lifecycle hook order is: 

151 

152 1. :meth:`on_op_begin` — pre-actions. 

153 2. Opaque region (inner ops bypass lifecycle hooks). 

154 3. :meth:`on_op_end` — trace recording with **raw** tensors 

155 (consistent with :meth:`dispatch`). 

156 4. :meth:`OpaqueRegionEnd` — autograd boundary that wraps 

157 outputs into :class:`ShadowTensor` **inside** the autograd 

158 function (required for correct subclass graph linkage). 

159 

160 Steps 3 and 4 happen **inside** the opaque region so that any 

161 incidental dispatch triggered by the autograd engine during 

162 :meth:`OpaqueRegionEnd.apply` does not invoke lifecycle hooks. 

163 """ 

164 if self.in_opaque_region: 

165 return fn(*args, **kwargs) 

166 

167 def fwd_dummy(*_a: Any, **_kw: Any) -> Any: 

168 """Dummy forward function that records the op boundary.""" 

169 

170 fwd_dummy.__name__ = func_name + "_fwd" 

171 

172 self.enter_opaque_region() 

173 try: 

174 self.on_op_begin(fwd_dummy, args, kwargs) 

175 

176 # Inject a dummy tensor to ensure backward graph continuity 

177 dummy = torch.zeros(1, requires_grad=True) 

178 flat_args, spec_args = tree_flatten((args, kwargs)) 

179 

180 # Boundary 1: Wrap inputs to delay backward virtual step exit 

181 out_start = OpaqueRegionStart.apply(self, func_name, dummy, *flat_args) 

182 dummy_out = out_start[0] 

183 flat_args_out = out_start[1:] 

184 

185 args_out, kwargs_out = tree_unflatten(flat_args_out, spec_args) 

186 

187 result = fn(*args_out, **kwargs_out) 

188 

189 # Lifecycle: After op — record trace with RAW tensors. 

190 self.on_op_end(result) 

191 

192 # Boundary 2: Wrap outputs inside autograd (shadowing must 

193 # happen inside the autograd Function for the engine to 

194 # correctly link ShadowTensor subclasses into the graph). 

195 flat_res, spec_res = tree_flatten(result) 

196 out_end = OpaqueRegionEnd.apply(self, func_name, dummy_out, *flat_res) 

197 result_unflat = tree_unflatten(out_end, spec_res) 

198 finally: 

199 self.exit_opaque_region() 

200 

201 return result_unflat 

202 

203 # ------------------------------------------------------------------ 

204 # Dispatch (template method) 

205 # ------------------------------------------------------------------ 

206 

207 def dispatch(self, func: Callable[..., Any], args: tuple, kwargs: dict) -> Any: 

208 """Dispatch *func* with *args*/*kwargs*. 

209 

210 When the executor is inside an opaque region (e.g. executing the 

211 internals of a virtual op), *func* is called directly, 

212 **skipping** the lifecycle hooks 

213 (:meth:`on_op_begin` / :meth:`on_op_end`) since those 

214 boundaries are managed by ``OpaqueRegionStart`` / ``OpaqueRegionEnd``. 

215 

216 Otherwise the standard slow-path is taken: 

217 

218 1. :meth:`on_op_begin` — pre-actions (prefetch, etc.). 

219 2. ``func(*args, **kwargs)`` — raw execution. 

220 3. :meth:`on_op_end` — trace recording, post-actions **and** 

221 :class:`ShadowTensor` wrapping (single pass). 

222 """ 

223 if self.in_opaque_region: 

224 return func(*args, **kwargs) 

225 

226 self.on_op_begin(func, args, kwargs) 

227 result = func(*args, **kwargs) 

228 return self.on_op_end(result) 

229 

230 # ------------------------------------------------------------------ 

231 # Lifecycle hooks 

232 # ------------------------------------------------------------------ 

233 

234 def on_op_begin(self, func: Callable[..., Any], args: tuple, kwargs: dict) -> None: 

235 """Lifecycle callback before the operator is executed. 

236 

237 Caches *func*, *args*, *kwargs* so that :meth:`on_op_end` 

238 can access them via ``self._last_func`` etc. Subclasses that 

239 override this method **must** call ``super().on_op_begin(...)`` 

240 to maintain the cache. 

241 """ 

242 self._last_func = func 

243 self._last_args = args 

244 self._last_kwargs = kwargs 

245 self._last_flat_inputs = tree_flatten((args, kwargs)) 

246 self.op_idx += 1 

247 

248 @abstractmethod 

249 def on_op_end(self, result) -> Any: 

250 """Lifecycle callback after the operator is executed. 

251 

252 Responsible for trace recording, phase-specific post-actions, 

253 **and** shadow wrapping. Must return the (possibly shadowed) 

254 result tree so that :meth:`dispatch` can return it directly. 

255 

256 The op's function and arguments are available via 

257 ``self._last_func``, ``self._last_args``, ``self._last_kwargs`` 

258 (cached by :meth:`on_op_begin`). 

259 

260 Subclasses should call :meth:`apply_shadows` with the bindings 

261 they have already computed (e.g. from the tracker or the guide) 

262 to avoid redundant traversal. 

263 """ 

264 

265 def apply_shadows( 

266 self, result: Any, bindings: dict[int, int], 

267 *, flattened: tuple[list, TreeSpec] | None = None, 

268 ) -> Any: 

269 """Replace result tensors with ShadowTensor instances per an explicit bindings map. 

270 

271 Subclasses that have already computed the ``leaf_index → sid`` 

272 mapping (e.g. during trace recording) pass it here to avoid a 

273 redundant second traversal and SID re-resolution. 

274 

275 Caches *bindings* in ``_last_output_bindings`` for use by autograd 

276 boundaries (:class:`OpaqueRegionEnd`) that need to shadow outputs 

277 after :meth:`on_op_end` has already returned. 

278 

279 Args: 

280 result: The raw output pytree. 

281 bindings: Mapping ``leaf_index → storage_id``. Only leaves 

282 whose index appears in the map are shadowed. 

283 flattened: Reuse the current output traversal when already available. 

284 

285 Returns: 

286 A pytree of the same structure as *result* with eligible 

287 tensors replaced by :class:`ShadowTensor`. 

288 

289 """ 

290 self._last_output_bindings = bindings 

291 if not bindings: 

292 return result 

293 leaves, tree_spec = flattened if flattened is not None else tree_flatten(result) 

294 shadowed = list(leaves) 

295 for idx, leaf in enumerate(leaves): 

296 if idx in bindings and isinstance(leaf, torch.Tensor): 

297 shadowed[idx] = self.make_shadow(bindings[idx], leaf) 

298 result = tree_unflatten(shadowed, tree_spec) 

299 self._last_output_bindings = bindings 

300 return result 

301 

302 # ------------------------------------------------------------------ 

303 # Orchestration helper (output wrapping) 

304 # ------------------------------------------------------------------ 

305 

306 @property 

307 def retained_sids(self) -> set[int]: 

308 """Return the set of storage IDs that still have alive shadows.""" 

309 return {sid for sid, shadows in self._alive_shadows.items() if shadows} 

310 

311 def make_shadow(self, storage_id: int, tensor: torch.Tensor) -> Any: 

312 """Register physical storage, create shadow, and track logically. 

313 

314 Composes: 

315 #. :meth:`ResidencyManager.bind` — physical registration. 

316 #. :class:`ShadowTensor` construction. 

317 #. Tracking in ``_alive_shadows`` for ``retained_sids``. 

318 

319 Args: 

320 storage_id: Physical storage ID. 

321 tensor: The device-resident tensor to shadow. 

322 

323 Returns: 

324 The original *tensor* replaced by a :class:`ShadowTensor`, 

325 or the same shadow updated in-place for mutation. 

326 

327 """ 

328 with torch.utils._python_dispatch._disable_current_modes(): # pylint: disable=protected-access 

329 if isinstance(tensor, ShadowTensor): 

330 return tensor 

331 

332 buffer = self.residency_manager.bind(storage_id, tensor) 

333 shadow = ShadowTensor(tensor, buffer, storage_id) 

334 self._alive_shadows[storage_id].add(shadow) 

335 return shadow 

336 

337 def reset(self) -> None: 

338 """Reset per-cycle state before a new pass.""" 

339 self._opaque_depth = 0 

340 self.op_idx = -1 

341 self._alive_shadows.clear() 

342 self._last_func = None 

343 self._last_args = None 

344 self._last_kwargs = None 

345 self._last_flat_inputs = None 

346 self._last_output_bindings = None 

347 self.residency_manager.clear_runtime()