Coverage for / home / jenkins / .local / lib / python3.10 / site-packages / hyper_parallel / core / activation_memory / swap.py: 91%
705 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"""Swap tensor and swap manager implementation for activation checkpointing"""
16# pylint: disable=W0212
18import functools
19import threading
20import warnings
22from collections import defaultdict
23from contextlib import contextmanager
24from contextvars import ContextVar
25from typing import Any, Dict, Iterable, Iterator, List, Optional, Set
27from hyper_parallel.core.dtensor.dtensor import DTensor
28from . import _backend
30# ---------------------------------------------------------------------------
31# Module-level buffer pools — process-local, no locking needed for single-
32# stream training. Each GPU process owns its own Python interpreter, so
33# these dicts are never shared across processes.
34#
35# _CPU_PINNED_POOL: a list of available pinned CPU tensors per dtype_key.
36# Created via alloc_tensor_buffer(pin_memory=True) on the first miss; the
37# base tensor is returned here after wait_load and reused in the next
38# launch_offload, avoiding repeated cudaHostAlloc / cudaFreeHost calls.
39# ---------------------------------------------------------------------------
40_CPU_PINNED_POOL: Dict[str, List[Any]] = defaultdict(list)
41# Cap each group-swap staging allocation. 32 MiB keeps DMA chunks large
42# while avoiding one huge per-dtype staging tensor in large models.
43_GROUP_SWAP_MAX_BULK_COPY_BYTES = 32 * 1024 * 1024
46def _get_cpu_pinned_buf(dtype_key: str, total_numel: int, dtype):
47 """Pop the smallest sufficient pinned buffer from the pool, or allocate.
49 Best-fit selection minimises wasted pinned memory. When no buffer in the
50 pool is large enough, an undersized entry is discarded before allocating a
51 fresh buffer via alloc_tensor_buffer.
53 Returns the *full* buffer (capacity >= total_numel). Callers must slice
54 ``buf[:total_numel]`` for the actual copy so the returned reference can be
55 passed back to :func:`_return_cpu_pinned_buf` without any platform-specific
56 introspection.
57 """
58 pool = _CPU_PINNED_POOL[dtype_key]
59 best_i = -1
60 for i, buf in enumerate(pool):
61 if buf.numel() >= total_numel:
62 if best_i == -1 or buf.numel() < pool[best_i].numel():
63 best_i = i
64 if best_i != -1:
65 return pool.pop(best_i)
66 # No suitable buffer — discard one stale undersized entry.
67 if pool:
68 pool.pop()
69 return _backend.alloc_tensor_buffer(total_numel, dtype, device='cpu', pin_memory=True)
72def _return_cpu_pinned_buf(buf):
73 """Return a full pinned CPU buffer to the pool for reuse."""
74 if buf is None:
75 return
76 _CPU_PINNED_POOL[str(buf.dtype)].append(buf)
79def _collect_device_storage_ids(tensors: Any) -> Set[int]:
80 """Collect device storage identities from a nested tensor structure.
82 Each storage is identified by its Python object identity, which stays
83 distinct for empty tensors and FakeTensors. The ids stay valid while the
84 owning tensors are alive, which the caller guarantees for the duration of
85 one protect pass.
86 """
87 storage_ids = set()
89 def _collect(x):
90 local_tensor = x.to_local() if isinstance(x, DTensor) else x
91 if isinstance(local_tensor, _backend.Tensor) and str(local_tensor.device).lower() != "cpu":
92 storage_ids.add(id(local_tensor.untyped_storage()))
93 return x
95 _backend.tree_map(_collect, tensors)
96 return storage_ids
99class SwapTensor:
100 """A tensor that can be swapped between device and host memory asynchronously."""
101 STATE_DEVICE = "device"
102 STATE_HOST = "host"
103 STATE_D2H = "d2h"
104 STATE_H2D = "h2d"
105 STATE_NON_TENSOR = "non_tensor"
107 def __init__(self, val: Any, funcname: str, group_swap: bool = False, cpu_pool=None) -> None:
108 self.val = val
109 self.funcname = funcname
110 self._keep_on_device = False
111 self._duplicate_swap = False
112 self._group_managed = False # True when this tensor is handled by SwapGroup bulk copy
113 self.group_swap = group_swap # opt-in for group copy fusion (MUST_SWAP tensors only)
114 self.cpu_pool = cpu_pool
115 self._cpu_pool_buffer = None
116 if isinstance(val, _backend.Tensor) and str(val.device).lower() != 'cpu':
117 self.ver = val._version
118 self._state = self.STATE_DEVICE
119 val_storage = val.untyped_storage()
120 self.storage_size = val_storage.size()
121 self.is_slice_tensor = self.storage_size != val.numel() * _backend.get_element_size(val)
122 self.val_cpu = None
123 else:
124 self.ver = None
125 self._state = self.STATE_NON_TENSOR
126 self.val_cpu = None
127 self.is_slice_tensor = False
128 self.storage_size = 0
130 def dedup_key(self):
131 """Return a stable identity key for duplicate-swap detection.
133 The key is the storage PyObject's identity, which stays distinct for
134 every FakeTensor and empty storage. The SwapTensor keeps ``self.val``
135 (and with it the storage object) alive for the whole group lifecycle,
136 so the id cannot be recycled while the key is in a group's seen-set.
137 """
138 if self._state == self.STATE_NON_TENSOR:
139 return None
140 val_storage = self.val.untyped_storage()
141 return (
142 str(self.val.device),
143 id(val_storage),
144 self.val.storage_offset(),
145 val_storage.size(),
146 tuple(self.val.stride()),
147 )
149 def mark_duplicate_swap(self) -> None:
150 """Mark this wrapper as a duplicate registration in the same swap group."""
151 self._duplicate_swap = True
153 def protect_if_aliases(self, alias_storage_ids: Set[int]) -> None:
154 """Keep tensors that alias externally-owned tensors on device.
156 Args:
157 alias_storage_ids: Storage identities owned outside the swap group.
158 """
159 if self._state == self.STATE_NON_TENSOR:
160 return
161 if id(self.val.untyped_storage()) in alias_storage_ids:
162 self._keep_on_device = True
164 def get_val(self) -> Any:
165 """Return the underlying tensor value.
167 Raises RuntimeError if the tensor is not currently in the 'device' state.
168 Non-tensor values are returned directly regardless of state.
169 """
170 if self._state == self.STATE_NON_TENSOR:
171 return self.val
172 if self._state != self.STATE_DEVICE:
173 raise RuntimeError(
174 f"Cannot call get_val(): tensor is in '{self._state}' state. "
175 f"Must be in 'device' state."
176 )
177 return self.val
179 def resize_device_storage(self):
180 """Reallocate device memory on compute stream."""
181 if self._state == self.STATE_NON_TENSOR or self._duplicate_swap:
182 return
184 if self._state != self.STATE_HOST:
185 return
186 storage = self.val.untyped_storage()
187 if storage.size() == self.storage_size:
188 return
189 storage.resize_(self.storage_size)
191 def async_load(self):
192 """async load tensor from host to device"""
193 if self._state == self.STATE_NON_TENSOR or self._keep_on_device or self._duplicate_swap:
194 return
195 if self._group_managed:
196 return
198 if self._state != self.STATE_HOST:
199 warnings.warn(
200 f"[SwapTensor.async_load] Invalid state: current={self._state}, "
201 f"expected 'host'. Operation skipped."
202 )
203 return
205 if self.val_cpu is None:
206 raise ValueError("val_cpu must not be None during async_load")
207 with _backend.preserve_version_counter(self.val):
208 if self.cpu_pool is not None or self.is_slice_tensor:
209 self.val.data.copy_(self.val_cpu, non_blocking=True)
210 else:
211 self.val.untyped_storage().copy_(self.val_cpu.untyped_storage(), non_blocking=True)
212 self._state = self.STATE_H2D
214 def async_group_load(self, source):
215 """Copy a packed device-buffer slice back into the original storage."""
216 if self._state == self.STATE_NON_TENSOR or self._keep_on_device or self._duplicate_swap:
217 return
218 if not self._group_managed:
219 return
220 if self._state != self.STATE_HOST:
221 warnings.warn(
222 f"[SwapTensor.async_group_load] Invalid state: current={self._state}, "
223 f"expected 'host'. Operation skipped."
224 )
225 return
226 if self.val.untyped_storage().size() != self.storage_size:
227 raise RuntimeError(
228 f"Cannot load grouped tensor from {self.funcname}: device storage was not restored. "
229 f"expected size:{self.storage_size}, current size:{self.val.untyped_storage().size()}"
230 )
231 with _backend.preserve_version_counter(self.val):
232 self.val.copy_(source.reshape(self.val.shape), non_blocking=True)
233 self._state = self.STATE_H2D
235 def release_cpu_buffer(self, event=None):
236 """Release an explicitly pooled host buffer exactly once."""
237 if self.cpu_pool is None or self._cpu_pool_buffer is None:
238 return
239 release_tensor = self.val_cpu if self.val_cpu is not None else self._cpu_pool_buffer
240 self.cpu_pool.release(release_tensor, event=event)
241 self._cpu_pool_buffer = None
242 self.val_cpu = None
244 def wait_load(self, release_event=None):
245 """change state to device after async load is done"""
246 if self._state == self.STATE_NON_TENSOR or self._keep_on_device or self._duplicate_swap:
247 return
249 if self._state == self.STATE_DEVICE:
250 return # already loaded
251 if self._state != self.STATE_H2D:
252 warnings.warn(
253 f"[SwapTensor.wait_load] Called in invalid state: {self._state}. "
254 f"Expected 'h2d'. Skipped."
255 )
256 return
257 self._state = self.STATE_DEVICE
258 self.release_cpu_buffer(release_event)
259 if self.cpu_pool is None:
260 self.val_cpu = None
262 def _copy_to_host(self):
263 """Copy the device tensor to its host buffer, releasing the pooled buffer on failure."""
264 try:
265 if self.cpu_pool is not None or self.is_slice_tensor:
266 self.val_cpu.copy_(self.val, non_blocking=True)
267 else:
268 self.val_cpu.untyped_storage().copy_(self.val.untyped_storage(), non_blocking=True)
269 except Exception as exc:
270 if self.cpu_pool is not None and self._cpu_pool_buffer is not None:
271 release_event = _backend.new_event()
272 release_event.record(_backend.get_current_stream())
273 self.release_cpu_buffer(release_event)
274 self.val_cpu = None
275 copy_mode = "tensor" if self.cpu_pool is not None or self.is_slice_tensor else "storage"
276 raise RuntimeError(
277 "Failed to offload activation tensor from device to CPU: "
278 f"source={self.funcname!r}, shape={tuple(self.val.shape)}, dtype={self.val.dtype}, "
279 f"device={self.val.device}, copy_mode={copy_mode}, "
280 f"cpu_pool={'enabled' if self.cpu_pool is not None else 'disabled'}. "
281 f"Original error: {exc}"
282 ) from exc
284 def async_offload(self):
285 """async offload tensor from device to host"""
286 if self._state == self.STATE_NON_TENSOR or self._keep_on_device or self._duplicate_swap:
287 return
288 if self._group_managed:
289 return
291 if self._state != self.STATE_DEVICE:
292 warnings.warn(
293 f"[SwapTensor.async_offload] Invalid state: current={self._state}, "
294 f"expected 'device'. Operation skipped."
295 )
296 return
298 if self.storage_size != self.val.untyped_storage().size():
299 raise RuntimeError(
300 f"There is a tensor from {self.funcname} cannot be SWAPPED! Its storage has been resized "
301 f"presize:{self.storage_size}, current size:{self.val.untyped_storage().size()}"
302 )
303 if self.ver != self.val._version:
304 raise RuntimeError(
305 f"There is a tensor from {self.funcname} cannot be SWAPPED! In-place modification happened "
306 f"preversion:{self.ver}, current version:{self.val._version}"
307 )
309 if self.val_cpu is None:
310 if self.cpu_pool is None:
311 self.val_cpu = _backend.empty_like(
312 self.val, device="cpu", pin_memory=True
313 )
314 else:
315 logical_bytes = self.val.numel() * _backend.get_element_size(self.val)
316 self._cpu_pool_buffer = self.cpu_pool.acquire(logical_bytes)
317 try:
318 self.val_cpu = self._cpu_pool_buffer.view(self.val.dtype).reshape(self.val.shape)
319 except Exception as exc:
320 pool_buffer = self._cpu_pool_buffer
321 self.release_cpu_buffer()
322 raise RuntimeError(
323 "Failed to create a typed CPU-pool view for activation tensor "
324 f"from {self.funcname!r}: shape={tuple(self.val.shape)}, dtype={self.val.dtype}, "
325 f"logical_bytes={logical_bytes}, pool_buffer_shape={tuple(pool_buffer.shape)}, "
326 f"pool_buffer_dtype={pool_buffer.dtype}. Original error: {exc}"
327 ) from exc
329 self._copy_to_host()
330 self._state = self.STATE_D2H
332 def wait_offload(self):
333 """wait offload to host and free device memory"""
334 if self._state == self.STATE_NON_TENSOR or self._keep_on_device or self._duplicate_swap:
335 return
337 if self._state == self.STATE_HOST:
338 return
339 if self._state != self.STATE_D2H:
340 warnings.warn(
341 f"[SwapTensor.wait_offload] Called in invalid state: {self._state}. "
342 f"Expected 'd2h'. Skipped."
343 )
344 return
345 storage = self.val.untyped_storage()
346 if storage.size() != 0:
347 storage.resize_(0)
348 self._state = self.STATE_HOST
350 @property
351 def state(self) -> str:
352 """Return the current swap state of this tensor (device, host, d2h, h2d, or non_tensor)."""
353 return self._state
355 def __repr__(self):
356 if self._state == self.STATE_NON_TENSOR:
357 return f"<SwapTensor state=non_tensor, val_type={type(self.val).__name__}>"
358 return (
359 f"<SwapTensor state={self._state}, duplicate={self._duplicate_swap}, "
360 f"device_val={'exists' if self.val is not None else 'None'}>"
361 )
364class Storage:
365 """Manage a collection of tensors for swapping operations.
367 Supports dict-like access: ``storage[key].append(item)``, ``storage.clear()``,
368 ``for batch in storage.values(): ...``.
369 """
371 def __init__(self):
372 self._data: Dict[Any, List[Any]] = defaultdict(list)
374 def __getitem__(self, key: Any) -> List[Any]:
375 return self._data[key]
377 def values(self):
378 """Return an iterable view of all stored lists."""
379 return self._data.values()
381 def clear(self):
382 """Remove all entries from the storage."""
383 self._data.clear()
385 def iter_swap_tensors(self):
386 """Iterate all SwapTensor objects stored in this storage."""
387 collected = []
389 def _collect(x):
390 if isinstance(x, SwapTensor):
391 collected.append(x)
392 return x
394 for storage_list in self.values():
395 for item in storage_list:
396 _backend.tree_map(_collect, item)
397 return collected
399 def mark_duplicate_swaps(self, seen_keys) -> int:
400 """Mark tensors already registered in the same swap group as duplicates.
402 Args:
403 seen_keys: Dedup keys already registered in this group.
404 """
405 duplicate_count = 0
406 for swap_tensor in self.iter_swap_tensors():
407 dedup_key = swap_tensor.dedup_key()
408 if dedup_key is None:
409 continue
410 if dedup_key in seen_keys:
411 swap_tensor.mark_duplicate_swap()
412 duplicate_count += 1
413 continue
414 seen_keys.add(dedup_key)
415 return duplicate_count
417 def protect_alias_storage_ids(self, alias_storage_ids: Set[int]) -> None:
418 """Avoid offloading swap entries that alias externally-owned storage.
420 Args:
421 alias_storage_ids: Storage identities owned outside the swap group.
422 """
423 if not alias_storage_ids:
424 return
426 def _protect_tensor(x):
427 if isinstance(x, SwapTensor):
428 x.protect_if_aliases(alias_storage_ids)
429 return x
431 for storage_list in self.values():
432 for item in storage_list:
433 _backend.tree_map(_protect_tensor, item)
435 def launch_load(self):
436 """launch async load for all tensors in swap storage"""
437 def _async_load(x):
438 if isinstance(x, SwapTensor):
439 x.async_load()
440 return x
442 for storage_list in self.values():
443 for item in storage_list:
444 _backend.tree_map(_async_load, item)
446 def resize_device_storage(self):
447 """Resize device storage for all swap tensors (runs on compute stream)."""
448 def _resize(x):
449 if isinstance(x, SwapTensor):
450 x.resize_device_storage()
451 return x
452 for storage_list in self.values():
453 for item in storage_list:
454 _backend.tree_map(_resize, item)
456 def wait_load(self, release_event=None):
457 """wait load for all tensors in swap storage"""
458 def _wait_load(x):
459 if isinstance(x, SwapTensor):
460 x.wait_load(release_event=release_event)
461 return x
463 for storage_list in self.values():
464 for item in storage_list:
465 _backend.tree_map(_wait_load, item)
466 self.clear()
468 def release_cpu_buffers(self, event=None):
469 """Release all explicitly pooled host buffers held by this storage."""
470 def _release(x):
471 if isinstance(x, SwapTensor):
472 x.release_cpu_buffer(event=event)
473 return x
475 for storage_list in self.values():
476 for item in storage_list:
477 _backend.tree_map(_release, item)
479 def wait_offload(self):
480 """wait offload for all tensors in swap storage"""
481 def _wait_offload(x):
482 if isinstance(x, SwapTensor):
483 x.wait_offload()
484 return x
486 for storage_list in self.values():
487 for item in storage_list:
488 _backend.tree_map(_wait_offload, item)
490 def launch_offload(self):
491 """launch async offload for all tensors in swap storage"""
492 def _async_offload(x):
494 if isinstance(x, SwapTensor):
495 x.async_offload()
496 return x
498 for storage_list in self.values():
499 for item in storage_list:
500 _backend.tree_map(_async_offload, item)
503class SwapGroup:
504 """Manager for a group of storages to coordinate swap operations.
506 Non-slice tensors within the group are packed into bounded contiguous device
507 buffers before D2H transfer, and loaded back from bounded H2D buffers.
508 Each packed slice is copied back into its tensor's original device storage so
509 autograd views that alias that storage remain valid during backward.
511 Slice tensors (storage larger than logical data) fall back to the original
512 per-tensor copy path.
513 """
515 def __init__(self, group_name: str):
516 self.group_name = group_name
517 self.is_last_group: bool = False
518 self._storages: List[Storage] = []
519 self._load_event: Optional[Any] = None
520 self._offload_event: Optional[Any] = None
521 # Group-level contiguous buffers for non-slice tensors.
522 self._packed_tensor_info: List = [] # [(SwapTensor, bucket_key, element_offset), ...]
523 self._packed_buckets: Dict[str, Dict[str, Any]] = {}
524 self._group_cpu_buf = None # pinned CPU bufs; live offload→load
525 self._group_device_buf = None # temp device bufs; cleared after each phase
526 # Persistent dedup set accumulated across add() calls; avoids O(N²) rebuild.
527 # mark_duplicate_swaps mutates it in-place, so new keys are added automatically.
528 # Reset at wait_load() so stale storage ids don't leak into the next iteration.
529 self._seen_dedup_keys: set = set()
530 # Per-bucket SwapTensor lists built in _collect_packable_tensors and consumed
531 # in launch_offload, eliminating a redundant pass over _packed_tensor_info.
532 self._packed_by_bucket: Dict[str, List] = {}
534 def add(self, storage):
535 """Add a storage to the swap group.
537 Args:
538 storage: Swap tensor storage wrapper being registered.
539 """
540 duplicate_count = storage.mark_duplicate_swaps(self._seen_dedup_keys)
541 if duplicate_count > 0:
542 warnings.warn(
543 f"SwapGroup '{self.group_name}' skipped {duplicate_count} duplicate tensor swap registration(s)."
544 )
545 self._storages.append(storage)
547 def protect_alias_tensors(self, tensors: Any):
548 """Protect externally-owned tensors from premature offload.
550 Args:
551 tensors: Nested tensors whose storages must stay on device.
552 """
553 alias_storage_ids = _collect_device_storage_ids(tensors)
554 if not alias_storage_ids:
555 return
556 for storage in self._storages:
557 storage.protect_alias_storage_ids(alias_storage_ids)
559 @staticmethod
560 def _bucket_tensor(candidate_buckets, dtype_key, x):
561 """Append ``x`` to its dtype bucket, opening a new bucket when full."""
562 dtype_buckets = candidate_buckets.setdefault(dtype_key, [])
563 if (not dtype_buckets or
564 dtype_buckets[-1]["total_bytes"] + x.storage_size > _GROUP_SWAP_MAX_BULK_COPY_BYTES):
565 dtype_buckets.append({
566 "bucket_key": f"{dtype_key}#{len(dtype_buckets)}",
567 "dtype": x.val.dtype,
568 "dtype_key": str(x.val.dtype),
569 "device": x.val.device,
570 "tensors": [],
571 "total_bytes": 0,
572 "total_numel": 0,
573 "cpu_pool": x.cpu_pool,
574 })
575 bucket = dtype_buckets[-1]
576 bucket["tensors"].append(x)
577 bucket["total_bytes"] += x.storage_size
578 bucket["total_numel"] += x.val.numel()
579 return x
581 @staticmethod
582 def _finalize_packed_buckets(candidate_buckets, packed_info, packed_buckets, packed_by_bucket) -> int:
583 """Turn multi-tensor candidate buckets into packed buckets; return owned bytes."""
584 total_bytes = 0
585 for dtype_bucket_list in candidate_buckets.values():
586 for candidate_bucket in dtype_bucket_list:
587 tensors = candidate_bucket["tensors"]
588 if len(tensors) < 2:
589 continue
590 bucket_key = candidate_bucket["bucket_key"]
591 packed_buckets[bucket_key] = {
592 "dtype": candidate_bucket["dtype"],
593 "dtype_key": candidate_bucket["dtype_key"],
594 "device": candidate_bucket["device"],
595 "total_numel": candidate_bucket["total_numel"],
596 "total_bytes": candidate_bucket["total_bytes"],
597 "cpu_pool": candidate_bucket["cpu_pool"],
598 }
599 element_offset = 0
600 for tensor in tensors:
601 tensor._group_managed = True
602 tensor._state = SwapTensor.STATE_D2H
603 packed_info.append((tensor, bucket_key, element_offset))
604 element_offset += tensor.val.numel()
605 packed_by_bucket[bucket_key] = tensors
606 total_bytes += candidate_bucket["total_bytes"]
607 return total_bytes
609 def _collect_packable_tensors(self) -> int:
610 """Identify tensors eligible for group packing and mark them for bulk copy.
612 A tensor is eligible only when it is contiguous, not a slice tensor,
613 not a duplicate, not sharing storage with another live swap tensor, and
614 has ``group_swap=True``. Dtype buckets are split before their staging
615 allocation would exceed ``_GROUP_SWAP_MAX_BULK_COPY_BYTES``. A packed
616 bucket with fewer than two tensors is left on the original per-tensor
617 path because it has no batch-copy benefit. Non-contiguous
618 tensors are excluded because the packing step copies storage-order
619 bytes while restore uses the original stride; those tensors fall back to
620 the per-tensor copy path.
621 Shared-storage tensors also fall back together because group packing
622 frees the original storage after packing, which would invalidate any
623 non-packed aliases such as transpose views before their own offload.
625 Side effects: marks each eligible tensor with ``_group_managed=True``
626 and ``_state=STATE_D2H``, and populates ``_packed_tensor_info`` /
627 ``_packed_buckets``.
629 Returns:
630 Total byte count of all packable tensors.
631 """
632 candidate_buckets: Dict[str, List[Dict[str, Any]]] = {}
633 packed_info: List = []
634 packed_buckets: Dict[str, Dict[str, Any]] = {}
635 packed_by_bucket: Dict[str, List] = {}
637 def _try_pack(x):
638 if not isinstance(x, SwapTensor):
639 return x
640 no_pack = (not x.group_swap or x._state != SwapTensor.STATE_DEVICE or x._keep_on_device
641 or x.is_slice_tensor or x._duplicate_swap or x.storage_size >= _GROUP_SWAP_MAX_BULK_COPY_BYTES
642 or not x.val.is_contiguous())
643 if no_pack:
644 return x
645 if x.storage_size != x.val.untyped_storage().size():
646 raise RuntimeError(
647 f"There is a tensor from {x.funcname} cannot be SWAPPED! Its storage has been resized "
648 f"presize:{x.storage_size}, current size:{x.val.untyped_storage().size()}"
649 )
650 if x.ver != x.val._version:
651 raise RuntimeError(
652 f"There is a tensor from {x.funcname} cannot be SWAPPED! In-place modification happened "
653 f"preversion:{x.ver}, current version:{x.val._version}"
654 )
655 dtype_key = (str(x.val.dtype), id(x.cpu_pool))
656 return self._bucket_tensor(candidate_buckets, dtype_key, x)
658 for storage in self._storages:
659 for storage_list in storage.values():
660 for item in storage_list:
661 _backend.tree_map(_try_pack, item)
663 total_bytes = self._finalize_packed_buckets(
664 candidate_buckets, packed_info, packed_buckets, packed_by_bucket
665 )
667 self._packed_tensor_info = packed_info
668 self._packed_buckets = packed_buckets
669 self._packed_by_bucket = packed_by_bucket
670 return total_bytes
672 def _pack_device_buffers(self):
673 """Concatenate each packed bucket's tensors into one contiguous device buffer."""
674 group_device_bufs = {}
675 for bucket_key, swap_tensors in self._packed_by_bucket.items():
676 group_device_bufs[bucket_key] = _backend.cat(
677 [st.val.reshape(-1) for st in swap_tensors], dim=0
678 )
679 return group_device_bufs
681 @staticmethod
682 def _protect_device_bufs(group_device_bufs, copy_stream):
683 """Keep staging device buffers reserved for the copy stream.
685 A staging buffer is otherwise referenced only by a local, so a failure
686 part-way through the copy loop can drop the last reference while the
687 copy stream is still reading it -- and the caching allocator may then
688 hand that memory to the compute stream.
689 """
690 for buf in group_device_bufs.values():
691 device = getattr(buf, "device", None)
692 if device is not None and device.type not in ("cpu", "meta"):
693 _backend.record_stream(buf, copy_stream)
695 def _acquire_bucket_cpu_buf(self, bucket_key, bucket):
696 """Acquire the pinned CPU buffer that receives one bucket's D2H copy."""
697 numel = bucket["total_numel"]
698 if bucket["cpu_pool"] is None:
699 return _get_cpu_pinned_buf(bucket["dtype_key"], numel, bucket["dtype"])
700 raw_buf = bucket["cpu_pool"].acquire(bucket["total_bytes"])
701 try:
702 return raw_buf.view(bucket["dtype"])
703 except Exception as exc:
704 bucket["cpu_pool"].release(raw_buf)
705 raise RuntimeError(
706 "Failed to create a typed CPU-pool view for packed activation bucket: "
707 f"group={self.group_name!r}, bucket={bucket_key!r}, "
708 f"requested_dtype={bucket['dtype']}, total_numel={numel}, "
709 f"total_bytes={bucket['total_bytes']}, raw_buffer_shape={tuple(raw_buf.shape)}, "
710 f"raw_buffer_dtype={raw_buf.dtype}. Original error: {exc}"
711 ) from exc
713 def _release_offloaded_bucket_bufs(self, group_cpu_bufs, copy_stream):
714 """Give back every buffer already filled before a failed D2H loop."""
715 release_event = _backend.new_event()
716 release_event.record(copy_stream)
717 for bucket_key, cpu_buf in group_cpu_bufs.items():
718 cpu_pool = self._packed_buckets[bucket_key]["cpu_pool"]
719 if cpu_pool is not None:
720 cpu_pool.release(cpu_buf, event=release_event)
721 else:
722 _return_cpu_pinned_buf(cpu_buf)
724 def _offload_buckets_d2h(self, group_device_bufs, copy_stream):
725 """One-shot D2H per packed bucket."""
726 group_cpu_bufs = {}
727 active_bucket_key = None
728 try:
729 for bucket_key, bucket in self._packed_buckets.items():
730 active_bucket_key = bucket_key
731 cpu_buf = self._acquire_bucket_cpu_buf(bucket_key, bucket)
732 group_cpu_bufs[bucket_key] = cpu_buf
733 cpu_buf[:bucket["total_numel"]].copy_(
734 group_device_bufs[bucket_key], non_blocking=True
735 )
736 except Exception as exc:
737 self._release_offloaded_bucket_bufs(group_cpu_bufs, copy_stream)
738 failed_bucket = self._packed_buckets.get(active_bucket_key, {})
739 raise RuntimeError(
740 "Failed to offload packed activation bucket from device to CPU: "
741 f"group={self.group_name!r}, bucket={active_bucket_key!r}, "
742 f"dtype={failed_bucket.get('dtype', 'unknown')}, "
743 f"total_numel={failed_bucket.get('total_numel', 'unknown')}, "
744 f"total_bytes={failed_bucket.get('total_bytes', 'unknown')}, "
745 f"cpu_pool={'enabled' if failed_bucket.get('cpu_pool') is not None else 'disabled'}. "
746 f"Original error: {exc}"
747 ) from exc
748 return group_cpu_bufs
750 def launch_offload(self, copy_stream):
751 """Launch async offload for all storages in the group.
753 Non-slice tensors are first packed into bounded contiguous device
754 buffers, then transferred to pinned CPU memory. Slice tensors are
755 offloaded individually via the existing per-tensor path.
756 """
757 total_bytes = self._collect_packable_tensors()
758 with _backend.no_grad():
759 group_device_bufs = self._pack_device_buffers() if total_bytes > 0 else {}
761 compute_event = _backend.new_event()
762 compute_event.record(_backend.get_current_stream())
763 self._offload_event = _backend.new_event()
764 stream_context = _backend.get_stream_context()
765 with _backend.no_grad(), stream_context(copy_stream):
766 compute_event.wait(copy_stream)
768 if total_bytes > 0:
769 # Publish and protect the staging buffers before the first async
770 # D2H: if the copy loop fails part-way, the stack unwinding must
771 # not drop the last reference to memory the copy stream is still
772 # reading.
773 self._group_device_buf = group_device_bufs
774 self._protect_device_bufs(group_device_bufs, copy_stream)
775 self._group_cpu_buf = self._offload_buckets_d2h(group_device_bufs, copy_stream)
777 # Slice tensors use the existing per-tensor path.
778 # Group-managed tensors are already STATE_D2H so async_offload is a no-op.
779 for storage in self._storages:
780 storage.launch_offload()
781 self._offload_event.record(copy_stream)
783 def wait_offload(self):
784 """Wait for offload to complete for all storages in the group."""
785 if self._offload_event is None:
786 raise RuntimeError(
787 f"SwapGroup '{self.group_name}' wait_offload() called before launch_offload()."
788 )
789 compute_stream = _backend.get_current_stream()
790 stream_context = _backend.get_stream_context()
791 with _backend.no_grad(), stream_context(compute_stream):
792 self._offload_event.wait(compute_stream)
793 self._offload_event = None
794 for storage in self._storages:
795 storage.wait_offload()
796 # Release the temporary device packing buffer; _group_cpu_buf persists until launch_load.
797 self._group_device_buf = None
799 def launch_load(self, copy_stream):
800 """Prepare storage and launch async load for all storages in the group.
802 Non-slice tensors are loaded from pinned CPU memory into bounded
803 contiguous device buffers, then copied device-to-device into their
804 original storages. Slice tensors use the existing per-tensor path.
805 """
806 # Restore original storages before scheduling copies. Keeping the same
807 # storage object is required for autograd-saved views of packed tensors.
808 with _backend.no_grad():
809 for storage in self._storages:
810 storage.resize_device_storage()
812 compute_event = _backend.new_event()
813 compute_event.record(_backend.get_current_stream())
814 self._load_event = _backend.new_event()
815 stream_context = _backend.get_stream_context()
816 with _backend.no_grad(), stream_context(copy_stream):
817 compute_event.wait(copy_stream)
819 if self._packed_tensor_info and self._group_cpu_buf is not None:
820 group_device_bufs = {}
821 for bucket_key, bucket in self._packed_buckets.items():
822 cpu_buf = self._group_cpu_buf.get(bucket_key)
823 if cpu_buf is None:
824 continue
825 numel = bucket["total_numel"]
826 group_device_bufs[bucket_key] = _backend.alloc_tensor_buffer(
827 numel, bucket["dtype"], bucket["device"]
828 )
829 # Publish and protect the staging buffers before the first async
830 # H2D, for the same reason as launch_offload.
831 self._group_device_buf = group_device_bufs
832 self._protect_device_bufs(group_device_bufs, copy_stream)
834 for bucket_key, bucket in self._packed_buckets.items():
835 group_device_buf = group_device_bufs.get(bucket_key)
836 if group_device_buf is None:
837 continue
838 # One-shot H2D per packed bucket.
839 group_device_buf.copy_(
840 self._group_cpu_buf[bucket_key][:bucket["total_numel"]],
841 non_blocking=True,
842 )
844 # Unpack with D2D copies into the original storages. Rebinding
845 # st.val with set_() would leave existing aliases on freed storage.
846 for st, bucket_key, element_offset in self._packed_tensor_info:
847 group_device_buf = group_device_bufs.get(bucket_key)
848 if group_device_buf is None:
849 continue
850 source = group_device_buf[element_offset:element_offset + st.val.numel()]
851 st.async_group_load(source)
853 # Slice tensors use the existing per-tensor path.
854 # Group-managed tensors skip async_load via _group_managed flag.
855 for storage in self._storages:
856 storage.launch_load() # Only copy, no resize
857 self._load_event.record(copy_stream)
859 def release_cpu_buffers(self, event=None):
860 """Release staging buffers immediately or defer until ``event`` completes."""
861 if self._group_cpu_buf is None:
862 return
863 for bucket_key, buf in self._group_cpu_buf.items():
864 bucket = self._packed_buckets.get(bucket_key)
865 if bucket is not None and bucket["cpu_pool"] is not None:
866 bucket["cpu_pool"].release(buf, event=event)
867 else:
868 _return_cpu_pinned_buf(buf)
869 self._group_cpu_buf = None
871 def wait_load(self):
872 """Wait for grouped H2D and D2D loads to complete."""
873 if self._load_event is None:
874 raise RuntimeError(
875 f"SwapGroup '{self.group_name}' wait_load() called before launch_load()."
876 )
877 compute_stream = _backend.get_current_stream()
878 load_event = self._load_event
879 stream_context = _backend.get_stream_context()
880 with _backend.no_grad(), stream_context(compute_stream):
881 load_event.wait(compute_stream)
882 for storage in self._storages:
883 storage.wait_load(release_event=load_event)
884 self._load_event = None
885 self._storages.clear()
886 # Keep explicit-pool buffers pending until the copy event completes;
887 # legacy buffers retain their existing immediate-reuse behavior.
888 self.release_cpu_buffers(event=load_event)
889 # Device buffer: the pool holds the staging reference; just drop
890 # the local reference. Tensors aliasing _group_device_buf's
891 # storage keep it alive via their own storage references until
892 # they are consumed in backward.
893 self._group_device_buf = None
894 self._packed_tensor_info = []
895 self._packed_buckets = {}
896 self._packed_by_bucket = {}
897 self._seen_dedup_keys = set()
900class SwapManager:
901 """Singleton manager for swap groups and their operations."""
902 _instance: Optional["SwapManager"] = None
903 _lock = threading.Lock()
904 _FORWARD_PREFETCH_HOOK_HANDLE_ATTRS = (
905 "_swap_forward_pre_hook_handle",
906 "_swap_forward_hook_handle",
907 "_swap_backward_pre_hook_handle",
908 "_swap_backward_hook_handle",
909 )
911 def __init__(self) -> None:
912 """Initialize process-local swap groups once for the singleton."""
913 if hasattr(self, '_groups'):
914 return
915 self._groups: Dict[str, SwapGroup] = {}
916 self._current_group_name: ContextVar[str] = ContextVar(
917 "swap_current_group_name", default=""
918 )
919 self._layer_count: int = 0
920 self._copy_stream: Optional[Any] = None
921 self._missing_group_warned: bool = False
923 def __new__(cls):
924 if cls._instance is None:
925 with cls._lock:
926 if cls._instance is None:
927 cls._instance = super().__new__(cls)
928 return cls._instance
930 def add_storage(self, group_name: str, storage: Storage) -> None:
931 """Add a storage to a specified swap group."""
932 self.ensure_group(group_name)
933 self._groups[group_name].add(storage)
935 def ensure_group(self, group_name: str) -> None:
936 """Create the swap group if it does not exist yet."""
937 if group_name not in self._groups:
938 self._groups[group_name] = SwapGroup(group_name)
940 def launch_offload(self, group_name: str, copy_stream=None):
941 """Launch async offload for a specified swap group."""
942 group = self._groups.get(group_name)
943 if group is None:
944 raise RuntimeError(f"Group {group_name} does not exist.")
945 if copy_stream is None:
946 copy_stream = self._get_copy_stream()
947 group.launch_offload(copy_stream)
949 def protect_alias_tensors(self, group_name: str, tensors: Any):
950 """Keep tensors that alias externally-owned tensors on device.
952 Args:
953 group_name: Swap group the tensors are being registered with.
954 tensors: Nested tensors whose storages must stay on device.
955 """
956 group = self._groups.get(group_name)
957 if group is None:
958 raise RuntimeError(f"Group {group_name} does not exist.")
959 group.protect_alias_tensors(tensors)
961 def wait_offload(self, group_name: str):
962 """Wait for offload to complete for a specified swap group."""
963 group = self._groups.get(group_name)
964 if group is None:
965 raise RuntimeError(f"Group {group_name} does not exist.")
966 group.wait_offload()
968 def launch_load(self, group_name: str, copy_stream=None):
969 """Launch async load for a specified swap group."""
970 group = self._groups.get(group_name)
971 if group is None:
972 raise RuntimeError(f"Group {group_name} does not exist.")
973 if copy_stream is None:
974 copy_stream = self._get_copy_stream()
975 group.launch_load(copy_stream)
977 def wait_load(self, group_name: str):
978 """Wait for load to complete for a specified swap group."""
979 group = self._groups.get(group_name)
980 if group is None:
981 raise RuntimeError(f"Group {group_name} does not exist.")
982 group.wait_load()
984 def release_group_storage(self, group_name: str) -> None:
985 """Release storage references held by the swap group."""
986 group = self._groups.get(group_name)
987 if group is not None:
988 group._storages.clear()
990 def abort_group(self, group_name: str) -> None:
991 """Synchronize in-flight transfers and remove a failed run's group."""
992 group = self._groups.pop(group_name, None)
993 if group is None:
994 return
995 for event in (group._offload_event, group._load_event):
996 if event is not None:
997 event.synchronize()
998 for storage in group._storages:
999 storage.release_cpu_buffers()
1000 group.release_cpu_buffers()
1001 group._storages.clear()
1003 def reset_after_device_restart(self, modules: Iterable[Any]) -> None:
1004 """Discard failed activations while preserving model swap wiring.
1006 Call only after device restart and after the training thread has parked.
1007 Synchronizing the device fences old transfers without querying their
1008 potentially invalid events. Failure leaves buffers owned by the old run.
1010 Args:
1011 modules: This model's modules carrying registered swap-group names.
1012 """
1013 modules = tuple(modules)
1014 names = {vars(module)["_swap_group_name"] for module in modules}
1015 if not names:
1016 return
1017 _backend.get_device_handle().synchronize()
1018 pools = {}
1019 for module in modules:
1020 pool = vars(module).get("cpu_pool")
1021 if pool is not None:
1022 pools[id(pool)] = pool
1023 for name in names:
1024 group = self._groups.get(name)
1025 if group is None:
1026 continue
1027 for storage in group._storages:
1028 for tensor in storage.iter_swap_tensors():
1029 if tensor.cpu_pool is not None:
1030 pools[id(tensor.cpu_pool)] = tensor.cpu_pool
1031 storage.release_cpu_buffers()
1032 storage.clear()
1033 for bucket in group._packed_buckets.values():
1034 pool = bucket["cpu_pool"]
1035 if pool is not None:
1036 pools[id(pool)] = pool
1037 group.release_cpu_buffers()
1038 replacement = SwapGroup(name)
1039 replacement.is_last_group = group.is_last_group
1040 self._groups[name] = replacement
1041 for pool in pools.values():
1042 pool.reset_after_device_restart()
1043 for module in modules:
1044 vars(module).pop("_swap_state", None)
1045 self._copy_stream = None
1047 def get_current_group_name(self) -> str:
1048 """Return the name of the currently active swap group."""
1049 return self._current_group_name.get()
1051 def set_current_group_name(self, group_name: str) -> None:
1052 """Set the name of the currently active swap group."""
1053 self._current_group_name.set(group_name)
1055 def warn_missing_group_once(self) -> None:
1056 """Warn once per process when ``MUST_SWAP`` runs outside any swap group.
1058 Activation swap only serves pipeline chunks the schedule marked as
1059 swappable; every other region keeps its activations on device. A single
1060 warning keeps that fallback discoverable without repeating for every
1061 dispatched operator.
1062 """
1063 if self._missing_group_warned:
1064 return
1065 self._missing_group_warned = True
1066 warnings.warn(
1067 "Activation swap requested MUST_SWAP outside an active swap group; "
1068 "the activations were kept on device instead of being offloaded.",
1069 UserWarning,
1070 stacklevel=2,
1071 )
1073 def active_group_count(self) -> int:
1074 """Return the number of live swap groups for lifecycle diagnostics."""
1075 return len(self._groups)
1077 @contextmanager
1078 def group_context(self, group_name: str) -> Iterator[None]:
1079 """Activate a swap group within the current execution context."""
1080 token = self._current_group_name.set(group_name)
1081 try:
1082 yield
1083 finally:
1084 self._current_group_name.reset(token)
1086 def is_last_group(self, group_name: Optional[str] = None) -> bool:
1087 """Return whether the specified swap group is the terminal group in the chain."""
1088 group_name = self.get_current_group_name() if group_name is None else group_name
1089 group = self._groups.get(group_name)
1090 if group is None:
1091 return False
1092 return group.is_last_group
1094 def unregister_forward_prefetch_hooks(self, module: Any) -> int:
1095 """Remove hooks installed by :meth:`set_forward_prefetch_layer`.
1097 Args:
1098 module: Module whose layer-level swap hooks should be removed.
1100 Returns:
1101 Number of removed hook handles.
1102 """
1103 removed_count = 0
1104 for attr_name in self._FORWARD_PREFETCH_HOOK_HANDLE_ATTRS:
1105 if not hasattr(module, attr_name):
1106 continue
1107 handle = getattr(module, attr_name)
1108 if handle is not None:
1109 handle.remove()
1110 delattr(module, attr_name)
1111 removed_count += 1
1112 return removed_count
1114 def unregister_forward_prefetch_layer(self, module: Any) -> int:
1115 """Tear down prefetch wiring registered on ``module`` and its group.
1117 Removes the four forward/backward swap hooks installed on ``module``
1118 by :meth:`set_forward_prefetch_layer` and drops its swap group from the
1119 process-wide singleton. Mirrors the reverse of :meth:`set_forward_prefetch_layer`
1120 so models destroyed in a long-lived process do not leave stale ``SwapGroup``
1121 entries or hook handles behind (see the swap-inputs path in
1122 ``distributed/activation_checkpoint.py``, which installs these hooks but
1123 previously had no teardown).
1125 Args:
1126 module: A layer that participated in a prefetch chain.
1128 Returns:
1129 Number of removed hook handles.
1130 """
1131 removed_count = self.unregister_forward_prefetch_hooks(module)
1132 group_name = getattr(module, "_swap_group_name", None)
1133 if group_name is not None:
1134 self.abort_group(group_name)
1135 delattr(module, "_swap_group_name")
1136 if hasattr(module, "_swap_group_order"):
1137 delattr(module, "_swap_group_order")
1138 # Also drop the swap state so a module re-registered through
1139 # set_forward_prefetch_layer does not inherit a stale "pre_backward"
1140 # flag that would short-circuit the new forward pre-hook.
1141 if hasattr(module, "_swap_state"):
1142 delattr(module, "_swap_state")
1143 return removed_count
1145 def set_forward_prefetch_layer(self, first_layer, second_layer):
1146 """
1147 Configure prefetching and offloading order between two consecutive layers.
1149 Usage:
1150 for i in range(len(model.layers) - 1):
1151 set_forward_prefetch_layer(model.layers[i], model.layers[i + 1])
1153 Ensures idempotency: safe to call multiple times on the same layer pair.
1154 """
1155 if first_layer is second_layer:
1156 warnings.warn(
1157 "set_forward_prefetch_layer: "
1158 "Prefetching between identical layers has no effect.",
1159 UserWarning,
1160 stacklevel=2,
1161 )
1163 def _ensure_group_name(module):
1164 """Assign a unique swap group name to the module if not already assigned."""
1165 if not hasattr(module, "_swap_group_name"):
1166 name = f"swap_group_{self._layer_count}"
1167 self._layer_count += 1
1168 module._swap_group_name = name
1169 module._swap_group_order = {"prev": None, "next": None}
1170 return module._swap_group_name
1171 first_name = _ensure_group_name(first_layer)
1172 second_name = _ensure_group_name(second_layer)
1174 if first_name not in self._groups:
1175 self._groups[first_name] = SwapGroup(first_name)
1176 if second_name not in self._groups:
1177 self._groups[second_name] = SwapGroup(second_name)
1179 if first_layer._swap_group_order["next"] is None:
1180 first_layer._swap_group_order["next"] = second_name
1181 if second_layer._swap_group_order["prev"] is None:
1182 second_layer._swap_group_order["prev"] = first_name
1184 self._groups[first_name].is_last_group = first_layer._swap_group_order["next"] is None
1185 self._groups[second_name].is_last_group = second_layer._swap_group_order["next"] is None
1187 def _forward_pre_hook(group_name, module, _): # pylint: disable=W0613
1188 if getattr(module, "_swap_state", None) == "pre_backward":
1189 return
1190 SwapManager().set_current_group_name(group_name)
1192 def _forward_hook(group_name, module, args, output): # pylint: disable=W0613
1193 """
1194 Forward post-hook executed immediately after forward computation
1195 of the current layer finishes.
1197 Execution timeline (example with 3 layers, forward order: L0 → L1 → L2):
1199 Time →
1200 Forward Compute Stream:
1201 | Fwd L0 | post(L0) | Fwd L1 | post(L1) | Fwd L2 |
1203 Copy Stream (offload):
1204 | Offload L0 | - | Offload L1 |
1205 ↑ ↑
1206 offload at post(L0) offload at post(L1)
1208 Swap rules:
1209 1. After forward computation of the current layer completes:
1210 - If a next layer exists, asynchronously offload the activations
1211 of the current layer (launch_offload).
1213 Example:
1214 - At post-forward of L0, offload activations of L0.
1215 - At post-forward of L1, offload activations of L1.
1217 2. To limit device memory peak:
1218 - If a previous layer exists, wait until its offload operation
1219 has completed (wait_offload).
1221 Notes:
1222 - Offload operations are issued on the copy stream to overlap data transfer
1223 with forward computation of subsequent layers.
1224 - If the module is already in 'pre_backward' state, this hook is skipped
1225 to avoid triggering offload during backward phase.
1226 """
1227 if getattr(module, "_swap_state", None) == "pre_backward":
1228 return
1229 next_name = module._swap_group_order.get('next', None)
1230 if next_name:
1231 SwapManager().protect_alias_tensors(group_name, output)
1232 SwapManager().launch_offload(group_name)
1233 prev_name = module._swap_group_order.get('prev', None)
1234 if prev_name:
1235 SwapManager().wait_offload(prev_name)
1237 def _backward_pre_hook(group_name, module, grad_input): # pylint: disable=W0613
1238 """
1239 Pre-backward hook executed immediately before backward computation
1240 of the current layer starts.
1242 Execution timeline (example with 3 layers, backward order: L2 → L1 → L0):
1244 Time →
1245 Backward Compute Stream:
1246 | pre(L2) | Grad L2 | pre(L1) | Grad L1 | pre(L0) | Grad L0 |
1248 Copy Stream (load):
1249 | Load L1 | - | Load L0 |
1250 ↑ ↑
1251 prefetch at pre(L2) prefetch at pre(L1)
1253 Swap rules:
1254 1. At the beginning of backward for the current layer:
1255 - If a previous layer exists in backward order, asynchronously
1256 prefetch its activations (launch_load).
1258 Example:
1259 - At pre-backward of L2, prefetch activations of L1.
1260 - At pre-backward of L1, prefetch activations of L0.
1262 2. Before starting backward computation of the current layer:
1263 - Ensure that the activations of the current layer have already
1264 been loaded back to device memory (wait_load).
1266 Notes:
1267 - Load operations are issued on the copy stream to overlap data transfer
1268 with backward computation of the current layer.
1269 - The swap state is marked as 'pre_backward' to prevent forward hooks
1270 from issuing offload operations during backward phase.
1271 """
1272 module._swap_state = "pre_backward"
1273 prev_name = module._swap_group_order.get('prev', None)
1274 if prev_name:
1275 SwapManager().launch_load(prev_name)
1277 next_name = module._swap_group_order.get('next', None)
1278 if next_name:
1279 SwapManager().wait_load(group_name)
1280 SwapManager().release_group_storage(group_name)
1282 def _backward_hook(group_name, module, grad_input, grad_output): # pylint: disable=W0613
1283 module._swap_state = "backward"
1285 def _register_hooks_once(module, group_name):
1286 hooks = [
1287 ("_swap_forward_pre_hook_handle",
1288 lambda h: _backend.register_forward_pre_hook(module, h, prepend=True),
1289 functools.partial(_forward_pre_hook, group_name)),
1291 ("_swap_forward_hook_handle",
1292 module.register_forward_hook,
1293 functools.partial(_forward_hook, group_name)),
1295 ("_swap_backward_pre_hook_handle",
1296 lambda h: _backend.register_full_backward_pre_hook(module, h, prepend=True),
1297 functools.partial(_backward_pre_hook, group_name)),
1299 ("_swap_backward_hook_handle",
1300 lambda h: _backend.register_full_backward_hook(module, h),
1301 functools.partial(_backward_hook, group_name)),
1302 ]
1304 for attr_name, register_func, hook in hooks:
1305 if not hasattr(module, attr_name):
1306 handle = register_func(hook)
1307 setattr(module, attr_name, handle)
1308 # Register for both layers
1309 _register_hooks_once(first_layer, first_name)
1310 _register_hooks_once(second_layer, second_name)
1312 def _get_copy_stream(self):
1313 """Return a singleton copy stream, created on first access."""
1314 if self._copy_stream is None:
1315 self._copy_stream = _backend.new_stream()
1316 return self._copy_stream
1319def _teardown_wired_swap_layers(wired_modules: Iterable[Any]) -> None:
1320 """Release swap groups and prefetch hooks for an iterable of wired layers.
1322 Teardown for layers already registered through
1323 :meth:`SwapManager.set_forward_prefetch_layer` (the activation-swap paths in
1324 ``distributed/activation_checkpoint.py``). Those paths register the modules
1325 in the process-wide singleton and install
1326 hook handles, but never otherwise tear them down, so a long-lived process
1327 that rebuilds or discards models leaks ``SwapGroup`` entries and hook
1328 handles. This is called from each path's life-cycle finalizer with the wired
1329 modules held directly, because the model container is unreachable at that
1330 point and its module tree can no longer be traversed. Idempotent: a module
1331 with no ``_swap_group_name`` (already released) is a no-op.
1333 Args:
1334 wired_modules: Layers that participated in a swap prefetch chain.
1335 """
1336 manager = SwapManager()
1337 for module in wired_modules:
1338 manager.unregister_forward_prefetch_layer(module)