Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / api / session.py: 98%
133 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"""Activation offload session built on TorchDispatchMode."""
17from __future__ import annotations
19import contextvars
20import logging
21from types import TracebackType
23import torch
24from torch.utils._python_dispatch import TorchDispatchMode, _get_current_dispatch_mode_stack
26from hyper_parallel.auto_parallel.hyper_offload.api.config import OffloadConfig
27from hyper_parallel.auto_parallel.hyper_offload.api.scope import (
28 dispatch_framework_read,
29 has_managed_inputs,
30 inside_fsdp_runtime,
31)
32from hyper_parallel.auto_parallel.hyper_offload.execution.saved_tensors import (
33 SavedNative, SavedTensorRecorder, SavedTensorReplay,
34)
35from hyper_parallel.auto_parallel.hyper_offload.execution.replay import ReplayExecutor
36from hyper_parallel.auto_parallel.hyper_offload.execution.warmup import WarmupExecutor
37from hyper_parallel.auto_parallel.hyper_offload.planning.peak import PeakResidencyPlanner
38from hyper_parallel.auto_parallel.hyper_offload.runtime.residency import ResidencyManager
40logger = logging.getLogger(__name__)
42# Context variable tracking the active OffloadSession (set on __enter__).
43_active_session: contextvars.ContextVar[OffloadSession | None] = contextvars.ContextVar("_active_session", default=None)
46def _pack_native(tensor: torch.Tensor) -> SavedNative:
47 return SavedNative(tensor.detach(), tensor._version) # pylint: disable=protected-access
50def _unpack_native(packed: SavedNative) -> torch.Tensor:
51 if packed.tensor._version != packed.version: # pylint: disable=protected-access
52 raise RuntimeError("a tensor saved for backward was modified in place")
53 return packed.tensor
56class ActivationDispatchMode(TorchDispatchMode):
57 """Dispatch mode that delegates to a :class:`BaseExecutor`.
59 The executor (warmup or replay) is selected by
60 :class:`OffloadSession` and never swapped while this mode
61 is active.
62 """
64 def __init__(self, session: OffloadSession, *, record_framework_ops: bool = False) -> None:
65 """Bind this dispatch mode to the active offload session."""
66 super().__init__()
67 self.session = session
68 self._executor = session.executor
69 self._record_framework_ops = record_framework_ops
70 self._replay_framework_ops = record_framework_ops and isinstance(session.executor, ReplayExecutor)
72 def __torch_dispatch__(self, func, types, args=(), kwargs=None): # pylint: disable=unused-argument
73 """Dispatch a torch operation."""
74 # Opaque boundaries own their inner lifetimes. Native tensors need no
75 # framework ownership check; subclasses still take the guarded path.
76 opaque = self._executor.in_opaque_region
77 if opaque and all(tensor_type is torch.Tensor for tensor_type in types):
78 return func(*args, **(kwargs or {}))
79 if self._replay_framework_ops and not opaque:
80 return self._executor.dispatch(func, args, kwargs)
81 if inside_fsdp_runtime():
82 kwargs = kwargs or {}
83 # Native redispatch may report Tensor itself (notably for detach).
84 # Neither that case nor an empty set can contain a ShadowTensor.
85 native_inputs = (
86 all(tensor_type is torch.Tensor for tensor_type in types)
87 or not has_managed_inputs(args, kwargs)
88 )
89 if native_inputs and not self._record_framework_ops:
90 return func(*args, **kwargs)
91 return dispatch_framework_read(self._executor, func, args, kwargs, native_inputs=native_inputs)
92 return self._executor.dispatch(func, args, kwargs)
95class OffloadSession:
96 """Manage warmup and replay for activation residency control.
98 Holds lifecycle state and a single active executor (:class:`WarmupExecutor`
99 or :class:`ReplayExecutor`). The executor is switched during the
100 warmup → replay transition in :meth:`__exit__`.
101 """
103 def __init__(self, config: OffloadConfig) -> None:
104 """Initialize warmup execution and the configured residency planner."""
105 self.mode: str = "warmup"
107 self.planner = config.planner if config.planner is not None else PeakResidencyPlanner()
108 self.residency_manager = ResidencyManager(
109 max_host_bytes=config.max_offload_activation_mb * 1024**2,
110 )
111 self.executor: WarmupExecutor | ReplayExecutor = WarmupExecutor(
112 residency_manager=self.residency_manager,
113 memory_limit_bytes=config.max_resident_activation_mb * 1024**2,
114 )
116 self._dispatch_context = None
117 self._session_token = None
118 self._native_replay = False
119 self._saved_recorder = None
120 self._saved_replay = None
121 self._saved_context = None
123 # ------------------------------------------------------------------
124 # Active session lookup (used by skip_offload decorator)
125 # ------------------------------------------------------------------
127 @staticmethod
128 def get_active() -> OffloadSession | None:
129 """Return the currently active OffloadSession, or ``None``."""
130 session = _active_session.get()
131 if session is not None:
132 return session
133 # Autograd carries dispatch modes into worker threads, but Python
134 # context variables are not inherited by checkpoint recomputation.
135 for mode in reversed(_get_current_dispatch_mode_stack()):
136 if isinstance(mode, ActivationDispatchMode):
137 return mode.session
138 return None
140 # ------------------------------------------------------------------
141 # Context manager
142 # ------------------------------------------------------------------
144 def __enter__(self) -> OffloadSession:
145 """Enter the runtime context."""
146 self.executor.reset()
148 self._session_token = _active_session.set(self)
149 if self._saved_replay is not None:
150 self._saved_replay.reset()
151 self.executor.native_saved_replay = True
152 self._saved_context = torch.autograd.graph.saved_tensors_hooks(
153 self._saved_replay.pack, self._saved_replay.unpack,
154 )
155 self._saved_context.__enter__()
156 return self
157 self._native_replay = self.mode == "replay" and not self.executor.requires_dispatch
158 if self._native_replay:
159 return self
160 self._dispatch_context = ActivationDispatchMode(self, record_framework_ops=True)
161 self._dispatch_context.__enter__()
162 if self.mode == "warmup":
163 self._saved_recorder = SavedTensorRecorder(self.executor)
164 pack, unpack = self._saved_recorder.pack, self._saved_recorder.unpack
165 else:
166 pack, unpack = _pack_native, _unpack_native
167 self._saved_context = torch.autograd.graph.saved_tensors_hooks(pack, unpack)
168 self._saved_context.__enter__()
169 return self
171 def close(self) -> None:
172 """Validate that the session is idle before closing; it may be reused."""
173 if self._session_token is not None:
174 raise RuntimeError("cannot close an active OffloadSession")
176 def __exit__(
177 self, exc_type: type[BaseException] | None,
178 exc_val: BaseException | None, exc_tb: TracebackType | None,
179 ) -> bool:
180 """Exit the runtime context."""
181 if self._saved_context is not None:
182 self._saved_context.__exit__(exc_type, exc_val, exc_tb)
183 self._saved_context = None
184 if self._dispatch_context is not None:
185 self._dispatch_context.__exit__(exc_type, exc_val, exc_tb)
186 self._dispatch_context = None
187 if self._session_token is not None:
188 _active_session.reset(self._session_token)
189 self._session_token = None
191 if self._saved_replay is not None:
192 self.executor.native_saved_replay = False
193 if exc_type is not None:
194 self.residency_manager.sync_all_transfers()
195 self.executor.reset()
196 self._saved_replay.reset()
197 else:
198 try:
199 self._saved_replay.finish()
200 self.residency_manager.wait_for_transfers()
201 except BaseException:
202 self.residency_manager.sync_all_transfers()
203 self.executor.reset()
204 self._saved_replay.reset()
205 raise
206 return False
208 if self._native_replay:
209 return False
211 if exc_type is not None:
212 self.residency_manager.sync_all_transfers()
213 self.executor.reset()
214 return False
216 self.residency_manager.wait_for_transfers()
218 if self.mode == "warmup":
219 trace, guide = self.executor.finish()
220 if self._saved_recorder is not None:
221 SavedTensorReplay.add_planning_hints(self._saved_recorder, trace)
222 schedule = self.planner.build(trace)
223 if self._saved_recorder is not None:
224 self._saved_replay = SavedTensorReplay.from_trace(
225 self.residency_manager, self._saved_recorder, trace, schedule,
226 )
227 # Native hooks own the complete replay contract. Retaining the
228 # operator guide and its binding dictionaries only adds host memory
229 # and garbage-collector traversal to every subsequent iteration.
230 replay_guide = guide if self._saved_replay is None else []
231 self.executor = ReplayExecutor(self.residency_manager, schedule, replay_guide)
232 self._saved_recorder = None
233 self.mode = "replay"
234 if not self.executor.requires_dispatch:
235 logger.info("HyperOffload plan has no transfers; subsequent steps use native execution")
236 else:
237 self.executor.finish()
239 return False