Diff Coverage

Diff: origin/master...HEAD, staged and unstaged changes

Source File Diff Coverage (%) Missing Lines
hyper_parallel/auto_parallel/hyper_offload/api/config.py 45.5% 51-56
hyper_parallel/auto_parallel/hyper_offload/api/scope.py 52.6% 35,41,48-54
hyper_parallel/auto_parallel/hyper_offload/api/session.py 14.1% 47,51-53,68-70,76-82,85,89-92,107,118-121,130-132,135-138,149-152,155-160,162-164,166-168,173-174,181-183,191-196,198-206,208-209,220-221,223-224,230-232,234-235,237
hyper_parallel/auto_parallel/hyper_offload/execution/base.py 31.2% 126,245,290-293,342-346
hyper_parallel/auto_parallel/hyper_offload/execution/framework.py 13.0% 35,37,45-48,53,58-59,61-65,80,82,88-92,96-99,101,107-118,120-121
hyper_parallel/auto_parallel/hyper_offload/execution/replay/executor.py 15.9% 56,63,70-73,77-80,91,95-103,106-108,111,119,127,133-134,139-140,146-147,157-163,165-166,170-177,180,185-186,189-192,196-199,218-220,237-239,246-248,251,253-254,257-260,270-271,288,301,314-315,323-326,331-334
hyper_parallel/auto_parallel/hyper_offload/execution/saved_tensors.py 23.0% 48,60-63,71,73-76,84-88,110-112,140-158,168-185,190-201,205-209,213,215,220,224-225,228,232-236,250-257,261,264-267,272-277,284,287-296,300-301,304-307,309-310,314-317,319,321-323,326-329,333-340,343-345,353-377,379-383,386-391,394-397,400-404,412-415,417-432,435-436,440-445
hyper_parallel/auto_parallel/hyper_offload/execution/tensor.py 16.7% 108,112-114,118
hyper_parallel/auto_parallel/hyper_offload/execution/warmup/executor.py 18.5% 74-75,87-92,134,151,167,198,203-207,212,214,222,247-248
hyper_parallel/auto_parallel/hyper_offload/ir/replay.py 100%  
hyper_parallel/auto_parallel/hyper_offload/ir/schedule.py 100%  
hyper_parallel/auto_parallel/hyper_offload/ir/trace.py 100%  
hyper_parallel/auto_parallel/hyper_offload/planning/__init__.py 100%  
hyper_parallel/auto_parallel/hyper_offload/planning/_peak_model.py 39.6% 57-64,67-86,89
hyper_parallel/auto_parallel/hyper_offload/planning/communication_mask.py 21.7% 53-55,58,61-62,64-65,68-76,80-81,84-93,106-108,114-117,120-122,125-126,141,146-149,152-159,169-179
hyper_parallel/auto_parallel/hyper_offload/planning/peak.py 21.6% 56,59-64,74-76,78,80,86,88,96-102,104,109-113,117-123,131-132,136-137,140,143-147,154-156,161,164,169-171,193-197,200,213-217,221-223,227-228,240-246,249-252,255,259,263-265,270,279,283
hyper_parallel/auto_parallel/hyper_offload/runtime/residency.py 13.6% 163,177,207-208,214,326-327,335,361-369,384-385
hyper_parallel/trainer/base.py 6.2% 616-620,902-903,1265,1318-1320,1322-1323,1326-1327
hyper_parallel/trainer/config/trainer.py 28.6% 106-110
hyper_parallel/auto_parallel/hyper_offload/api/config.py
47
48
49
50
51
52
53
54
55
56
    enable: bool = False

    def __post_init__(self) -> None:
        """Validate budgets before training allocates model memory."""
        if not isinstance(self.enable, bool):
            raise TypeError("hyper_offload.enable must be a bool")
        for name in ("max_resident_activation_mb", "max_offload_activation_mb"):
            value = getattr(self, name)
            if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
                raise ValueError(f"hyper_offload.{name} must be a positive integer")
hyper_parallel/auto_parallel/hyper_offload/api/scope.py
31
32
33
34
35
36
37
38
39
def has_managed_inputs(args: tuple, kwargs: dict) -> bool:
    """Return whether framework code is consuming a tracked activation."""
    # This is a predicate: rebuilding every argument container dominates the
    # framework's otherwise metadata-only gradient view operations.
    return any(isinstance(value, ShadowTensor) for value in tree_iter((args, kwargs)))


@lru_cache(maxsize=256)
def _is_fsdp_module(module_name: str) -> bool:
37
38
39
40
41
42
43
44

@lru_cache(maxsize=256)
def _is_fsdp_module(module_name: str) -> bool:
    """Cache only immutable classification, never the live calling context."""
    return module_name.startswith((
        "hyper_parallel.core.fully_shard.", "torch.distributed.fsdp._fully_shard.",
    ))

44
45
46
47
48
49
50
51
52
53
54


def inside_fsdp_runtime() -> bool:
    """Identify parameter and collective hooks, excluding ordinary model execution."""
    frame = sys._getframe(1)  # pylint: disable=protected-access
    while frame is not None:
        module_name = frame.f_globals.get("__name__", "")
        if _is_fsdp_module(module_name):
            return True
        frame = frame.f_back
    return False
hyper_parallel/auto_parallel/hyper_offload/api/session.py
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
_active_session: contextvars.ContextVar[OffloadSession | None] = contextvars.ContextVar("_active_session", default=None)


def _pack_native(tensor: torch.Tensor) -> SavedNative:
    return SavedNative(tensor.detach(), tensor._version)  # pylint: disable=protected-access


def _unpack_native(packed: SavedNative) -> torch.Tensor:
    if packed.tensor._version != packed.version:  # pylint: disable=protected-access
        raise RuntimeError("a tensor saved for backward was modified in place")
    return packed.tensor


class ActivationDispatchMode(TorchDispatchMode):
    """Dispatch mode that delegates to a :class:`BaseExecutor`.
64
65
66
67
68
69
70
71
72
73
74
    def __init__(self, session: OffloadSession, *, record_framework_ops: bool = False) -> None:
        """Bind this dispatch mode to the active offload session."""
        super().__init__()
        self.session = session
        self._executor = session.executor
        self._record_framework_ops = record_framework_ops
        self._replay_framework_ops = record_framework_ops and isinstance(session.executor, ReplayExecutor)

    def __torch_dispatch__(self, func, types, args=(), kwargs=None):  # pylint: disable=unused-argument
        """Dispatch a torch operation."""
        # Opaque boundaries own their inner lifetimes. Native tensors need no
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    def __torch_dispatch__(self, func, types, args=(), kwargs=None):  # pylint: disable=unused-argument
        """Dispatch a torch operation."""
        # Opaque boundaries own their inner lifetimes. Native tensors need no
        # framework ownership check; subclasses still take the guarded path.
        opaque = self._executor.in_opaque_region
        if opaque and all(tensor_type is torch.Tensor for tensor_type in types):
            return func(*args, **(kwargs or {}))
        if self._replay_framework_ops and not opaque:
            return self._executor.dispatch(func, args, kwargs)
        if inside_fsdp_runtime():
            kwargs = kwargs or {}
            # Native redispatch may report Tensor itself (notably for detach).
            # Neither that case nor an empty set can contain a ShadowTensor.
            native_inputs = (
                all(tensor_type is torch.Tensor for tensor_type in types)
                or not has_managed_inputs(args, kwargs)
            )
            if native_inputs and not self._record_framework_ops:
                return func(*args, **kwargs)
            return dispatch_framework_read(self._executor, func, args, kwargs, native_inputs=native_inputs)
        return self._executor.dispatch(func, args, kwargs)


class OffloadSession:
    """Manage warmup and replay for activation residency control.
103
104
105
106
107
108
109
110
111
    def __init__(self, config: OffloadConfig) -> None:
        """Initialize warmup execution and the configured residency planner."""
        self.mode: str = "warmup"

        self.planner = config.planner if config.planner is not None else PeakResidencyPlanner()
        self.residency_manager = ResidencyManager(
            max_host_bytes=config.max_offload_activation_mb * 1024**2,
        )
        self.executor: WarmupExecutor | ReplayExecutor = WarmupExecutor(
114
115
116
117
118
119
120
121
122
123
124
125
        )

        self._dispatch_context = None
        self._session_token = None
        self._native_replay = False
        self._saved_recorder = None
        self._saved_replay = None
        self._saved_context = None

    # ------------------------------------------------------------------
    # Active session lookup (used by skip_offload decorator)
    # ------------------------------------------------------------------
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142

    @staticmethod
    def get_active() -> OffloadSession | None:
        """Return the currently active OffloadSession, or ``None``."""
        session = _active_session.get()
        if session is not None:
            return session
        # Autograd carries dispatch modes into worker threads, but Python
        # context variables are not inherited by checkpoint recomputation.
        for mode in reversed(_get_current_dispatch_mode_stack()):
            if isinstance(mode, ActivationDispatchMode):
                return mode.session
        return None

    # ------------------------------------------------------------------
    # Context manager
    # ------------------------------------------------------------------
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        """Enter the runtime context."""
        self.executor.reset()

        self._session_token = _active_session.set(self)
        if self._saved_replay is not None:
            self._saved_replay.reset()
            self.executor.native_saved_replay = True
            self._saved_context = torch.autograd.graph.saved_tensors_hooks(
                self._saved_replay.pack, self._saved_replay.unpack,
            )
            self._saved_context.__enter__()
            return self
        self._native_replay = self.mode == "replay" and not self.executor.requires_dispatch
        if self._native_replay:
            return self
        self._dispatch_context = ActivationDispatchMode(self, record_framework_ops=True)
        self._dispatch_context.__enter__()
        if self.mode == "warmup":
            self._saved_recorder = SavedTensorRecorder(self.executor)
            pack, unpack = self._saved_recorder.pack, self._saved_recorder.unpack
        else:
            pack, unpack = _pack_native, _unpack_native
        self._saved_context = torch.autograd.graph.saved_tensors_hooks(pack, unpack)
        self._saved_context.__enter__()
        return self

    def close(self) -> None:
        """Validate that the session is idle before closing; it may be reused."""
        if self._session_token is not None:
            raise RuntimeError("cannot close an active OffloadSession")

    def __exit__(
        self, exc_type: type[BaseException] | None,
        exc_val: BaseException | None, exc_tb: TracebackType | None,
177
178
179
180
181
182
183
184
185
186
187
        self, exc_type: type[BaseException] | None,
        exc_val: BaseException | None, exc_tb: TracebackType | None,
    ) -> bool:
        """Exit the runtime context."""
        if self._saved_context is not None:
            self._saved_context.__exit__(exc_type, exc_val, exc_tb)
            self._saved_context = None
        if self._dispatch_context is not None:
            self._dispatch_context.__exit__(exc_type, exc_val, exc_tb)
            self._dispatch_context = None
        if self._session_token is not None:
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
        if self._session_token is not None:
            _active_session.reset(self._session_token)
            self._session_token = None

        if self._saved_replay is not None:
            self.executor.native_saved_replay = False
            if exc_type is not None:
                self.residency_manager.sync_all_transfers()
                self.executor.reset()
                self._saved_replay.reset()
            else:
                try:
                    self._saved_replay.finish()
                    self.residency_manager.wait_for_transfers()
                except BaseException:
                    self.residency_manager.sync_all_transfers()
                    self.executor.reset()
                    self._saved_replay.reset()
                    raise
            return False

        if self._native_replay:
            return False

        if exc_type is not None:
            self.residency_manager.sync_all_transfers()
            self.executor.reset()
216
217
218
219
220
221
222
223
224
225
226
227
228
        self.residency_manager.wait_for_transfers()

        if self.mode == "warmup":
            trace, guide = self.executor.finish()
            if self._saved_recorder is not None:
                SavedTensorReplay.add_planning_hints(self._saved_recorder, trace)
            schedule = self.planner.build(trace)
            if self._saved_recorder is not None:
                self._saved_replay = SavedTensorReplay.from_trace(
                    self.residency_manager, self._saved_recorder, trace, schedule,
                )
            # Native hooks own the complete replay contract. Retaining the
            # operator guide and its binding dictionaries only adds host memory
226
227
228
229
230
231
232
233
234
235
236
237
238
239
                )
            # Native hooks own the complete replay contract. Retaining the
            # operator guide and its binding dictionaries only adds host memory
            # and garbage-collector traversal to every subsequent iteration.
            replay_guide = guide if self._saved_replay is None else []
            self.executor = ReplayExecutor(self.residency_manager, schedule, replay_guide)
            self._saved_recorder = None
            self.mode = "replay"
            if not self.executor.requires_dispatch:
                logger.info("HyperOffload plan has no transfers; subsequent steps use native execution")
        else:
            self.executor.finish()

        return False
hyper_parallel/auto_parallel/hyper_offload/execution/base.py
122
123
124
125
126
127
128
129
130
        # Cached by on_op_begin for use in on_op_end.
        self._last_func = None
        self._last_args = None
        self._last_kwargs = None
        self._last_flat_inputs = None
        # Cached by apply_shadows for use in autograd boundaries.
        self._last_output_bindings: dict[int, int] | None = None

    @property
241
242
243
244
245
246
247
248
249
        """
        self._last_func = func
        self._last_args = args
        self._last_kwargs = kwargs
        self._last_flat_inputs = tree_flatten((args, kwargs))
        self.op_idx += 1

    @abstractmethod
    def on_op_end(self, result) -> Any:
286
287
288
289
290
291
292
293
294
295
296
297
            A pytree of the same structure as *result* with eligible
            tensors replaced by :class:`ShadowTensor`.

        """
        self._last_output_bindings = bindings
        if not bindings:
            return result
        leaves, tree_spec = flattened if flattened is not None else tree_flatten(result)
        shadowed = list(leaves)
        for idx, leaf in enumerate(leaves):
            if idx in bindings and isinstance(leaf, torch.Tensor):
                shadowed[idx] = self.make_shadow(bindings[idx], leaf)
338
339
340
341
342
343
344
345
346
347
        """Reset per-cycle state before a new pass."""
        self._opaque_depth = 0
        self.op_idx = -1
        self._alive_shadows.clear()
        self._last_func = None
        self._last_args = None
        self._last_kwargs = None
        self._last_flat_inputs = None
        self._last_output_bindings = None
        self.residency_manager.clear_runtime()
hyper_parallel/auto_parallel/hyper_offload/execution/framework.py
31
32
33
34
35
36
37
38
39
40
41
        args: Positional operation inputs.
        kwargs: Keyword operation inputs.
        native_inputs: Whether all tensor inputs are outside managed ownership.
    """
    output = None

    def framework_read(*inputs: Any, **options: Any) -> tuple:
        """Expose input lifetimes without adopting framework-owned outputs.

        Args:
            inputs: Positional operation inputs.
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
            inputs: Positional operation inputs.
            options: Keyword operation inputs.
        """
        nonlocal output
        output = func(*inputs, **options) if native_inputs else dispatch_framework_op(func, inputs, options)
        recorder = getattr(executor, "record_framework_allocation", None)
        if recorder is not None:
            input_storages = {
                value.untyped_storage()._cdata  # pylint: disable=protected-access
                for value in tree_iter((inputs, options))
                if isinstance(value, torch.Tensor)
            }
            allocated = {
                value.untyped_storage()._cdata: value.untyped_storage().nbytes()  # pylint: disable=protected-access
                for value in tree_iter(output) if isinstance(value, torch.Tensor)
                and value.untyped_storage()._cdata not in input_storages  # pylint: disable=protected-access
            }
            recorder(sum(allocated.values()))
        return ()

    framework_read.__name__ = "framework_read:" + func.__name__
    if hasattr(func, "_schema"):
        framework_read._schema = func._schema  # pylint: disable=protected-access
    executor.dispatch(framework_read, args, kwargs)
    return output


def dispatch_framework_op(func: Any, args: tuple, kwargs: dict) -> Any:
    """Export activation views to framework-owned storage at the dispatch boundary.
76
77
78
79
80
81
82
83
84
85
86
        func: Framework-owned tensor operation.
        args: Positional operation inputs.
        kwargs: Keyword operation inputs.
    """
    activation_storages = set()

    def unwrap(value: Any) -> Any:
        """Resolve managed inputs while recording their source storage.

        Args:
            value: Input tree leaf.
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105

        Args:
            value: Input tree leaf.
        """
        if not isinstance(value, ShadowTensor):
            return value
        resolved = value.resolve()
        activation_storages.add(resolved.untyped_storage())
        return resolved

    # Only local materialization bypasses modes. The framework op itself still
    # passes through any unrelated dispatch mode installed below this one.
    with torch._C._DisableTorchDispatch():  # pylint: disable=protected-access
        real_args, real_kwargs = tree_map(unwrap, (args, kwargs))
    result = func(*real_args, **real_kwargs)
    owned = {}

    def export(value: Any) -> Any:
        """Give aliased outputs storage owned by the framework caller.

        Args:
            value: Output tree leaf.
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

        Args:
            value: Output tree leaf.
        """
        if not isinstance(value, torch.Tensor):
            return value
        storage = value.untyped_storage()
        if storage not in activation_storages:
            return value
        if storage not in owned:
            raw = torch.empty(0, dtype=torch.uint8, device=value.device)
            raw.set_(storage, 0, (storage.nbytes(),), (1,))
            owned[storage] = raw.clone()
        output = torch.empty(0, dtype=value.dtype, device=value.device)
        output.set_(owned[storage].untyped_storage(), value.storage_offset(), value.size(), value.stride())
        return output

    with torch._C._DisableTorchDispatch():  # pylint: disable=protected-access
        return tree_map(export, result)
hyper_parallel/auto_parallel/hyper_offload/execution/replay/executor.py
52
53
54
55
56
57
58
59
60
        guide: list[OpGuide],
    ) -> None:
        """Bind a recorded trace and select the storages requiring replay management."""
        super().__init__(residency_manager)
        self.native_saved_replay = False
        self._schedule = schedule
        self._guide = guide
        # Transfer storage keeps wrapper identity; unrelated activations remain
        # native. Wrapper replay can add detach and virtual FSDP-read records
59
60
61
62
63
64
65
66
67
        # Transfer storage keeps wrapper identity; unrelated activations remain
        # native. Wrapper replay can add detach and virtual FSDP-read records
        # that native replay omits, so on_op_begin advances over those entries.
        # Keep legacy hand-built guides on their original contract.
        transfer_sids = {
            action.storage_id
            for phase in (schedule.pre, schedule.post)
            for actions in phase.values()
            for action in actions
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
            for actions in phase.values()
            for action in actions
            if action.kind in (ResidencyActionType.COPY_D2H, ResidencyActionType.COPY_H2D)
        }
        self._managed_sids = self._select_managed_sids(guide, transfer_sids)
        self._requires_dispatch = self._managed_sids is None or bool(transfer_sids)
        self._replay_output_bindings = [self._managed_bindings(op.output_bindings) for op in guide]
        self._replay_input_bindings = [
            self._managed_bindings(op.input_bindings) if op.input_bindings is not None else None
            for op in guide
        ]
        self._active_ops = [self._op_requires_management(index) for index in range(len(guide))]
        self._framework_ops = [op.name.startswith("framework_read:") for op in guide]
        self._dispatch_names = [op.name.removeprefix("framework_read:") for op in guide]
        logger.info(
            "Replay management: transfer_storages=%d, managed_storages=%s, wrapped_outputs=%d/%d",
            len(transfer_sids),
            len(self._managed_sids) if self._managed_sids is not None else "all",
            sum(len(bindings) for bindings in self._replay_output_bindings),
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115

    @property
    def requires_dispatch(self) -> bool:
        """Whether replay needs tensor management for any planned transfer."""
        return self._requires_dispatch

    def _select_managed_sids(self, guide: list[OpGuide], transfer_sids: set[int]) -> set[int] | None:
        """Retain legacy ownership and expand transfer-boundary dependencies."""
        if any(op.input_bindings is None for op in guide):
            return None
        managed_sids = set(transfer_sids)
        for op_idx, op in enumerate(guide):
            if op.name == "detach.default" or op.name.startswith("framework_read:"):
                actions = self._schedule.pre_actions(op_idx) + self._schedule.post_actions(op_idx)
                if any(action.storage_id in transfer_sids for action in actions):
                    managed_sids.update(op.input_bindings.values())
        return managed_sids

    def _managed_bindings(self, bindings: dict[int, int]) -> dict[int, int]:
        if self._managed_sids is None:
            return bindings
        return {index: sid for index, sid in bindings.items() if sid in self._managed_sids}

    def _input_bindings(self, leaves: list[Any]) -> dict[int, int]:
        return {
            index: value.storage_id
            for index, value in enumerate(leaves)
            if isinstance(value, ShadowTensor)
            and (self._managed_sids is None or value.storage_id in self._managed_sids)
115
116
117
118
119
120
121
122
123
            and (self._managed_sids is None or value.storage_id in self._managed_sids)
        }

    def _op_requires_management(self, index: int) -> bool:
        return (
            self._managed_sids is None
            or bool(self._replay_input_bindings[index])
            or bool(self._replay_output_bindings[index])
            or self._has_actions(index)
123
124
125
126
127
128
129
130
            or self._has_actions(index)
        )

    def _has_actions(self, op_idx: int) -> bool:
        return any(
            self._managed_sids is None or action.storage_id in self._managed_sids
            for action in self._schedule.pre_actions(op_idx) + self._schedule.post_actions(op_idx)
        )
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
            for action in self._schedule.pre_actions(op_idx) + self._schedule.post_actions(op_idx)
        )

    def _is_elidable(self, op_idx: int) -> bool:
        name = self._guide[op_idx].name
        return not self._active_ops[op_idx] and (
            name == "detach.default" or name.startswith("framework_read:")
        )

    def _next_op(self, name: str) -> int:
        index = self.op_idx + 1
        while (
            index < len(self._guide)
            and name != self._guide[index].name
            and name != self._dispatch_names[index]
            and self._is_elidable(index)
142
143
144
145
146
147
148
149
150
            and name != self._guide[index].name
            and name != self._dispatch_names[index]
            and self._is_elidable(index)
        ):
            index += 1
        return index

    def dispatch(self, func: Callable, args: tuple, kwargs: dict) -> Any:
        """Run unrelated native operations without building ownership pytrees.
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
            func: Replayed tensor operation.
            args: Positional operation inputs.
            kwargs: Keyword operation inputs.
        """
        if self.in_opaque_region:
            return func(*args, **kwargs)
        index = self.op_idx + 1
        if index < len(self._guide) and func.__name__ == self._dispatch_names[index]:
            if not self._active_ops[index]:
                self.op_idx = index
                return func(*args, **(kwargs or {}))
        else:
            index = self._next_op(func.__name__)
        return self._dispatch_slow(func, args, kwargs or {}, index)

    def _dispatch_slow(self, func: Callable, args: tuple, kwargs: dict, index: int) -> Any:
        """Handle elided records and managed ownership boundaries."""
        if self._is_unplanned_detach(func, args, kwargs, index):
            return func(*args, **kwargs)
        if index < len(self._guide) and self._framework_ops[index] and func.__name__ == self._dispatch_names[index]:
            if not self._active_ops[index]:
                self.op_idx = index
                return func(*args, **(kwargs or {}))
            self.op_idx = index - 1
            return dispatch_framework_read(
                self, func, args, kwargs or {}, native_inputs=self._replay_input_bindings[index] == {},
            )
        if (
            index < len(self._guide)
            and not self._active_ops[index]
            and not func.__name__.startswith("framework_read:")
        ):
            if func.__name__ != self._guide[index].name:
                raise RuntimeError(
                    f"replay operator differs at op={index}: expected={self._guide[index].name}, actual={func.__name__}"
                )
            self.op_idx = index
            return func(*args, **kwargs)
        self.op_idx = index - 1
        return super().dispatch(func, args, kwargs)

    def _is_unplanned_detach(self, func: Callable, args: tuple, kwargs: dict, index: int) -> bool:
        """Identify checkpoint detaches without planned transfer ownership."""
        if self._managed_sids is None or func.__name__ != "detach.default":
            return False
        leaves, _ = tree_flatten((args, kwargs))
        return not self._input_bindings(leaves) and (
            index >= len(self._guide) or self._dispatch_names[index] != "detach.default"
        )

    def execute_opaque_op(
214
215
216
217
218
219
220
221
222
223
224
            fn: Native callable inside the boundary.
            args: Positional arguments.
            kwargs: Keyword arguments.
        """
        if self.native_saved_replay or not self.requires_dispatch:
            return fn(*args, **kwargs)
        return super().execute_opaque_op(func_name, fn, args, kwargs)

    # ------------------------------------------------------------------
    # Lifecycle hooks
    # ------------------------------------------------------------------
233
234
235
236
237
238
239
240
241
242
243
                f"trace_ops={len(self._guide)}, "
                f"op={func.__name__}"
            )

        guide = self._guide[self.op_idx]
        actual_bindings = self._input_bindings(self._last_flat_inputs[0])
        while (
            (
                func.__name__ != guide.name
                or actual_bindings != (self._replay_input_bindings[self.op_idx] or {})
            )
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
                or actual_bindings != (self._replay_input_bindings[self.op_idx] or {})
            )
            and self._is_elidable(self.op_idx)
        ):
            self.op_idx += 1
            if self.op_idx >= len(self._guide):
                raise RuntimeError(
                    f"replay operator differs at op={self.op_idx}: actual={func.__name__}"
                )
            guide = self._guide[self.op_idx]

        if guide.input_bindings is not None and func.__name__ != guide.name:
            raise RuntimeError(
                f"replay operator differs at op={self.op_idx}: expected={guide.name}, actual={func.__name__}"
            )
        if guide.input_bindings is not None:
            expected_bindings = self._replay_input_bindings[self.op_idx]
            if actual_bindings != expected_bindings:
                raise RuntimeError(
                    f"replay input bindings differ at op={self.op_idx}: "
                    f"name={guide.name}, "
                    f"expected_bindings={expected_bindings}, "
                    f"actual_bindings={actual_bindings}"
266
267
268
269
270
271
272
273
274
275

        for action in self._schedule.pre_actions(self.op_idx):
            if action.kind == ResidencyActionType.COPY_H2D:
                self.residency_manager.copy_h2d(action.storage_id)
            elif action.kind == ResidencyActionType.RELEASE_HOST:
                self.residency_manager.release_host(action.storage_id)
            else:
                raise RuntimeError(f"unsupported pre action {action} at op={self.op_idx}")

    def on_op_end(self, result) -> Any:
284
285
286
287
288
289
290
291
292
        and missing host copies.
        """
        func = self._last_func
        op_guide = self._guide[self.op_idx]
        leaves, output_spec = tree_flatten(result)
        if len(leaves) != op_guide.output_leaf_count:
            raise RuntimeError(
                "replay output structure differs from warmup trace: "
                f"op_idx={self.op_idx}, "
297
298
299
300
301
302
303
304
305
            )

        # 1. Shadow outputs first — binds PhysicalBuffers so that
        #    post-actions can find and operate on them.
        result = self.apply_shadows(
            result,
            self._replay_output_bindings[self.op_idx],
            flattened=(leaves, output_spec),
        )
310
311
312
313
314
315
316
317
318
319
            if action.kind == ResidencyActionType.COPY_D2H:
                self.residency_manager.copy_d2h(sid)
            elif action.kind == ResidencyActionType.RELEASE_DEVICE:
                self.residency_manager.release_device(sid)
            elif action.kind == ResidencyActionType.TRY_RELEASE_DEVICE:
                self.residency_manager.try_release_device(sid)
            elif action.kind == ResidencyActionType.RELEASE_HOST:
                self.residency_manager.release_host(sid)
            else:
                raise RuntimeError(f"unsupported post action {action} at op={self.op_idx}")
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
                raise RuntimeError(f"unsupported post action {action} at op={self.op_idx}")

        # Sparse replay may execute many native ops before the next managed
        # boundary. Do not retain its input tensors throughout that interval.
        self._last_func = None
        self._last_args = None
        self._last_kwargs = None
        self._last_flat_inputs = None
        return result

    def finish(self) -> None:
        """Reject truncated steps as well as steps with additional operations."""
        while self.op_idx + 1 < len(self._guide) and self._is_elidable(self.op_idx + 1):
            self.op_idx += 1
        if self.op_idx + 1 != len(self._guide):
            raise RuntimeError(
                f"replay op count differs from warmup trace: expected={len(self._guide)}, actual={self.op_idx + 1}"
            )
hyper_parallel/auto_parallel/hyper_offload/execution/saved_tensors.py
44
45
46
47
48
49
50
51
52

    Args:
        tensor: Saved activation or parameter view.
    """
    return (tuple(tensor.shape), tuple(tensor.stride()), tensor.storage_offset(), tensor.dtype, tensor.device)


class SavedTensorRecorder:
    """Associate autograd save slots with the warmup storage identities."""
56
57
58
59
60
61
62
63
64
65
66

        Args:
            executor: Warmup executor recording the same step.
        """
        self.executor = executor
        self.slots: list[SavedSlot] = []
        self.unpacks: list[tuple[int, int]] = []
        self.save_unpack_counts: list[int] = []

    def pack(self, tensor: torch.Tensor) -> tuple:
        """Record a save without retaining a tensor in the persistent guide.
67
68
69
70
71
72
73
74
75
76
77
78
79

        Args:
            tensor: Tensor being saved by autograd.
        """
        sid = (tensor.storage_id if isinstance(tensor, ShadowTensor)
               else self.executor._tracker.get_activation_sid(tensor))  # pylint: disable=protected-access
        index = len(self.slots)
        self.slots.append(SavedSlot(sid, tensor_metadata(tensor), self.executor.op_idx))
        self.save_unpack_counts.append(len(self.unpacks))
        return index, tensor.detach(), tensor._version  # pylint: disable=protected-access

    def unpack(self, packed: tuple) -> torch.Tensor:
        """Record the backward access anchor and restore the saved tensor.
80
81
82
83
84
85
86
87
88
89
90
91
92

        Args:
            packed: Save slot and detached tensor from pack.
        """
        index, tensor, version = packed
        if tensor._version != version:  # pylint: disable=protected-access
            raise RuntimeError("a tensor saved for backward was modified in place")
        self.unpacks.append((index, self.executor.op_idx))
        return tensor


class NativeSavedValue(Protocol):
    """Native and Python saved values expose the same replay access contract."""
106
107
108
109
110
111
112
113
114
115
116
    slot_index: int | None = None

    def unpack(self) -> torch.Tensor:
        """Check mutations before returning a Python-managed saved view."""
        if self.tensor._version != self.version:  # pylint: disable=protected-access
            raise RuntimeError("a tensor saved for backward was modified in place")
        return self.tensor


@dataclass(frozen=True, slots=True)  # pylint: disable=unexpected-keyword-arg
class SavedActivation:
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
            manager: Existing physical residency controller.
            slots: Recorded autograd saves.
            selected: Storage IDs selected by the unchanged planner.
        """
        self.manager = manager
        self.slot_count = len(slots)
        self.slots = {index: slot for index, slot in enumerate(slots) if slot.storage_id in selected}
        self.selected = selected
        self._next_slot = 0
        self._bound: dict[int, tuple[int, list[tuple[Any, int]]]] = {}
        self._unpacked = 0
        self._prefetched = False
        self._pending_release: set[int] = set()
        self.prefetch_at: dict[int, list[int]] = {0: list(selected)}
        self.release_at: dict[int, list[int]] = {}
        self.unpack_count: int | None = None
        self._next_unpack = 0
        self._restored: set[int] = set()
        self._remaining_uses: dict[int, int] = dict(Counter(slot.storage_id for slot in self.slots.values()))
        self._use_counts = dict(self._remaining_uses)
        self.save_unpack_counts: list[int] | None = None
        self.unpack_slots: list[int] | None = None
        self._forward_slot_count = len(slots)

    @staticmethod
    def add_planning_hints(recorder: SavedTensorRecorder, trace: Any) -> None:
        """Prefer immutable forward-save/backward-use gaps without relaxing budgets.
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        Args:
            recorder: Completed autograd save and use recording.
            trace: Planner input receiving optional candidate preferences.
        """
        if not recorder.unpacks:
            return
        backward = recorder.unpacks[0][1]
        used = {recorder.slots[index].storage_id for index, _ in recorder.unpacks}
        first_saves = {}
        for slot in recorder.slots:
            if slot.storage_id is not None and slot.storage_id in used and slot.op_id < backward:
                first_saves.setdefault(slot.storage_id, slot.op_id)
        positions, writes = SavedTensorReplay._saved_access_positions(trace, first_saves)
        for sid, accesses in positions.items():
            boundary = bisect_left(accesses, backward)
            if not 0 < boundary < len(accesses) or sid in trace.retained_sids:
                continue
            if not SavedTensorReplay._writes_are_immutable(first_saves[sid], writes.get(sid, []), trace):
                continue
            start, end = accesses[boundary - 1], accesses[boundary]
            if end > start + 1:
                trace.preferred_eviction_gaps.append((sid, start, end))

    @staticmethod
    def _saved_access_positions(trace: Any, first_saves: dict[int, int]) -> tuple[dict, dict]:
        """Collect distinct operator accesses and writes for saved storages."""
        positions, writes = {}, {}
        for op_id, op in enumerate(trace.ops):
            for access in op.accesses:
                sid = access.storage_id
                if sid not in first_saves:
                    continue
                rows = positions.setdefault(sid, [])
                if not rows or rows[-1] != op_id:
                    rows.append(op_id)
                if access.kind == AccessKind.WRITE:
                    writes.setdefault(sid, []).append(op_id)
        return positions, writes

    @staticmethod
    def _immutable_save_slots(sid: int, recorder: SavedTensorRecorder, trace: Any) -> bool:
        slots = [index for index, slot in enumerate(recorder.slots) if slot.storage_id == sid]
        used = [index for index, _ in recorder.unpacks if index in slots]
        if not used:
            return False
        return SavedTensorReplay._immutable_writes(sid, recorder.slots[slots[0]].op_id, trace)

    @staticmethod
    def _immutable_writes(sid: int, first_save: int, trace: Any) -> bool:
        writes = [op_id for op_id, op in enumerate(trace.ops)
                  if any(access.storage_id == sid and access.kind == AccessKind.WRITE for access in op.accesses)]
        return SavedTensorReplay._writes_are_immutable(first_save, writes, trace)

    @staticmethod
    def _writes_are_immutable(first_save: int, writes: list[int], trace: Any) -> bool:
        """Check that writes preserve storage before and after its first save."""
        aliases = {"detach.default", "view.default", "_unsafe_view.default", "alias.default", "t.default",
                   "transpose.int", "permute.default", "slice.Tensor", "select.int", "as_strided.default",
                   "squeeze.default", "squeeze.dim", "unsqueeze.default", "expand.default",
                   "split.Tensor", "split.sizes", "split_with_sizes.default", "unbind.int"}
        if not writes or writes[0] > first_save:
            return False
        # Initialization can update storage before its first autograd save.
        # Later writes must only create aliases of the saved bytes.
        return all(op_id < first_save or trace.ops[op_id].name in aliases for op_id in writes[1:])

    @staticmethod
    def _copy_actions(schedule: Any) -> list:
        copies = []
        for phase in (schedule.pre, schedule.post):
            for actions in phase.values():
                copies.extend(action for action in actions if action.kind in (Action.COPY_D2H, Action.COPY_H2D))
        return copies

    @classmethod
    def from_trace(
        cls, manager: Any, recorder: SavedTensorRecorder, trace: Any, schedule: Any,
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
            recorder: Completed save and unpack recording.
            trace: Warmup trace passed to the planner.
            schedule: Schedule returned by the planner.
        """
        copies = cls._copy_actions(schedule)
        selected = {action.storage_id for action in copies}
        if not cls._can_replay(copies, selected, recorder, trace):
            return None
        replay = cls(manager, recorder.slots, selected)
        replay.save_unpack_counts = getattr(recorder, "save_unpack_counts", None)
        replay.unpack_slots = [index for index, _ in recorder.unpacks]
        replay._forward_slot_count = (
            replay.save_unpack_counts.count(0) if replay.save_unpack_counts is not None
            else sum(slot.op_id < recorder.unpacks[0][1] for slot in recorder.slots)
        )
        replay._use_counts = dict(Counter(
            recorder.slots[index].storage_id for index, _ in recorder.unpacks if index in replay.slots
        ))
        replay._remaining_uses = dict(replay._use_counts)
        replay._compile_prefetch(copies, recorder)
        replay._compile_releases(schedule, recorder)
        return replay

    @classmethod
    def _can_replay(cls, copies: list, selected: set[int], recorder: SavedTensorRecorder, trace: Any) -> bool:
        """Require complete immutable forward-save/backward-use transfers."""
        counts = Counter((action.storage_id, action.kind) for action in copies)
        if not selected or not recorder.unpacks or selected & trace.retained_sids:
            return False
        if any(counts[sid, kind] != 1 for sid in selected for kind in (Action.COPY_D2H, Action.COPY_H2D)):
            return False
        return cls._forward_intervals(copies, recorder) and all(
            cls._immutable_save_slots(sid, recorder, trace) for sid in selected
        )

    @staticmethod
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348

    @staticmethod
    def _forward_intervals(copies: list, recorder: SavedTensorRecorder) -> bool:
        """Check that selected transfers fit forward saves and backward reads."""
        first_backward = recorder.unpacks[0][1]
        # Checkpoint recomputation can save additional aliases after backward
        # starts. Each moved storage must still be saved in the forward.
        for sid in {action.storage_id for action in copies}:
            saves = [slot.op_id for slot in recorder.slots if slot.storage_id == sid]
            if not saves or min(saves) >= first_backward:
                return False
        for action in copies:
            if action.kind == Action.COPY_D2H and action.op_id >= first_backward:
                return False
            if action.kind == Action.COPY_H2D and action.op_id < first_backward:
                return False
        return True

    def _compile_prefetch(self, copies: list, recorder: SavedTensorRecorder) -> None:
        """Anchor restores to backward reads without exceeding the resident budget."""
        self.prefetch_at.clear()
        unpack_ops = [op_id for _, op_id in recorder.unpacks]
        # Round prefetch later to the next autograd access. Moving all restores
        # to backward entry would violate the planner's device-memory budget.
        for action in copies:
            if action.kind == Action.COPY_H2D:
                anchor = bisect_left(unpack_ops, action.op_id)
                first_use = next(index for index, (slot, _) in enumerate(recorder.unpacks)
                                 if recorder.slots[slot].storage_id == action.storage_id)
                self.prefetch_at.setdefault(min(anchor, first_use), []).append(action.storage_id)
        self.unpack_count = len(recorder.unpacks)

    def _compile_releases(self, schedule: Any, recorder: SavedTensorRecorder) -> None:
        """Anchor source releases to saves before the planned restore."""
        save_ops = [slot.op_id for slot in recorder.slots]
        actions = [action for phase in (schedule.pre, schedule.post) for group in phase.values() for action in group]
        for sid in self.selected:
            restore_op = next(action.op_id for action in actions
                              if action.storage_id == sid and action.kind == Action.COPY_H2D)
            deadlines = [action.op_id for action in actions if action.storage_id == sid
                         and action.kind == Action.RELEASE_DEVICE and action.op_id < restore_op]
            if deadlines:
                anchor = bisect_left(save_ops, min(deadlines))
                self.release_at.setdefault(anchor, []).append(sid)

    def _release_due_sources(self, index: int) -> None:
        for sid in self.release_at.get(index, ()):
            if sid in self._pending_release:
                self.manager.release_device(sid)
                self._pending_release.remove(sid)

    def reset(self) -> None:
        """Reset metadata after the preceding step has released its graph."""
        self._next_slot = 0
        self._bound.clear()
        self._unpacked = 0
        self._prefetched = False
        self._pending_release.clear()
        self._next_unpack = 0
        self._restored.clear()
        self._remaining_uses = dict(self._use_counts)

    def _retire_sources(self) -> None:
        for sid in tuple(self._pending_release):
            if self.manager.try_release_device(sid):
                self._pending_release.remove(sid)

    def pack(self, tensor: torch.Tensor) -> NativeSavedValue | SavedActivation:
        """Save unrelated values natively and move only planned immutable storage.
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407

        Args:
            tensor: Value saved for backward by native autograd.
        """
        index = self._next_slot
        self._next_slot += 1
        if index >= self.slot_count:
            raise RuntimeError("saved-tensor replay save sequence differs from warmup")
        if self.save_unpack_counts is not None and self.save_unpack_counts[index] != self._next_unpack:
            raise RuntimeError("saved-tensor replay save/use order differs from warmup")
        if self._pending_release:
            self._release_due_sources(index)
        slot = self.slots.get(index)
        if slot is None:
            if self._pending_release and index % 32 == 0:
                self._retire_sources()
            return SavedNative(tensor.detach(), tensor._version, index)  # pylint: disable=protected-access
        if tensor_metadata(tensor) != slot.metadata:
            raise RuntimeError(f"saved-tensor replay metadata differs at slot={index}")
        sid = slot.storage_id
        storage_id = tensor.untyped_storage()._cdata  # pylint: disable=protected-access
        version = tensor._version  # pylint: disable=protected-access
        if sid not in self._bound:
            self._bound[sid] = (storage_id, [])
            self.manager.bind(sid, tensor)
            self.manager.copy_d2h(sid)
            self._pending_release.add(sid)
        if sid in self._restored:
            storage_id_expected = self.manager.device_storage_id(sid)
        else:
            storage_id_expected = self._bound[sid][0]
        if storage_id_expected != storage_id:
            raise RuntimeError(f"saved-tensor replay alias differs at slot={index}")
        self._bound[sid][1].append((weakref.ref(tensor), version))
        return SavedActivation(sid, slot.metadata, index)

    def _validate_forward(self) -> None:
        if self._next_slot != self._forward_slot_count or set(self._bound) != self.selected:
            raise RuntimeError("saved-tensor replay forward save count differs from warmup")
        for sid in self._bound:
            self._validate_versions(sid)
        self._release_due_sources(self._next_slot)
        self._prefetched = True

    def _validate_versions(self, sid: int) -> None:
        for reference, version in self._bound[sid][1]:
            tensor = reference()
            if tensor is not None and tensor._version != version:  # pylint: disable=protected-access
                raise RuntimeError("an offloaded saved tensor was modified in place")

    def _prefetch(self, sid: int) -> None:
        self.manager.release_device(sid)
        self.manager.copy_h2d(sid)
        self.manager.release_host(sid)
        self._pending_release.discard(sid)
        self._restored.add(sid)

    def unpack(self, packed: NativeSavedValue | SavedActivation) -> torch.Tensor:
        """Prefetch at compiled backward anchors and resolve moved saved views.
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445

        Args:
            packed: Native saved value or activation metadata.
        """
        if not self._prefetched:
            self._validate_forward()
        if self.unpack_slots is not None:
            if (self._next_unpack >= len(self.unpack_slots)
                    or packed.slot_index != self.unpack_slots[self._next_unpack]):
                raise RuntimeError("saved-tensor replay unpack sequence differs from warmup")
        for sid in self.prefetch_at.get(self._next_unpack, ()):
            self._prefetch(sid)
        self._next_unpack += 1
        if not isinstance(packed, SavedActivation):
            return packed.unpack()
        if packed.storage_id not in self._restored:
            raise RuntimeError("saved-tensor replay unpack sequence differs from warmup")
        self._validate_versions(packed.storage_id)
        self._unpacked += 1
        shape, stride, offset, dtype, device = packed.metadata
        storage = self.manager.device_storage(packed.storage_id)
        result = torch.empty(0, dtype=dtype, device=device)
        result.set_(storage, offset, shape, stride)
        self._remaining_uses[packed.storage_id] -= 1
        if self._remaining_uses[packed.storage_id] == 0:
            # The returned native view owns its storage until its backward
            # consumer finishes; the manager must not retain it afterwards.
            self.manager.release_device(packed.storage_id)
        return result

    def finish(self) -> None:
        """Require the complete recorded step and release restored device storage."""
        if self._next_slot != self.slot_count or self._unpacked != sum(self._use_counts.values()):
            raise RuntimeError("saved-tensor replay step differs from warmup")
        if self.unpack_count is not None and self._next_unpack != self.unpack_count:
            raise RuntimeError("saved-tensor replay backward use count differs from warmup")
        for sid in self.selected:
            self.manager.release_device(sid)
hyper_parallel/auto_parallel/hyper_offload/execution/tensor.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    @classmethod
    def __torch_dispatch__(cls, func, types, args=(), kwargs=None):  # pylint: disable=unused-argument
        """Dispatch a torch operation."""
        kwargs = kwargs or {}
        resolved: dict[int, torch.Tensor] = {}

        def unwrap(value: Any) -> Any:
            if isinstance(value, ShadowTensor):
                if id(value) not in resolved:
                    resolved[id(value)] = value.resolve()
                return resolved[id(value)]
            return value

        with torch._C._DisableTorchDispatch():  # pylint: disable=protected-access
            return func(*tree_map(unwrap, args), **tree_map(unwrap, kwargs))
hyper_parallel/auto_parallel/hyper_offload/execution/warmup/executor.py
70
71
72
73
74
75
76
77
78
79
        self._tracker = ActivationTracker()
        self._timer = DeviceTimer()
        self._guide: list[OpGuide] = []
        self._ops: list[TraceOp] = []
        self._input_bindings = {}
        self._framework_allocation_bytes = 0
        #: sid -> the op index that first produced this activation.
        self._sid_produced_at_op: dict[int, int] = {}

    # ------------------------------------------------------------------
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    def _enforce_budget(self, protected_sids: set[int]) -> None:
        """Evict warmup activations until resident bytes fit the configured budget."""
        # The residency table owns buffers, not tensor lifetimes. Retire dead
        # temporaries before considering live activations for host offload.
        for sid, shadows in tuple(self._alive_shadows.items()):
            if not shadows and sid not in protected_sids:
                self.residency_manager.release_device(sid)
                self.residency_manager.release_host(sid)
                del self._alive_shadows[sid]
                self._sid_produced_at_op.pop(sid, None)
        while self.residency_manager.resident_bytes > self._memory_limit_bytes:
            # Greedy: evict oldest first; within the same op, evict largest first.
            victim_sid: int | None = None
            victim_key: tuple[int, int] | None = None
130
131
132
133
134
135
136
137
138
            if (sid := self._tracker.get_activation_sid(t)) is not None:
                protected_sids.add(sid)
        self._enforce_budget(protected_sids)

        self._input_bindings = {
            index: value.storage_id
            for index, value in enumerate(self._last_flat_inputs[0])
            if isinstance(value, ShadowTensor)
        }
147
148
149
150
151
152
153
154
155
        self._tracker.register_op_activations(iter_tensors((args, kwargs)), iter_tensors(result))

        op = TraceOp(name=func.__name__, duration_ms=op_duration_ms)

        mutated_tensor_ids = self._mutated_tensor_ids(func, args)

        seen: set[tuple[int, AccessKind]] = set()

        # --- Input accesses ---
163
164
165
166
167
168
169
170
171
                seen.add((sid, kind))
                op.accesses.append(StorageAccess(self.op_idx, sid, kind))

        # --- Output accesses + bindings ---
        leaves, output_spec = tree_flatten(result)
        output_bindings: dict[int, int] = {}

        for leaf_index, t in enumerate(leaves):
            if not isinstance(t, torch.Tensor):
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217

        self._ops.append(op)
        self._guide.append(guide)

        return self.apply_shadows(result, output_bindings, flattened=(leaves, output_spec))

    @staticmethod
    def _mutated_tensor_ids(func: Callable, args: tuple) -> set[int]:
        """Identify write inputs from the operator schema."""
        mutated_tensor_ids: set[int] = set()
        if hasattr(func, "_schema") and func._schema.is_mutable:  # pylint: disable=protected-access
            flat_args = iter_tensors((args, {}))
            for idx, arg_info in enumerate(func._schema.arguments):  # pylint: disable=protected-access
                if (
                    arg_info.alias_info is not None
                    and arg_info.alias_info.is_write
                    and idx < len(flat_args)
                ):
                    mutated_tensor_ids.add(id(flat_args[idx]))

        return mutated_tensor_ids

    def record_framework_allocation(self, size_bytes: int) -> None:
        """Remember framework workspace sizes without adopting their storage.
218
219
220
221
222
223
224
225
226

        Args:
            size_bytes: Fresh storage allocated by one framework operation.
        """
        self._framework_allocation_bytes = max(self._framework_allocation_bytes, size_bytes)

    def finish(self) -> tuple[ActivationTrace, list[OpGuide]]:
        """Finish warmup and return recorded trace and replay guide."""
        d2h, h2d = profile_transfer_bandwidth()
243
244
245
246
247
248
249
250
        """Reset."""
        self._sid_produced_at_op.clear()
        self._ops = []
        self._guide = []
        self._input_bindings = {}
        self._framework_allocation_bytes = 0
        self._tracker.clear_activations()
        super().reset()
hyper_parallel/auto_parallel/hyper_offload/planning/_peak_model.py
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
    READ/WRITE pairs at the same operator share a residency slot. Every WRITE
    is conservatively a snapshot barrier, including view outputs recorded as
    writes by the baseline tracer.
    """
    accesses = {}
    for op_id, op in enumerate(trace.ops):
        for access in op.accesses:
            if access.op_id != op_id:
                raise ValueError("storage access op_id must match its trace position")
            if access.kind not in (AccessKind.READ, AccessKind.WRITE):
                raise ValueError("unknown storage access kind")
            accesses.setdefault(access.storage_id, {}).setdefault(op_id, set()).add(
                access.kind
            )
    delta = [0] * (len(trace.ops) + 1)
    gaps, last_uses = [], {}
    for sid, by_op in accesses.items():
        size = trace.storage_sizes.get(sid)
        if isinstance(size, bool) or not isinstance(size, int) or size < 0:
            raise ValueError(f"storage {sid} requires a nonnegative integer byte size")
        positions = sorted(by_op)
        first, last = positions[0], positions[-1]
        resident_end = len(trace.ops) - 1 if sid in trace.retained_sids else last
        delta[first] += size
        delta[resident_end + 1] -= size
        last_uses[sid] = last
        if sid in trace.retained_sids:
            continue
        latest_write = first
        for start, end in pairwise(positions):
            if AccessKind.WRITE in by_op[start]:
                latest_write = start
            if end > start + 1 and size:
                gaps.append(
                    EvictionGap(sid, size, start, end, latest_write, first, last)
                )
    return PeakProfile(list(accumulate(delta[:-1])), gaps, last_uses)
hyper_parallel/auto_parallel/hyper_offload/planning/communication_mask.py
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
    in place. A snapshot cannot cross an earlier selected gap of the same
    storage: the baseline runtime must restore and retire that snapshot first.
    Runtime events remain responsible for actual transfer completion.
    """
    placements = []
    restored_at = {}
    for gap in sorted(
        selected, key=lambda item: (item.start, item.end, item.storage_id)
    ):
        copy_after = max(
            gap.copy_start, restored_at.get(gap.storage_id, gap.copy_start)
        )
        placements.append(TransferPlacement(gap, copy_after, gap.start, gap.end))
        restored_at[gap.storage_id] = gap.end

    previous_prefetch = 0
    for placement in sorted(
        placements, key=lambda item: (item.gap.end, item.gap.start, item.gap.storage_id)
    ):
        gap = placement.gap
        lower = max(placement.release_after + 1, previous_prefetch)
        while placement.prefetch_before > lower:
            slot = placement.prefetch_before - 1
            if resident_bytes[slot] + gap.size_bytes > limit:
                break
            resident_bytes[slot] += gap.size_bytes
            placement.prefetch_before = slot
        previous_prefetch = placement.prefetch_before

    # Spend spare residency on H2D overlap first; delaying D2H release is
    # useful only when it does not push a prefetch past its source retirement.
    next_release = len(resident_bytes)
    for placement in sorted(
        placements, key=lambda item: (item.copy_after, item.gap.start), reverse=True
    ):
        gap = placement.gap
        upper = min(gap.end - 1, placement.prefetch_before - 1, next_release)
        while placement.release_after < upper:
            slot = placement.release_after + 1
            if resident_bytes[slot] + gap.size_bytes > limit:
                break
            resident_bytes[slot] += gap.size_bytes
            placement.release_after = slot
        next_release = placement.release_after
    return placements


def limit_release_delay(
    placements: list[TransferPlacement], durations_ms: list[float], bandwidth_gbps: float
102
103
104
105
106
107
108
109
110
111
112
    completion position. Warmup timing may overestimate replay computation,
    so an estimate must not force compute to wait for unfinished transfers.
    Missing timing keeps the memory-only mask. H2D positions stay unchanged.
    """
    if not placements:
        return
    if (
        not math.isfinite(bandwidth_gbps)
        or bandwidth_gbps <= 0
        or any(not math.isfinite(value) or value < 0 for value in durations_ms)
        or not any(durations_ms)
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
        or bandwidth_gbps <= 0
        or any(not math.isfinite(value) or value < 0 for value in durations_ms)
        or not any(durations_ms)
    ):
        return
    ends = list(accumulate(durations_ms))
    copy_complete_ms = 0.0
    for placement in sorted(
        placements, key=lambda item: (item.copy_after, item.gap.storage_id)
    ):
        transfer_ms = placement.gap.size_bytes * 1000 / (bandwidth_gbps * 1024**3)
        copy_complete_ms = max(copy_complete_ms, ends[placement.copy_after]) + transfer_ms
        ready = bisect_left(
            ends, copy_complete_ms, placement.gap.start, placement.release_after + 1
        )
        placement.release_deadline = placement.release_after
        placement.release_after = min(ready, placement.release_deadline)


def limit_prefetch_advance(
    placements: list[TransferPlacement], resident_bytes: list[int],
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
    and competes with backward workspaces. Schedule the copy queue backwards
    from consumer deadlines with a margin for faster replay than warmup.
    Moving a prefetch later only reduces the memory-only mask's residency.
    """
    if (
        not placements or not math.isfinite(bandwidth_gbps) or bandwidth_gbps <= 0
        or any(not math.isfinite(value) or value < 0 for value in durations_ms)
        or not any(durations_ms)
    ):
        return
    starts = [0.0, *accumulate(durations_ms)]
    next_start = math.inf
    for placement in sorted(
        placements, key=lambda item: (item.gap.end, item.gap.storage_id), reverse=True
    ):
        transfer_ms = placement.gap.size_bytes * 1000 / (bandwidth_gbps * 1024**3)
        start_ms = min(starts[placement.gap.end], next_start) - PREFETCH_LEAD_COPIES * transfer_ms
        target = max(placement.prefetch_before, bisect_right(starts, start_ms) - 1)
        target = min(target, placement.gap.end)
        for slot in range(placement.prefetch_before, target):
            resident_bytes[slot] -= placement.gap.size_bytes
        placement.prefetch_before = target
        next_start = starts[target]


def release_checkpoints(placement: TransferPlacement) -> list[int]:
    """Return sparse completion checks strictly before the memory deadline.
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
    Exponentially spaced operator boundaries bound event-query overhead when
    the host runs ahead of the copy stream. All checkpoints are after the
    last source use; the original release still enforces the memory budget.
    """
    deadline = placement.release_deadline
    if deadline is None:
        return []
    checkpoints = []
    position = placement.release_after
    distance = max(1, position - placement.copy_after)
    while position < deadline:
        checkpoints.append(position)
        position += distance
        distance *= 2
    return checkpoints
hyper_parallel/auto_parallel/hyper_offload/planning/peak.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    neighbor_impact: float = 1.0


def _overlap_fraction(gap: EvictionGap, selected: list[EvictionGap]) -> float:
    intervals = sorted(
        (max(gap.first, other.first), min(gap.last, other.last)) for other in selected
    )
    covered, cursor = 0, gap.first
    for start, end in intervals:
        if end > max(cursor, start):
            covered += end - max(cursor, start)
            cursor = end
    return covered / max(1, gap.last - gap.first)


def _choose_gap(
    eligible: list[EvictionGap],
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    selected: list[EvictionGap],
    weights: ScoreWeights,
) -> EvictionGap:
    """Choose an eviction interval by size, peak coverage and overlap."""
    max_size = max(gap.size_bytes for gap in eligible)
    max_left = max(peak - gap.first for gap in eligible)
    max_right = max(gap.end - peak for gap in eligible)

    def score(gap: EvictionGap) -> tuple:
        """Rank candidates with deterministic size and position tie breaks."""
        value = (
            weights.size * gap.size_bytes / max_size
            + weights.cover_start * (peak - gap.first) / max_left
            + weights.cover_end * (gap.end - peak) / max_right
            - weights.neighbor_impact * _overlap_fraction(gap, selected)
82
83
84
85
86
87
88
89
90
91
92
            + weights.cover_start * (peak - gap.first) / max_left
            + weights.cover_end * (gap.end - peak) / max_right
            - weights.neighbor_impact * _overlap_fraction(gap, selected)
        )
        return value, gap.size_bytes, gap.end - gap.start, gap.start, -gap.storage_id

    return max(eligible, key=score)


def _select_gaps(
    resident: list[int], gaps: list[EvictionGap], limit: int, weights: ScoreWeights,
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
    resident: list[int], gaps: list[EvictionGap], limit: int, weights: ScoreWeights,
    preferred: set[tuple[int, int, int]] | None = None,
) -> list[EvictionGap]:
    """Select eviction intervals until reducible peaks fit the budget."""
    remaining, selected = list(gaps), []
    delta = [0] * (len(resident) + 1)
    for gap in gaps:
        delta[gap.start + 1] += 1
        delta[gap.end] -= 1
    covering = list(accumulate(delta[:-1]))
    while remaining:
        # An unavoidable operator peak must not hide other reducible peaks.
        reducible = (
            slot
            for slot, count in enumerate(covering)
            if count and resident[slot] > limit
        )
        peak = max(reducible, key=lambda slot: (resident[slot], slot), default=None)
        if peak is None:
            break
        eligible = [gap for gap in remaining if gap.start < peak < gap.end]
        native = [
            gap for gap in eligible
            if preferred and (gap.storage_id, gap.start, gap.end) in preferred
        ]
        chosen = _choose_gap(native or eligible, peak, selected, weights)
        selected.append(chosen)
        remaining.remove(chosen)
        for slot in range(chosen.start + 1, chosen.end):
            resident[slot] -= chosen.size_bytes
            covering[slot] -= 1
    return selected


def _emit_schedule(
    placements: list[TransferPlacement], last_uses: dict[int, int], retained: set[int],
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
    placements: list[TransferPlacement], last_uses: dict[int, int], retained: set[int],
    checkpoint_ops: set[int],
) -> ResidencySchedule:
    """Translate selected intervals into ordered residency actions."""
    schedule = ResidencySchedule()
    for placement in sorted(
        placements,
        key=lambda item: (item.prefetch_before, item.gap.end, item.gap.storage_id),
    ):
        sid = placement.gap.storage_id
        schedule.add_pre(placement.prefetch_before, ResidencyActionType.COPY_H2D, sid)
        # Retire the old snapshot before a consumer may mutate this storage.
        # The existing pool defers reuse until the H2D completion event.
        schedule.add_pre(
            placement.prefetch_before, ResidencyActionType.RELEASE_HOST, sid
        )
    posts = []
    for placement in placements:
        sid = placement.gap.storage_id
        posts.append((placement.copy_after, 0, sid, ResidencyActionType.COPY_D2H))
        deadline = (
            placement.release_after
            if placement.release_deadline is None
            else placement.release_deadline
        )
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
            else placement.release_deadline
        )
        # A hard fence on an unrelated wrapper-only op expands management.
        # An earlier native boundary is safe, but never cross the last use.
        while deadline > placement.gap.start and deadline not in checkpoint_ops:
            deadline -= 1
        posts.extend(
            (op, 1, sid, ResidencyActionType.TRY_RELEASE_DEVICE)
            for op in release_checkpoints(placement)
            if op in checkpoint_ops and op < deadline
        )
        posts.append(
            (deadline, 1, sid, ResidencyActionType.RELEASE_DEVICE)
        )
    posts.extend(
        (op, 1, sid, ResidencyActionType.RELEASE_DEVICE)
        for sid, op in last_uses.items()
        if sid not in retained
    )
    for op, _, sid, kind in sorted(posts):
        schedule.add_post(op, kind, sid)
    return schedule


class PeakResidencyPlanner:
    """Select idle storage gaps covering the current peak, then mask transfers.
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
        enable_communication_masking: bool = True,
        weights: ScoreWeights | None = None,
    ) -> None:
        """Configure peak selection and optional communication masking."""
        if not isinstance(enable_communication_masking, bool):
            raise TypeError("enable_communication_masking must be a bool")
        self.enable_communication_masking = enable_communication_masking
        self.weights = weights if weights is not None else ScoreWeights()
        if not all(
            math.isfinite(value) and value >= 0 for value in vars(self.weights).values()
        ):
            raise ValueError("peak score weights must be finite and nonnegative")

    def _reserve_framework_workspace(
        self, trace: ActivationTrace, profile: PeakProfile, selected: list[EvictionGap], limit: int,
    ) -> int:
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
            profile: Residency profile updated by the extra selections.
            selected: Existing selections extended with extra native intervals.
            limit: Original activation-residency limit in bytes.
        """
        workspace = trace.framework_allocation_bytes
        if isinstance(workspace, bool) or not isinstance(workspace, int) or workspace < 0:
            raise ValueError("framework_allocation_bytes must be a nonnegative integer")
        if not workspace:
            return limit
        # Framework dtype conversions are outside activation ownership.
        # Leave room for their large contiguous allocation plus allocator
        # split slack, using only native-save intervals for extra offload.
        limit = max(0, limit - 2 * workspace)
        preferred = set(trace.preferred_eviction_gaps)
        remaining = [
            gap for gap in profile.gaps
            if gap not in selected and (gap.storage_id, gap.start, gap.end) in preferred
        ]
        selected.extend(_select_gaps(profile.resident_bytes, remaining, limit, self.weights, preferred))
        return limit

    def build(self, trace: ActivationTrace) -> ResidencySchedule:
        """Build actions compatible with the baseline replay executor.
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274

        Args:
            trace: Warmup operations, storage lifetimes and allocation metadata.
        """
        limit = trace.memory_limit_bytes
        if limit is None:
            return ResidencySchedule()
        if isinstance(limit, bool) or not isinstance(limit, int) or limit < 0:
            raise ValueError("memory_limit_bytes must be a nonnegative integer or None")
        profile = build_profile(trace)
        selected = _select_gaps(
            profile.resident_bytes, profile.gaps, limit, self.weights, set(trace.preferred_eviction_gaps)
        )
        limit = self._reserve_framework_workspace(trace, profile, selected, limit)
        if self.enable_communication_masking:
            placements = mask_communications(selected, profile.resident_bytes, limit)
            limit_prefetch_advance(
                placements, profile.resident_bytes, [op.duration_ms for op in trace.ops], trace.h2d_bandwidth_gbps
            )
            limit_release_delay(
                placements, [op.duration_ms for op in trace.ops], trace.d2h_bandwidth_gbps
            )
        else:
            placements = [
                TransferPlacement(gap, gap.start, gap.start, gap.end)
                for gap in selected
            ]
        peak = max(profile.resident_bytes, default=0)
        if peak > limit:
            logger.warning(
                "Peak planner cannot meet budget: planned peak=%d bytes, limit=%d bytes",
                peak,
                limit,
            )
        logger.info(
            "Peak planner selected %d/%d gaps; planned peak=%d bytes, budget=%d bytes",
            len(selected),
            len(profile.gaps),
            peak,
275
276
277
278
279
280
281
282
283
            limit,
        )
        # Optional checks must not turn wrapper-only detach/framework reads
        # into required replay operations or expand managed tensor bindings.
        checkpoint_ops = {
            index for index, op in enumerate(trace.ops)
            if op.name != "detach.default" and not op.name.startswith("framework_read:")
        }
        return _emit_schedule(placements, profile.last_uses, trace.retained_sids, checkpoint_ops)
hyper_parallel/auto_parallel/hyper_offload/runtime/residency.py
159
160
161
162
163
164
165
166

        Raises:
            KeyError: If the storage identifier is not registered.
        """
        return self._residency[sid].device_storage()

    def device_storage_id(self, sid: int) -> int:
        """Return the current native identity of a registered device storage.
173
174
175
176
177
178
179
180
181

        Raises:
            KeyError: If the storage identifier is not registered.
        """
        return self.device_storage(sid)._cdata  # pylint: disable=protected-access

    # ------------------------------------------------------------------
    # Stream synchronisation
    # ------------------------------------------------------------------
203
204
205
206
207
208
209
210
211
212
        buffer = self._residency[sid]
        buffer.device = tensor.device

        storage = tensor.untyped_storage()
        current = buffer.device_buffer
        if current is not None and (
            current.untyped_storage()._cdata == storage._cdata  # pylint: disable=protected-access
            and current.numel() == storage.nbytes()
        ):
            # Reuse the full-storage byte view for aliases without changing
210
211
212
213
214
215
216
217
218
            and current.numel() == storage.nbytes()
        ):
            # Reuse the full-storage byte view for aliases without changing
            # transfer fences. Storage growth requires a newly sized view.
            return buffer
        dev_view = torch.empty(0, dtype=torch.uint8, device=tensor.device)
        dev_view.set_(storage, 0, (storage.size(),), (1,))
        buffer.device_buffer = dev_view
        return buffer
322
323
324
325
326
327
328
329
330
331
        # Keep restored activations in the copy stream's allocation pool so
        # their varied lifetimes do not split the compute stream's large blocks.
        copy_stream = self._get_copy_stream()
        event = None
        if buffer.device != copy_stream.device:
            dev_bytes = torch.empty(size_bytes, dtype=torch.uint8, device=buffer.device)
            dev_bytes.copy_(buffer.host_buffer, non_blocking=False)
        else:
            event = torch.Event()
            with copy_stream:
331
332
333
334
335
336
337
338
339
            with copy_stream:
                # The destination belongs to this stream's allocator pool.
                # Only the host snapshot must be ready; waiting for unrelated
                # compute here prevents early H2D from overlapping its work.
                dev_bytes = torch.empty(size_bytes, dtype=torch.uint8, device=buffer.device)
                if buffer.host_event is not None:
                    buffer.host_event.wait(copy_stream)
                dev_bytes.copy_(buffer.host_buffer, non_blocking=True)
                event.record(copy_stream)
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372

        Returns:
            Whether the source is absent or was safely retired.
        """
        buffer = self._residency.get(sid)
        if buffer is None or buffer.device_buffer is None:
            return True
        if buffer.host_buffer is None or buffer.device_event is not None:
            return False
        if buffer.host_event is not None and not buffer.host_event.query():
            return False
        buffer.device_buffer = None
        return True

    def release_device(self, sid: int) -> None:
        """Release device-resident bytes for a storage ID.
380
381
382
383
384
385
386
387
388
389
        buffer = self._residency.get(sid)
        if buffer is None or buffer.device_buffer is None:
            return

        if buffer.host_event is not None:
            buffer.host_event.wait(torch.accelerator.current_stream())

        if buffer.device_event is not None:
            buffer.device_event.synchronize()
            buffer.device_event = None
hyper_parallel/trainer/base.py
612
613
614
615
616
617
618
619
620
621
622
623
624
            self.model_fwd_context = partial(loss_parallel, mesh=tp_mesh)
        else:
            self.model_fwd_context = nullcontext()
        self.model_bwd_context = nullcontext()
        offload = self.config.hyper_offload
        self.hyper_offload_context = nullcontext()
        if offload.enable:
            self.hyper_offload_context = OffloadSession(offload)
            logger.info("HyperOffload enabled: peak planner with communication masking; %s", offload)
        self.graph_compiler: Optional[GraphCompiler] = None

    def _build_graph_compiler(self) -> None:
        """Build the optional joint-graph compiler for this trainer runtime."""
898
899
900
901
902
903
904
905
906
907
            channel_loss_callback.micro_step_context(self.state, micro_batch)
            if channel_loss_callback is not None
            else nullcontext()
        )
        offload_context = getattr(self, "hyper_offload_context", nullcontext())
        with offload_context, micro_step_context, aux_loss_scale_context():
            micro_batch = self.preforward(micro_batch)
            # TextTrainer passes loss-only fields separately. Keep the legacy
            # BaseTrainer/VLM one-dictionary call contract working as well.
            if loss_inputs is None:
1261
1262
1263
1264
1265
1266
1267
1268
1269

    @recovery_train_loop
    def train(self) -> None:
        """Run the configured training loop."""
        offload_context = getattr(self, "hyper_offload_context", None)
        try:
            config: TrainerConfig = self.config
            self.on_train_begin()
            self.data_iterator = HyperIter(
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
            except BaseException:  # pylint: disable=broad-exception-caught
                logger.exception("Failed to save memory snapshot after training error.")
            finally:
                self.abort_profilers()
            if isinstance(offload_context, OffloadSession):
                try:
                    offload_context.close()
                # Preserve the causal training error if session cleanup fails.
                except BaseException:  # pylint: disable=broad-exception-caught
                    logger.exception("Failed to close the HyperOffload session after training error.")
            raise

        if isinstance(offload_context, OffloadSession):
            offload_context.close()
        synchronize()

        self.destroy_distributed()
hyper_parallel/trainer/config/trainer.py
102
103
104
105
106
107
108
109
110
111
112
113
114
            and not self.compile.selects_graph_compiler()
            and self.accelerator.pp_size > 1
        ):
            raise ValueError("compile is not supported together with pipeline parallelism")
        if self.hyper_offload.enable:
            if self.compile.enabled or self.accelerator.pp_size > 1:
                raise ValueError("hyper_offload requires eager training without pipeline parallelism")
            if self.activation_swap != "none" or self.activation_checkpoint.swap_inputs:
                raise ValueError("hyper_offload cannot be combined with activation swapping")
        reduce_dtype = self.fsdp_config.mix_precision.reduce_dtype
        if self.optimizer.fp32_main_params and reduce_dtype != "float32":
            raise ValueError(
                "optimizer.fp32_main_params=true requires "