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 100%  
hyper_parallel/auto_parallel/hyper_offload/api/scope.py 100%  
hyper_parallel/auto_parallel/hyper_offload/api/session.py 96.7% 52,173-174
hyper_parallel/auto_parallel/hyper_offload/execution/base.py 100%  
hyper_parallel/auto_parallel/hyper_offload/execution/framework.py 95.7% 108,111
hyper_parallel/auto_parallel/hyper_offload/execution/replay/executor.py 90.7% 158,174-175,189-190,246-248,251,332
hyper_parallel/auto_parallel/hyper_offload/execution/saved_tensors.py 94.7% 86,225,293,327-329,356,358,364,381,387,397,417,424,443
hyper_parallel/auto_parallel/hyper_offload/execution/tensor.py 100%  
hyper_parallel/auto_parallel/hyper_offload/execution/warmup/executor.py 100%  
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 97.9% 63
hyper_parallel/auto_parallel/hyper_offload/planning/communication_mask.py 100%  
hyper_parallel/auto_parallel/hyper_offload/planning/peak.py 100%  
hyper_parallel/auto_parallel/hyper_offload/runtime/residency.py 100%  
hyper_parallel/trainer/base.py 100%  
hyper_parallel/trainer/config/trainer.py 100%  
hyper_parallel/auto_parallel/hyper_offload/api/session.py
48
49
50
51
52
53
54
55
56


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):
169
170
171
172
173
174
175
176
177
178
        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,
hyper_parallel/auto_parallel/hyper_offload/execution/framework.py
104
105
106
107
108
109
110
111
112
113
114
115
        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()
hyper_parallel/auto_parallel/hyper_offload/execution/replay/executor.py
154
155
156
157
158
159
160
161
162
            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
170
171
172
173
174
175
176
177
178
179
        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] == {},
            )
185
186
187
188
189
190
191
192
193
194
            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:
242
243
244
245
246
247
248
249
250
251
252
253
254
255
                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__}"
328
329
330
331
332
333
334
335
336

    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
82
83
84
85
86
87
88
89
            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

221
222
223
224
225
226
227
228
                   "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:])
289
290
291
292
293
294
295
296
            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
323
324
325
326
327
328
329
330
331
332
333
                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
352
353
354
355
356
357
358
359
360
361
362
        """
        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:
360
361
362
363
364
365
366
367
368
            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
377
378
379
380
381
382
383
384
385
            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:
383
384
385
386
387
388
389
390
391
        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
393
394
395
396
397
398
399
400
401
    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)
413
414
415
416
417
418
419
420
421
            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):
420
421
422
423
424
425
426
427
428
        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)
439
440
441
442
443
444
445
        """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/planning/_peak_model.py
59
60
61
62
63
64
65
66
67
        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)