Repository navigation
[group offloading] Reuse a pinned staging buffer for streamed low_cpu_mem_usage offloading #15396
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
a89edf5
ee278e1
1010ec6
5e9207c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,7 @@ | |
|
|
||
| import hashlib | ||
| import os | ||
| import weakref | ||
| from contextlib import contextmanager, nullcontext | ||
| from dataclasses import dataclass, replace | ||
| from enum import Enum | ||
|
|
@@ -36,6 +37,10 @@ | |
|
|
||
| logger = get_logger(__name__) # pylint: disable=invalid-name | ||
|
|
||
| _STREAM_PINNED_STAGING: weakref.WeakKeyDictionary = weakref.WeakKeyDictionary() | ||
| # Slices of the staging buffer start at multiples of this, so every dtype can view its slice. | ||
| _STAGING_ALIGNMENT_BYTES = 16 | ||
|
|
||
|
|
||
| def _apply_to_inner_tensors(tensor: torch.Tensor, fn) -> torch.Tensor: | ||
| """Rebuild a wrapper subclass tensor with `fn` applied to each of its inner tensors. | ||
|
|
@@ -77,6 +82,15 @@ def _pin_memory(tensor: torch.Tensor) -> torch.Tensor: | |
| return tensor if tensor.is_pinned() else tensor.pin_memory() | ||
|
|
||
|
|
||
| def _can_stage(tensor: torch.Tensor) -> bool: | ||
| return not is_traceable_wrapper_subclass(tensor) and not tensor.is_pinned() and tensor.is_contiguous() | ||
|
|
||
|
|
||
| def _staging_nbytes(tensor: torch.Tensor) -> int: | ||
| nbytes = tensor.numel() * tensor.element_size() | ||
| return -(-nbytes // _STAGING_ALIGNMENT_BYTES) * _STAGING_ALIGNMENT_BYTES | ||
|
|
||
|
|
||
| def _record_stream_wrapper_tensor(param: torch.Tensor, stream) -> None: | ||
| """Record stream for all inner tensors of a wrapper subclass parameter.""" | ||
| inner_tensor_names, _ = param.__tensor_flatten__() | ||
|
|
@@ -147,6 +161,9 @@ def __init__( | |
| self.record_stream = record_stream | ||
| self.onload_self = onload_self | ||
| self.low_cpu_mem_usage = low_cpu_mem_usage | ||
| # Streamed groups copy from CPU tensors kept here; low_cpu_mem_usage groups keep them to restore the | ||
| # original (e.g. memory-mapped) storage on offload instead of copying the weights back. | ||
| self.keep_cpu_copies = stream is not None or low_cpu_mem_usage | ||
|
|
||
| self.offload_to_disk_path = offload_to_disk_path | ||
| self._is_offloaded_to_disk = False | ||
|
|
@@ -183,7 +200,7 @@ def _to_cpu(tensor, low_cpu_mem_usage): | |
|
|
||
| def _init_cpu_param_dict(self): | ||
| cpu_param_dict = {} | ||
| if self.stream is None: | ||
| if not self.keep_cpu_copies: | ||
| return cpu_param_dict | ||
|
|
||
| for module in self.modules: | ||
|
|
@@ -203,7 +220,33 @@ def _init_cpu_param_dict(self): | |
| @contextmanager | ||
| def _pinned_memory_tensors(self): | ||
| try: | ||
| pinned_dict = {param: _pin_memory(tensor) for param, tensor in self.cpu_param_dict.items()} | ||
| if self.stream is not None and self.low_cpu_mem_usage: | ||
| staging_bytes = sum( | ||
| _staging_nbytes(tensor) for tensor in self.cpu_param_dict.values() if _can_stage(tensor) | ||
| ) | ||
| staging = None | ||
| if staging_bytes > 0: | ||
| # One buffer per stream is enough: `_onload_from_memory` synchronizes the stream before | ||
| # refilling it, so the previous transfer out of it has finished. | ||
| staging = _STREAM_PINNED_STAGING.get(self.stream) | ||
| if staging is None or staging.numel() < staging_bytes: | ||
| # A byte buffer: tensors of different dtypes share it, each viewing its own slice. | ||
| staging = torch.empty(staging_bytes, dtype=torch.uint8, pin_memory=True) | ||
| _STREAM_PINNED_STAGING[self.stream] = staging | ||
|
|
||
| offset = 0 | ||
| pinned_dict = {} | ||
| for param, tensor in self.cpu_param_dict.items(): | ||
| if staging is not None and _can_stage(tensor): | ||
| nbytes = tensor.numel() * tensor.element_size() | ||
| view = staging[offset : offset + nbytes].view(tensor.dtype).reshape(tensor.shape) | ||
| view.copy_(tensor) | ||
| pinned_dict[param] = view | ||
| offset += _staging_nbytes(tensor) | ||
| else: | ||
| pinned_dict[param] = _pin_memory(tensor) | ||
| else: | ||
| pinned_dict = {param: _pin_memory(tensor) for param, tensor in self.cpu_param_dict.items()} | ||
| yield pinned_dict | ||
| finally: | ||
| pinned_dict = None | ||
|
|
@@ -318,8 +361,8 @@ def _offload_to_disk(self): | |
| tensor_obj.data = torch.empty_like(tensor_obj.data, device=self.offload_device) | ||
|
|
||
| def _offload_to_memory(self): | ||
| if self.stream is not None: | ||
| if not self.record_stream: | ||
| if self.keep_cpu_copies: | ||
| if self.stream is not None and not self.record_stream: | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Checking |
||
| self._torch_accelerator_module.current_stream().synchronize() | ||
|
|
||
| for group_module in self.modules: | ||
|
|
@@ -817,6 +860,7 @@ def _apply_group_offloading_block_level(module: torch.nn.Module, config: GroupOf | |
| non_blocking=False, | ||
| stream=None, | ||
| record_stream=False, | ||
| low_cpu_mem_usage=config.low_cpu_mem_usage, | ||
| onload_self=True, | ||
| group_id=f"{config.module_prefix}{module.__class__.__name__}_unmatched_group", | ||
| ) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why does it have to be
torch.uint8?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The buffer holds raw bytes for tensors of different dtypes in the same group (e.g. an fp16 scale next to fp32 weights). With
uint8, sizes and offsets are byte counts, and each tensor getsstaging[offset : offset + nbytes].view(dtype).reshape(shape). Added a one-line comment.