Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / activation_memory / _backend.py: 79%
48 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
« prev ^ index » next coverage.py v7.13.1, created at 2026-12-05 05:12 +0800
1# Copyright 2026 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ============================================================================
15"""PyTorch device primitives used by the activation-swap implementation."""
17__all__ = [
18 "Tensor",
19 "get_device_handle",
20 "new_stream",
21 "get_stream_context",
22 "get_current_stream",
23 "new_event",
24 "record_stream",
25 "no_grad",
26 "preserve_version_counter",
27 "cat",
28 "empty_like",
29 "tree_map",
30 "get_element_size",
31 "alloc_tensor_buffer",
32 "register_forward_pre_hook",
33 "register_full_backward_hook",
34 "register_full_backward_pre_hook",
35]
37from typing import Any
39import torch
40from torch import Tensor
42from hyper_parallel.core.utils.communication import get_device_handle
43from hyper_parallel.tools.dryrun.simulation import (
44 hold_for_simulated_stream,
45 is_device_runtime_simulated,
46 simulated_device_handle,
47)
50def _stream_owner():
51 """Return the namespace owning streams and events for this process.
53 Under logical simulation the process never binds an accelerator, so stream
54 and event primitives come from the simulated handle: every transfer then
55 completes in host program order, which preserves the storage lifecycle the
56 swap state machine expresses while dropping only device-side overlap.
57 """
58 if is_device_runtime_simulated():
59 return simulated_device_handle()
60 return get_device_handle()
63def new_stream():
64 """Create a new device stream on the current accelerator."""
65 return _stream_owner().Stream()
68def get_stream_context():
69 """Return the device stream context manager (``npu.stream`` / ``cuda.stream``)."""
70 return _stream_owner().stream
73def get_current_stream():
74 """Return the current device stream."""
75 return _stream_owner().current_stream()
78def new_event():
79 """Create a new device event on the current accelerator."""
80 return _stream_owner().Event()
83def record_stream(tensor: Tensor, stream: Any) -> None:
84 """Reserve ``tensor``'s storage for ``stream`` until its pending work ends.
86 Under simulation the reference is held until the next simulated wait —
87 the same point a real caching allocator could first reclaim it — so the
88 logical lifetime of staging buffers is conservative, never shorter than
89 the real one.
91 Args:
92 tensor: Tensor whose storage the stream will read.
93 stream: Stream that reads the storage asynchronously.
94 """
95 if is_device_runtime_simulated():
96 hold_for_simulated_stream(tensor)
97 return
98 tensor.record_stream(stream)
101def no_grad():
102 """Return ``torch.no_grad()``."""
103 return torch.no_grad()
106def preserve_version_counter(tensor):
107 """Temporarily keep the tensor version counter unchanged across an in-place write."""
108 return torch.autograd._unsafe_preserve_version_counter(tensor) # pylint: disable=W0212
111def cat(tensors, dim=0):
112 """Concatenate tensors along *dim*."""
113 return torch.cat(tensors, dim=dim)
116def empty_like(tensor, *, dtype=None, device=None, pin_memory=False):
117 """Allocate an uninitialized tensor shaped like *tensor*.
119 Args:
120 tensor: Tensor whose shape, dtype and layout are matched.
121 dtype: Optional override of the result dtype.
122 device: Optional override of the result device.
123 pin_memory: Request pinned host memory.
124 """
125 return torch.empty_like(tensor, dtype=dtype, device=device, pin_memory=pin_memory)
128def tree_map(fn, tree):
129 """Apply *fn* to every leaf of *tree* and rebuild the same structure.
131 Args:
132 fn: Callable applied to each leaf.
133 tree: Nested structure of tensors and containers.
134 """
135 return torch.utils._pytree.tree_map(fn, tree) # pylint: disable=W0212
138def get_element_size(tensor) -> int:
139 """Return the size in bytes of one element of *tensor*."""
140 return tensor.element_size()
143def alloc_tensor_buffer(numel: int, dtype, device="cpu", pin_memory: bool = False):
144 """Allocate an uninitialized 1-D tensor buffer.
146 Args:
147 numel: Number of elements to allocate.
148 dtype: Element type of the buffer.
149 device: Device to allocate on.
150 pin_memory: Request pinned host memory.
151 """
152 if pin_memory:
153 return torch.empty(numel, dtype=dtype, device="cpu", pin_memory=True)
154 return torch.empty(numel, dtype=dtype, device=device)
157def register_forward_pre_hook(module, hook, prepend=False, with_kwargs=False):
158 """Register a forward pre-hook on *module*, ignoring *prepend*."""
159 del prepend
160 return module.register_forward_pre_hook(hook, with_kwargs=with_kwargs)
163def register_full_backward_hook(module, hook, prepend=False):
164 """Register a full backward hook on *module*, ignoring *prepend*."""
165 del prepend
166 return module.register_full_backward_hook(hook)
169def register_full_backward_pre_hook(module, hook, prepend=False):
170 """Register a full backward pre-hook on *module*, ignoring *prepend*."""
171 del prepend
172 return module.register_full_backward_pre_hook(hook)