Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / auto_parallel / hyper_offload / runtime / residency.py: 99%
172 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"""Pure physical control plane for byte-level residency.
17This module provides the data-plane (:class:`PhysicalBuffer`) and
18the control-plane (:class:`ResidencyManager`) for raw byte buffers.
19"""
21from __future__ import annotations
23import logging
24from dataclasses import dataclass
26import torch
28from hyper_parallel.auto_parallel.hyper_offload.runtime.pinned_memory import PinnedMemoryPool
30logger = logging.getLogger(__name__)
33@dataclass
34class PhysicalBuffer:
35 """Pure physical memory block tracking host/device byte buffers.
37 This dataclass is intentionally minimal — it carries **no** knowledge
38 of logical tensors or ShadowTensor objects. Every field is
39 ``None`` when the corresponding resource is not held.
41 The **control plane** (:class:`ResidencyManager`) orchestrates
42 allocations and copies.
43 """
45 device: torch.device | None = None
46 """Target accelerator device (set on first registration)."""
48 host_buffer: torch.Tensor | None = None
49 """1-D uint8 pinned CPU buffer, or ``None`` when not resident on host."""
51 host_event: torch.Event | None = None
52 """:class:`torch.Event` recorded after the latest D2H copy completes."""
54 device_buffer: torch.Tensor | None = None
55 """1-D uint8 device buffer, or ``None`` when not resident on device."""
57 device_event: torch.Event | None = None
58 """:class:`torch.Event` recorded after the latest H2D copy completes."""
60 # ------------------------------------------------------------------
61 # Device-storage access (called by ShadowTensor)
62 # ------------------------------------------------------------------
64 def device_storage(self) -> torch.UntypedStorage:
65 """Return the device storage, waiting for any in-flight H2D event.
67 If the device buffer is not resident but host data is available,
68 this will synchronously demand-page the data back to the device.
70 Returns:
71 The underlying :class:`torch.UntypedStorage` of ``device_buffer``.
73 """
74 if self.device_buffer is None:
75 if self.host_buffer is not None and self.device is not None:
76 # Synchronous demand-paging fallback.
77 # Wait for any in-flight D2H copy to complete before reading
78 # from host_buffer (race-condition avoidance).
79 if self.host_event is not None:
80 self.host_event.synchronize()
81 self.host_event = None
83 size_bytes = self.host_buffer.numel()
84 dev_bytes = torch.empty(size_bytes, dtype=torch.uint8, device=self.device)
85 dev_bytes.copy_(self.host_buffer, non_blocking=False)
86 self.device_buffer = dev_bytes
87 else:
88 raise RuntimeError(
89 "No device buffer available and cannot demand-page. "
90 "Ensure host data is available if device data is evicted."
91 )
92 if self.device_event is not None:
93 current_stream = torch.accelerator.current_stream()
94 self.device_event.wait(current_stream)
95 self.device_buffer.record_stream(current_stream)
96 self.device_event = None
97 return self.device_buffer.untyped_storage()
100class ResidencyManager:
101 """Pure physical controller for byte-level tensor residency.
103 Owns
104 ----
105 * Physical residency table (``storage_id → PhysicalBuffer``).
106 * High-level state transitions (``copy_d2h``, ``copy_h2d``).
108 All public methods accept ``storage_id: int``.
109 """
111 def __init__(
112 self,
113 max_host_bytes: int,
114 ) -> None:
115 """Initialize deferred copy streams and the bounded pinned-memory pool."""
116 self._copy_stream = None
117 self._host_pool = PinnedMemoryPool(max_host_bytes)
118 self._residency: dict[int, PhysicalBuffer] = {}
120 def _get_copy_stream(self) -> torch.Stream:
121 """Return the internal copy stream, creating it lazily on first access.
123 Delaying stream creation avoids requiring an accelerator device context
124 at construction time (e.g. when running on CPU-only hosts or before
125 NPU/CUDA is initialised).
126 """
127 if self._copy_stream is None:
128 self._copy_stream = torch.Stream()
129 return self._copy_stream
131 # ------------------------------------------------------------------
132 # Device-side memory query
133 # ------------------------------------------------------------------
135 @property
136 def resident_bytes(self) -> int:
137 """Total bytes currently resident on the device side across all storage IDs."""
138 total = 0
139 for buf in self._residency.values():
140 if buf.device_buffer is not None:
141 total += buf.device_buffer.numel()
142 return total
144 def device_resident_size(self, sid: int) -> int | None:
145 """Return the device buffer size in bytes, or ``None`` if not device-resident."""
146 buffer = self._residency.get(sid)
147 if buffer is None or buffer.device_buffer is None:
148 return None
149 return buffer.device_buffer.numel()
151 def device_storage(self, sid: int) -> torch.UntypedStorage:
152 """Return device storage, preserving transfer waits and demand paging.
154 Args:
155 sid: Registered storage identifier.
157 Returns:
158 The device storage after resolving pending transfers.
160 Raises:
161 KeyError: If the storage identifier is not registered.
162 """
163 return self._residency[sid].device_storage()
165 def device_storage_id(self, sid: int) -> int:
166 """Return the current native identity of a registered device storage.
168 Args:
169 sid: Registered storage identifier.
171 Returns:
172 The storage identity after resolving pending transfers.
174 Raises:
175 KeyError: If the storage identifier is not registered.
176 """
177 return self.device_storage(sid)._cdata # pylint: disable=protected-access
179 # ------------------------------------------------------------------
180 # Stream synchronisation
181 # ------------------------------------------------------------------
183 def wait_for_transfers(self) -> None:
184 """Make the current accelerator stream wait for pending async transfers on the copy stream."""
185 torch.accelerator.current_stream().wait_stream(self._get_copy_stream())
187 def sync_all_transfers(self) -> None:
188 """Synchronise streams."""
189 self._get_copy_stream().synchronize()
191 # ------------------------------------------------------------------
192 # Registration: bind a storage ID to a tensor's device storage
193 # ------------------------------------------------------------------
195 def bind(self, sid: int, tensor: torch.Tensor) -> PhysicalBuffer:
196 """Point the physical buffer for *sid* at *tensor*'s device storage.
198 Returns the :class:`PhysicalBuffer` so that the caller can pass
199 it to a new :class:`~offload.execution.tensor.ShadowTensor`.
200 """
201 if sid not in self._residency:
202 self._residency[sid] = PhysicalBuffer()
203 buffer = self._residency[sid]
204 buffer.device = tensor.device
206 storage = tensor.untyped_storage()
207 current = buffer.device_buffer
208 if current is not None and (
209 current.untyped_storage()._cdata == storage._cdata # pylint: disable=protected-access
210 and current.numel() == storage.nbytes()
211 ):
212 # Reuse the full-storage byte view for aliases without changing
213 # transfer fences. Storage growth requires a newly sized view.
214 return buffer
215 dev_view = torch.empty(0, dtype=torch.uint8, device=tensor.device)
216 dev_view.set_(storage, 0, (storage.size(),), (1,))
217 buffer.device_buffer = dev_view
218 return buffer
220 # ------------------------------------------------------------------
221 # State transition: copy D2H
222 # ------------------------------------------------------------------
224 def copy_d2h(self, sid: int) -> None:
225 """Copy the physical storage for *sid* from device to host.
227 1. Look up the physical buffer for ``sid``.
228 2. If ``host_buffer`` is already present → no-op.
229 3. Launch an async D2H copy.
230 4. Keep the device buffer resident until ``release_device``.
231 """
232 buffer = self._residency.get(sid)
233 if buffer is None:
234 raise RuntimeError(
235 f"copy_d2h sid={sid}: no physical buffer registered"
236 )
237 if buffer.host_buffer is not None:
238 logger.debug("copy_d2h sid=%d: already on host, skip", sid)
239 return
240 if buffer.device_buffer is None:
241 raise RuntimeError(
242 f"copy_d2h sid={sid}: no device data to copy"
243 )
245 dev_src = buffer.device_buffer
246 size_bytes = dev_src.numel()
247 logger.debug(
248 "copy_d2h sid=%d: copying %d bytes (%.2f MiB) D2H",
249 sid,
250 size_bytes,
251 size_bytes / 1024**2,
252 )
254 # 1. Allocate pinned host buffer.
255 host_buf = self._host_pool.acquire(size_bytes)
257 # 2. Prevent the caching allocator from recycling the source
258 # memory while the copy stream reads it.
259 copy_stream = self._get_copy_stream()
260 if dev_src.device == copy_stream.device:
261 dev_src.record_stream(copy_stream)
263 # 3. Launch asynchronous D2H copy.
264 event = None
265 if dev_src.device != copy_stream.device:
266 host_buf.copy_(dev_src, non_blocking=False)
267 else:
268 producer_stream = torch.accelerator.current_stream()
269 event = torch.Event()
270 with copy_stream:
271 copy_stream.wait_stream(producer_stream)
272 host_buf.copy_(dev_src, non_blocking=True)
273 event.record(copy_stream)
275 # 4. Update physical buffer.
276 buffer.host_buffer = host_buf
277 buffer.host_event = event
279 logger.debug("copy_d2h sid=%d: done", sid)
281 # ------------------------------------------------------------------
282 # State transition: copy H2D
283 # ------------------------------------------------------------------
285 def copy_h2d(self, sid: int) -> None:
286 """Asynchronously copy (H2D) the physical storage for *sid* to device.
288 Allocates fresh device memory, launches an async H2D copy on the
289 copy stream, and updates the physical buffer with the
290 new ``device_buffer`` and ``device_event``. Returns immediately
291 without waiting for the copy to complete.
292 """
293 buffer = self._residency.get(sid)
294 if buffer is None:
295 raise RuntimeError(
296 f"copy_h2d sid={sid}: no physical buffer registered"
297 )
299 if buffer.device_buffer is not None:
300 logger.debug("copy_h2d sid=%d: already on device, skip", sid)
301 return
303 if buffer.host_buffer is None:
304 raise RuntimeError(
305 f"copy_h2d sid={sid}: no host data to copy"
306 )
308 if buffer.device is None:
309 raise RuntimeError(
310 f"copy_h2d sid={sid}: target device unknown"
311 )
313 size_bytes = buffer.host_buffer.numel()
314 logger.debug(
315 "copy_h2d sid=%d: copying %d bytes (%.2f MiB) H2D to %s",
316 sid,
317 size_bytes,
318 size_bytes / 1024**2,
319 buffer.device,
320 )
322 # Keep restored activations in the copy stream's allocation pool so
323 # their varied lifetimes do not split the compute stream's large blocks.
324 copy_stream = self._get_copy_stream()
325 event = None
326 if buffer.device != copy_stream.device:
327 dev_bytes = torch.empty(size_bytes, dtype=torch.uint8, device=buffer.device)
328 dev_bytes.copy_(buffer.host_buffer, non_blocking=False)
329 else:
330 event = torch.Event()
331 with copy_stream:
332 # The destination belongs to this stream's allocator pool.
333 # Only the host snapshot must be ready; waiting for unrelated
334 # compute here prevents early H2D from overlapping its work.
335 dev_bytes = torch.empty(size_bytes, dtype=torch.uint8, device=buffer.device)
336 if buffer.host_event is not None:
337 buffer.host_event.wait(copy_stream)
338 dev_bytes.copy_(buffer.host_buffer, non_blocking=True)
339 event.record(copy_stream)
341 # 3. Update physical buffer.
342 if dev_bytes.device == copy_stream.device:
343 dev_bytes.record_stream(copy_stream)
344 buffer.device_buffer = dev_bytes
345 buffer.device_event = event
347 # ------------------------------------------------------------------
348 # Release helpers
349 # ------------------------------------------------------------------
351 def try_release_device(self, sid: int) -> bool:
352 """Retire an idle D2H source only if its copy has already completed.
354 This optional action never inserts a stream wait or synchronizes the
355 host. The planner must also schedule a mandatory release before its
356 memory deadline and before any H2D restore or source mutation.
358 Returns:
359 Whether the source is absent or was safely retired.
360 """
361 buffer = self._residency.get(sid)
362 if buffer is None or buffer.device_buffer is None:
363 return True
364 if buffer.host_buffer is None or buffer.device_event is not None:
365 return False
366 if buffer.host_event is not None and not buffer.host_event.query():
367 return False
368 buffer.device_buffer = None
369 return True
371 def release_device(self, sid: int) -> None:
372 """Release device-resident bytes for a storage ID.
374 Frees the device buffer. If an H2D prefetch is still in flight,
375 waits for it before dropping the destination buffer reference.
376 At a delayed D2H release, order compute after the source copy before
377 freeing its storage. The wait is enqueued only at the release point,
378 so intervening forward computation can overlap the transfer.
379 """
380 buffer = self._residency.get(sid)
381 if buffer is None or buffer.device_buffer is None:
382 return
384 if buffer.host_event is not None:
385 buffer.host_event.wait(torch.accelerator.current_stream())
387 if buffer.device_event is not None:
388 buffer.device_event.synchronize()
389 buffer.device_event = None
391 buffer.device_buffer = None
392 if buffer.host_buffer is None:
393 del self._residency[sid]
395 def release_host(self, sid: int) -> None:
396 """Release host-resident bytes for a storage ID.
398 Waits for any in-flight H2D copy that may be reading from the
399 host buffer before returning it to the pool.
400 """
401 buffer = self._residency.get(sid)
402 if buffer is None or buffer.host_buffer is None:
403 return
405 # Ensure any in-flight H2D copy that reads this host buffer
406 # has completed before we return it to the pool.
407 event_to_wait = buffer.device_event if buffer.device_event is not None else buffer.host_event
408 self._host_pool.release(buffer.host_buffer, event=event_to_wait)
409 buffer.host_buffer = None
410 buffer.host_event = None
411 if buffer.device_buffer is None:
412 del self._residency[sid]
414 # ------------------------------------------------------------------
415 # Runtime clear
416 # ------------------------------------------------------------------
418 def clear_runtime(self) -> None:
419 """Release all physical resources and reset tracking."""
420 for buffer in self._residency.values():
421 if buffer.host_buffer is not None:
422 event_to_wait = (
423 buffer.device_event
424 if buffer.device_event is not None
425 else buffer.host_event
426 )
427 self._host_pool.release(buffer.host_buffer, event=event_to_wait)
428 self._residency.clear()