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"""Replay-phase executor.
16
17The executor executes residency schedule actions (D2H/H2D, device/host
18release) and validates replayed outputs against the warmup trace.
19Physical state transitions are delegated to
20:class:`~offload.runtime.residency.ResidencyManager`.
21"""
22
23from __future__ import annotations
24
25import logging
26from collections.abc import Callable
27from typing import Any
28
29from torch.utils._pytree import tree_flatten
30
31from hyper_parallel.auto_parallel.hyper_offload.execution.base import BaseExecutor
32from hyper_parallel.auto_parallel.hyper_offload.execution.framework import dispatch_framework_read
33from hyper_parallel.auto_parallel.hyper_offload.execution.tensor import ShadowTensor
34from hyper_parallel.auto_parallel.hyper_offload.ir.replay import OpGuide
35from hyper_parallel.auto_parallel.hyper_offload.ir.schedule import ResidencyActionType, ResidencySchedule
36from hyper_parallel.auto_parallel.hyper_offload.runtime.residency import ResidencyManager
37
38logger = logging.getLogger(__name__)
39
40
41class ReplayExecutor(BaseExecutor):
42 """Executor for the replay phase.
43
44 Executes residency schedule actions (D2H/H2D, device/host release)
45 and validates replayed outputs against the warmup trace.
46 """
47
48 def __init__(
49 self,
50 residency_manager: ResidencyManager,
51 schedule: ResidencySchedule,
52 guide: list[OpGuide],
53 ) -> None:
54 """Bind a recorded trace and select the storages requiring replay management."""
55 super().__init__(residency_manager)
56 self.native_saved_replay = False
57 self._schedule = schedule
58 self._guide = guide
59 # Transfer storage keeps wrapper identity; unrelated activations remain
60 # native. Wrapper replay can add detach and virtual FSDP-read records
61 # that native replay omits, so on_op_begin advances over those entries.
62 # Keep legacy hand-built guides on their original contract.
63 transfer_sids = {
64 action.storage_id
65 for phase in (schedule.pre, schedule.post)
66 for actions in phase.values()
67 for action in actions
68 if action.kind in (ResidencyActionType.COPY_D2H, ResidencyActionType.COPY_H2D)
69 }
70 self._managed_sids = self._select_managed_sids(guide, transfer_sids)
71 self._requires_dispatch = self._managed_sids is None or bool(transfer_sids)
72 self._replay_output_bindings = [self._managed_bindings(op.output_bindings) for op in guide]
73 self._replay_input_bindings = [
74 self._managed_bindings(op.input_bindings) if op.input_bindings is not None else None
75 for op in guide
76 ]
77 self._active_ops = [self._op_requires_management(index) for index in range(len(guide))]
78 self._framework_ops = [op.name.startswith("framework_read:") for op in guide]
79 self._dispatch_names = [op.name.removeprefix("framework_read:") for op in guide]
80 logger.info(
81 "Replay management: transfer_storages=%d, managed_storages=%s, wrapped_outputs=%d/%d",
82 len(transfer_sids),
83 len(self._managed_sids) if self._managed_sids is not None else "all",
84 sum(len(bindings) for bindings in self._replay_output_bindings),
85 sum(len(op.output_bindings) for op in guide),
86 )
87
88 @property
89 def requires_dispatch(self) -> bool:
90 """Whether replay needs tensor management for any planned transfer."""
91 return self._requires_dispatch
92
93 def _select_managed_sids(self, guide: list[OpGuide], transfer_sids: set[int]) -> set[int] | None:
94 """Retain legacy ownership and expand transfer-boundary dependencies."""
95 if any(op.input_bindings is None for op in guide):
96 return None
97 managed_sids = set(transfer_sids)
98 for op_idx, op in enumerate(guide):
99 if op.name == "detach.default" or op.name.startswith("framework_read:"):
100 actions = self._schedule.pre_actions(op_idx) + self._schedule.post_actions(op_idx)
101 if any(action.storage_id in transfer_sids for action in actions):
102 managed_sids.update(op.input_bindings.values())
103 return managed_sids
104
105 def _managed_bindings(self, bindings: dict[int, int]) -> dict[int, int]:
106 if self._managed_sids is None:
107 return bindings
108 return {index: sid for index, sid in bindings.items() if sid in self._managed_sids}
109
110 def _input_bindings(self, leaves: list[Any]) -> dict[int, int]:
111 return {
112 index: value.storage_id
113 for index, value in enumerate(leaves)
114 if isinstance(value, ShadowTensor)
115 and (self._managed_sids is None or value.storage_id in self._managed_sids)
116 }
117
118 def _op_requires_management(self, index: int) -> bool:
119 return (
120 self._managed_sids is None
121 or bool(self._replay_input_bindings[index])
122 or bool(self._replay_output_bindings[index])
123 or self._has_actions(index)
124 )
125
126 def _has_actions(self, op_idx: int) -> bool:
127 return any(
128 self._managed_sids is None or action.storage_id in self._managed_sids
129 for action in self._schedule.pre_actions(op_idx) + self._schedule.post_actions(op_idx)
130 )
131
132 def _is_elidable(self, op_idx: int) -> bool:
133 name = self._guide[op_idx].name
134 return not self._active_ops[op_idx] and (
135 name == "detach.default" or name.startswith("framework_read:")
136 )
137
138 def _next_op(self, name: str) -> int:
139 index = self.op_idx + 1
140 while (
141 index < len(self._guide)
142 and name != self._guide[index].name
143 and name != self._dispatch_names[index]
144 and self._is_elidable(index)
145 ):
146 index += 1
147 return index
148
149 def dispatch(self, func: Callable, args: tuple, kwargs: dict) -> Any:
150 """Run unrelated native operations without building ownership pytrees.
151
152 Args:
153 func: Replayed tensor operation.
154 args: Positional operation inputs.
155 kwargs: Keyword operation inputs.
156 """
157 if self.in_opaque_region:
158 return func(*args, **kwargs)
159 index = self.op_idx + 1
160 if index < len(self._guide) and func.__name__ == self._dispatch_names[index]:
161 if not self._active_ops[index]:
162 self.op_idx = index
163 return func(*args, **(kwargs or {}))
164 else:
165 index = self._next_op(func.__name__)
166 return self._dispatch_slow(func, args, kwargs or {}, index)
167
168 def _dispatch_slow(self, func: Callable, args: tuple, kwargs: dict, index: int) -> Any:
169 """Handle elided records and managed ownership boundaries."""
170 if self._is_unplanned_detach(func, args, kwargs, index):
171 return func(*args, **kwargs)
172 if index < len(self._guide) and self._framework_ops[index] and func.__name__ == self._dispatch_names[index]:
173 if not self._active_ops[index]:
174 self.op_idx = index
175 return func(*args, **(kwargs or {}))
176 self.op_idx = index - 1
177 return dispatch_framework_read(
178 self, func, args, kwargs or {}, native_inputs=self._replay_input_bindings[index] == {},
179 )
180 if (
181 index < len(self._guide)
182 and not self._active_ops[index]
183 and not func.__name__.startswith("framework_read:")
184 ):
185 if func.__name__ != self._guide[index].name:
186 raise RuntimeError(
187 f"replay operator differs at op={index}: expected={self._guide[index].name}, actual={func.__name__}"
188 )
189 self.op_idx = index
190 return func(*args, **kwargs)
191 self.op_idx = index - 1
192 return super().dispatch(func, args, kwargs)
193
194 def _is_unplanned_detach(self, func: Callable, args: tuple, kwargs: dict, index: int) -> bool:
195 """Identify checkpoint detaches without planned transfer ownership."""
196 if self._managed_sids is None or func.__name__ != "detach.default":
197 return False
198 leaves, _ = tree_flatten((args, kwargs))
199 return not self._input_bindings(leaves) and (
200 index >= len(self._guide) or self._dispatch_names[index] != "detach.default"
201 )
202
203 def execute_opaque_op(
204 self,
205 func_name: str,
206 fn: Callable,
207 args: tuple,
208 kwargs: dict,
209 ) -> Any:
210 """Run an opaque boundary and bind its native replay outputs.
211
212 Args:
213 func_name: Name recorded for the opaque boundary.
214 fn: Native callable inside the boundary.
215 args: Positional arguments.
216 kwargs: Keyword arguments.
217 """
218 if self.native_saved_replay or not self.requires_dispatch:
219 return fn(*args, **kwargs)
220 return super().execute_opaque_op(func_name, fn, args, kwargs)
221
222 # ------------------------------------------------------------------
223 # Lifecycle hooks
224 # ------------------------------------------------------------------
225
226 def on_op_begin(self, func, args, kwargs) -> None:
227 """Before op: execute pre-actions."""
228 super().on_op_begin(func, args, kwargs)
229 if self.op_idx >= len(self._guide):
230 raise RuntimeError(
231 "replay op count exceeds warmup trace: "
232 f"op_idx={self.op_idx}, "
233 f"trace_ops={len(self._guide)}, "
234 f"op={func.__name__}"
235 )
236
237 guide = self._guide[self.op_idx]
238 actual_bindings = self._input_bindings(self._last_flat_inputs[0])
239 while (
240 (
241 func.__name__ != guide.name
242 or actual_bindings != (self._replay_input_bindings[self.op_idx] or {})
243 )
244 and self._is_elidable(self.op_idx)
245 ):
246 self.op_idx += 1
247 if self.op_idx >= len(self._guide):
248 raise RuntimeError(
249 f"replay operator differs at op={self.op_idx}: actual={func.__name__}"
250 )
251 guide = self._guide[self.op_idx]
252
253 if guide.input_bindings is not None and func.__name__ != guide.name:
254 raise RuntimeError(
255 f"replay operator differs at op={self.op_idx}: expected={guide.name}, actual={func.__name__}"
256 )
257 if guide.input_bindings is not None:
258 expected_bindings = self._replay_input_bindings[self.op_idx]
259 if actual_bindings != expected_bindings:
260 raise RuntimeError(
261 f"replay input bindings differ at op={self.op_idx}: "
262 f"name={guide.name}, "
263 f"expected_bindings={expected_bindings}, "
264 f"actual_bindings={actual_bindings}"
265 )
266
267 for action in self._schedule.pre_actions(self.op_idx):
268 if action.kind == ResidencyActionType.COPY_H2D:
269 self.residency_manager.copy_h2d(action.storage_id)
270 elif action.kind == ResidencyActionType.RELEASE_HOST:
271 self.residency_manager.release_host(action.storage_id)
272 else:
273 raise RuntimeError(f"unsupported pre action {action} at op={self.op_idx}")
274
275 def on_op_end(self, result) -> Any:
276 """After op: validate output structure, shadow outputs, then execute post-actions.
277
278 The order is critical: :meth:`apply_shadows` must run **before**
279 post-actions so that output tensors are registered in the residency
280 table (via :meth:`bind`) before the scheduler tries to copy or
281 release them. The previous order (post-actions → apply_shadows)
282 caused ``COPY_D2H`` / ``RELEASE_DEVICE`` to silently skip output
283 sids that had not yet been bound, leaving stale device buffers
284 and missing host copies.
285 """
286 func = self._last_func
287 op_guide = self._guide[self.op_idx]
288 leaves, output_spec = tree_flatten(result)
289 if len(leaves) != op_guide.output_leaf_count:
290 raise RuntimeError(
291 "replay output structure differs from warmup trace: "
292 f"op_idx={self.op_idx}, "
293 f"name={op_guide.name}, "
294 f"expected_leaves={op_guide.output_leaf_count}, "
295 f"actual_leaves={len(leaves)}, "
296 f"op={func.__name__}"
297 )
298
299 # 1. Shadow outputs first — binds PhysicalBuffers so that
300 # post-actions can find and operate on them.
301 result = self.apply_shadows(
302 result,
303 self._replay_output_bindings[self.op_idx],
304 flattened=(leaves, output_spec),
305 )
306
307 # 2. Execute post-actions (COPY_D2H, RELEASE_DEVICE, RELEASE_HOST).
308 for action in self._schedule.post_actions(self.op_idx):
309 sid = action.storage_id
310 if action.kind == ResidencyActionType.COPY_D2H:
311 self.residency_manager.copy_d2h(sid)
312 elif action.kind == ResidencyActionType.RELEASE_DEVICE:
313 self.residency_manager.release_device(sid)
314 elif action.kind == ResidencyActionType.TRY_RELEASE_DEVICE:
315 self.residency_manager.try_release_device(sid)
316 elif action.kind == ResidencyActionType.RELEASE_HOST:
317 self.residency_manager.release_host(sid)
318 else:
319 raise RuntimeError(f"unsupported post action {action} at op={self.op_idx}")
320
321 # Sparse replay may execute many native ops before the next managed
322 # boundary. Do not retain its input tensors throughout that interval.
323 self._last_func = None
324 self._last_args = None
325 self._last_kwargs = None
326 self._last_flat_inputs = None
327 return result
328
329 def finish(self) -> None:
330 """Reject truncated steps as well as steps with additional operations."""
331 while self.op_idx + 1 < len(self._guide) and self._is_elidable(self.op_idx + 1):
332 self.op_idx += 1
333 if self.op_idx + 1 != len(self._guide):
334 raise RuntimeError(
335 f"replay op count differs from warmup trace: expected={len(self._guide)}, actual={self.op_idx + 1}"
336 )