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"""Warmup-phase executor.
16
17During warmup, the executor records the execution trace while applying
18online greedy eviction to keep device memory within budget. Every
19input tensor that was evicted in an earlier op is faulted back
20synchronously (demand-paging) before dispatch.
21
22Physical state transitions are delegated to
23:class:`~offload.runtime.residency.ResidencyManager`.
24"""
25
26from __future__ import annotations
27
28import logging
29from typing import Any, Callable
30
31import torch
32from torch.utils._pytree import tree_flatten
33
34from hyper_parallel.auto_parallel.hyper_offload.execution.base import BaseExecutor
35from hyper_parallel.auto_parallel.hyper_offload.runtime.timer import DeviceTimer
36from hyper_parallel.auto_parallel.hyper_offload.execution.tensor import ShadowTensor
37from hyper_parallel.auto_parallel.hyper_offload.execution.warmup.tracker import ActivationTracker
38from hyper_parallel.auto_parallel.hyper_offload.ir.replay import OpGuide
39from hyper_parallel.auto_parallel.hyper_offload.ir.trace import AccessKind, ActivationTrace, StorageAccess, TraceOp
40from hyper_parallel.auto_parallel.hyper_offload.runtime.bandwidth import profile_transfer_bandwidth
41from hyper_parallel.auto_parallel.hyper_offload.runtime.residency import ResidencyManager
42
43logger = logging.getLogger(__name__)
44
45
46def iter_tensors(value: Any) -> list[torch.Tensor]:
47 """Return tensor leaves from an arbitrary pytree."""
48 leaves, _ = tree_flatten(value)
49 return [leaf for leaf in leaves if isinstance(leaf, torch.Tensor)]
50
51
52class WarmupExecutor(BaseExecutor):
53 """Executor for the warmup phase.
54
55 Records the execution trace while applying online greedy eviction
56 to keep device memory within the configured budget. Evicts the
57 **oldest** activations first when the memory budget is exceeded
58 (oldest-first within the same op, largest-sized entries are
59 preferred as tie-breaker to minimise eviction count).
60 """
61
62 def __init__(
63 self,
64 residency_manager: ResidencyManager,
65 memory_limit_bytes: int,
66 ) -> None:
67 """Initialize activation tracking under the device-residency budget."""
68 super().__init__(residency_manager)
69 self._memory_limit_bytes = memory_limit_bytes
70 self._tracker = ActivationTracker()
71 self._timer = DeviceTimer()
72 self._guide: list[OpGuide] = []
73 self._ops: list[TraceOp] = []
74 self._input_bindings = {}
75 self._framework_allocation_bytes = 0
76 #: sid -> the op index that first produced this activation.
77 self._sid_produced_at_op: dict[int, int] = {}
78
79 # ------------------------------------------------------------------
80 # Eviction policy
81 # ------------------------------------------------------------------
82
83 def _enforce_budget(self, protected_sids: set[int]) -> None:
84 """Evict warmup activations until resident bytes fit the configured budget."""
85 # The residency table owns buffers, not tensor lifetimes. Retire dead
86 # temporaries before considering live activations for host offload.
87 for sid, shadows in tuple(self._alive_shadows.items()):
88 if not shadows and sid not in protected_sids:
89 self.residency_manager.release_device(sid)
90 self.residency_manager.release_host(sid)
91 del self._alive_shadows[sid]
92 self._sid_produced_at_op.pop(sid, None)
93 while self.residency_manager.resident_bytes > self._memory_limit_bytes:
94 # Greedy: evict oldest first; within the same op, evict largest first.
95 victim_sid: int | None = None
96 victim_key: tuple[int, int] | None = None
97
98 for sid, produced_at_op in self._sid_produced_at_op.items():
99 if sid in protected_sids:
100 continue
101 size = self.residency_manager.device_resident_size(sid)
102 if size is None:
103 continue
104 key = (produced_at_op, -size)
105 if victim_key is None or key < victim_key:
106 victim_key = key
107 victim_sid = sid
108
109 if victim_sid is None:
110 raise RuntimeError(
111 "Warmup memory budget exceeded but no evictable activation found. "
112 f"resident_bytes={self.residency_manager.resident_bytes}, "
113 f"limit={self._memory_limit_bytes}, "
114 f"protected_sids={protected_sids}"
115 )
116
117 self.residency_manager.copy_d2h(victim_sid)
118 self.residency_manager.release_device(victim_sid)
119
120 # ------------------------------------------------------------------
121 # Lifecycle hooks
122 # ------------------------------------------------------------------
123
124 def on_op_begin(self, func, args, kwargs) -> None:
125 """Before op: enforce memory budget and fault inputs back to device."""
126 super().on_op_begin(func, args, kwargs)
127
128 protected_sids: set[int] = set()
129 for t in iter_tensors((args, kwargs)):
130 if (sid := self._tracker.get_activation_sid(t)) is not None:
131 protected_sids.add(sid)
132 self._enforce_budget(protected_sids)
133
134 self._input_bindings = {
135 index: value.storage_id
136 for index, value in enumerate(self._last_flat_inputs[0])
137 if isinstance(value, ShadowTensor)
138 }
139 self._timer.start()
140
141 def on_op_end(self, result) -> Any:
142 """After op: record trace, residency metadata, and return shadowed result."""
143 op_duration_ms = self._timer.stop()
144
145 func, args, kwargs = self._last_func, self._last_args, self._last_kwargs
146
147 self._tracker.register_op_activations(iter_tensors((args, kwargs)), iter_tensors(result))
148
149 op = TraceOp(name=func.__name__, duration_ms=op_duration_ms)
150
151 mutated_tensor_ids = self._mutated_tensor_ids(func, args)
152
153 seen: set[tuple[int, AccessKind]] = set()
154
155 # --- Input accesses ---
156 for t in iter_tensors((args, kwargs)):
157 sid = self._tracker.get_activation_sid(t)
158 if sid is None:
159 continue
160 is_mutated = id(t) in mutated_tensor_ids
161 kind = AccessKind.WRITE if is_mutated else AccessKind.READ
162 if (sid, kind) not in seen:
163 seen.add((sid, kind))
164 op.accesses.append(StorageAccess(self.op_idx, sid, kind))
165
166 # --- Output accesses + bindings ---
167 leaves, output_spec = tree_flatten(result)
168 output_bindings: dict[int, int] = {}
169
170 for leaf_index, t in enumerate(leaves):
171 if not isinstance(t, torch.Tensor):
172 continue
173 sid = self._tracker.get_activation_sid(t)
174 if sid is None:
175 continue
176
177 if (sid, AccessKind.WRITE) not in seen:
178 seen.add((sid, AccessKind.WRITE))
179 op.accesses.append(StorageAccess(self.op_idx, sid, AccessKind.WRITE))
180
181 # Track the op that first produced this activation (used by
182 # eviction policy: oldest-first).
183 if sid not in self._sid_produced_at_op:
184 self._sid_produced_at_op[sid] = self.op_idx
185
186 output_bindings[leaf_index] = sid
187
188 guide = OpGuide(
189 name=func.__name__,
190 output_leaf_count=len(leaves),
191 output_bindings=output_bindings,
192 input_bindings=self._input_bindings,
193 )
194
195 self._ops.append(op)
196 self._guide.append(guide)
197
198 return self.apply_shadows(result, output_bindings, flattened=(leaves, output_spec))
199
200 @staticmethod
201 def _mutated_tensor_ids(func: Callable, args: tuple) -> set[int]:
202 """Identify write inputs from the operator schema."""
203 mutated_tensor_ids: set[int] = set()
204 if hasattr(func, "_schema") and func._schema.is_mutable: # pylint: disable=protected-access
205 flat_args = iter_tensors((args, {}))
206 for idx, arg_info in enumerate(func._schema.arguments): # pylint: disable=protected-access
207 if (
208 arg_info.alias_info is not None
209 and arg_info.alias_info.is_write
210 and idx < len(flat_args)
211 ):
212 mutated_tensor_ids.add(id(flat_args[idx]))
213
214 return mutated_tensor_ids
215
216 def record_framework_allocation(self, size_bytes: int) -> None:
217 """Remember framework workspace sizes without adopting their storage.
218
219 Args:
220 size_bytes: Fresh storage allocated by one framework operation.
221 """
222 self._framework_allocation_bytes = max(self._framework_allocation_bytes, size_bytes)
223
224 def finish(self) -> tuple[ActivationTrace, list[OpGuide]]:
225 """Finish warmup and return recorded trace and replay guide."""
226 d2h, h2d = profile_transfer_bandwidth()
227
228 trace = ActivationTrace(
229 ops=list(self._ops),
230 storage_sizes=self._tracker.storage_sizes,
231 retained_sids=set(self.retained_sids),
232 memory_limit_bytes=self._memory_limit_bytes,
233 d2h_bandwidth_gbps=d2h,
234 h2d_bandwidth_gbps=h2d,
235 framework_allocation_bytes=self._framework_allocation_bytes,
236 )
237 guide = self._guide
238
239 self.reset()
240 return trace, guide
241
242 def reset(self) -> None:
243 """Reset."""
244 self._sid_produced_at_op.clear()
245 self._ops = []
246 self._guide = []
247 self._input_bindings = {}
248 self._framework_allocation_bytes = 0
249 self._tracker.clear_activations()
250 super().reset()