Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
189 changes: 185 additions & 4 deletions src/diffusers/hooks/group_offloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import bisect
import ctypes
import hashlib
import itertools
import os
import weakref
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, replace
from enum import Enum
Expand All @@ -36,6 +40,13 @@

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
# (start, end) of a whole file mapping -> [number of modules using it, CPU tensors keeping the mapping alive]
_HOST_REGISTERED_RANGES: dict[tuple[int, int], list] = {}
_CUDA_HOST_REGISTER_READ_ONLY = 8


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.
Expand Down Expand Up @@ -77,6 +88,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__()
Expand Down Expand Up @@ -115,6 +135,7 @@ class GroupOffloadingConfig:
block_modules: list[str] | None = None
exclude_kwargs: list[str] | None = None
module_prefix: str = ""
pin_cpu_memory_in_place: bool = False


class ModuleGroup:
Expand Down Expand Up @@ -147,6 +168,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
Expand Down Expand Up @@ -183,7 +207,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:
Expand All @@ -203,7 +227,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
Expand Down Expand Up @@ -318,8 +368,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:
self._torch_accelerator_module.current_stream().synchronize()

for group_module in self.modules:
Expand Down Expand Up @@ -581,6 +631,7 @@ def apply_group_offloading(
offload_to_disk_path: str | None = None,
block_modules: list[str] | None = None,
exclude_kwargs: list[str] | None = None,
pin_cpu_memory_in_place: bool = False,
) -> None:
r"""
Applies group offloading to the internal layers of a torch.nn.Module. To understand what group offloading is, and
Expand Down Expand Up @@ -645,6 +696,14 @@ def apply_group_offloading(
List of kwarg keys that should not be processed by send_to_device. This is useful for mutable state like
caching lists that need to maintain their object identity across forward passes. If not provided, will be
inferred from the module's `_skip_keys` attribute if it exists.
pin_cpu_memory_in_place (`bool`, defaults to `False`):
Only used with `use_stream=True` and `low_cpu_mem_usage=True`. If True, CPU tensors of the module that are
views of a memory-mapped file (as loaded from safetensors with `low_cpu_mem_usage=True`) are page-locked
where they live with `cudaHostRegister`, so streamed onloading copies them to the device directly instead
of first copying them into a pinned buffer on every forward pass. Each file mapping is registered as a
whole, so every tensor of that file is pinned, and its pages stay resident and cannot be reclaimed by the
OS until the module is garbage collected. No second copy of the weights is allocated. Other CPU tensors,
and every tensor on platforms without `/proc/self/maps`, use the pinned staging path.

Example:
```python
Expand Down Expand Up @@ -682,6 +741,10 @@ def apply_group_offloading(

if not use_stream and record_stream:
raise ValueError("`record_stream` cannot be True when `use_stream=False`.")
if pin_cpu_memory_in_place and not (use_stream and low_cpu_mem_usage and offload_to_disk_path is None):
raise ValueError(
"`pin_cpu_memory_in_place=True` requires `use_stream=True`, `low_cpu_mem_usage=True` and no `offload_to_disk_path`."
)
if offload_type == GroupOffloadingType.BLOCK_LEVEL and num_blocks_per_group is None:
raise ValueError("`num_blocks_per_group` must be provided when using `offload_type='block_level'.")

Expand All @@ -705,6 +768,7 @@ def apply_group_offloading(
offload_to_disk_path=offload_to_disk_path,
block_modules=block_modules,
exclude_kwargs=exclude_kwargs,
pin_cpu_memory_in_place=pin_cpu_memory_in_place,
)
_apply_group_offloading(module, config)

Expand All @@ -716,6 +780,122 @@ def _apply_group_offloading(module: torch.nn.Module, config: GroupOffloadingConf
_apply_group_offloading_leaf_level(module, config)
else:
assert False
if config.pin_cpu_memory_in_place:
_pin_cpu_tensors_in_place(module)


def _release_host_ranges(ranges: list[tuple[int, int]]) -> None:
cudart = torch.cuda.cudart()
for key in ranges:
entry = _HOST_REGISTERED_RANGES[key]
entry[0] -= 1
if entry[0] > 0:
continue
if int(cudart.cudaHostUnregister(key[0])) != 0:
logger.warning(f"Could not unregister the page-locked CPU range at {key[0]:#x}.")
del _HOST_REGISTERED_RANGES[key]


def _file_mappings() -> list[tuple[int, int]]:
# Linux only; elsewhere nothing is page-locked in place.
try:
with open("/proc/self/maps") as f:
lines = f.readlines()
except OSError:
return []
mappings = []
for line in lines:
fields = line.split(maxsplit=5)
if len(fields) == 6 and fields[5].startswith("/") and not fields[5].startswith(("/dev/", "/memfd:")):
start, end = fields[0].split("-")
mappings.append((int(start, 16), int(end, 16)))
return sorted(mappings)


def _pin_cpu_tensors_in_place(module: torch.nn.Module) -> None:
if not torch.cuda.is_available():
logger.warning("`pin_cpu_memory_in_place=True` needs a CUDA/ROCm device; falling back to pinned staging.")
return
# Whole file mappings are registered, never parts of one: CUDA rejects a copy that lies partly inside a
# registration, so page-rounded spans would break unregistered neighbours sharing the edge pages.
mappings = _file_mappings()
starts = [start for start, _ in mappings]
tensors_by_mapping: dict[tuple[int, int], list[torch.Tensor]] = {}
rejected = set()
num_skipped = 0
for tensor in itertools.chain(module.parameters(), module.buffers()):
if tensor.device.type != "cpu" or tensor.numel() == 0 or is_traceable_wrapper_subclass(tensor):
continue
storage = tensor.untyped_storage()
begin, end = storage.data_ptr(), storage.data_ptr() + storage.nbytes()
overlapping = []
i = max(bisect.bisect_right(starts, begin) - 1, 0)
while i < len(mappings) and mappings[i][0] < end:
if begin < mappings[i][1]:
overlapping.append(mappings[i])
i += 1
inside = len(overlapping) == 1 and overlapping[0][0] <= begin and end <= overlapping[0][1]
# Pinned through an existing registration: share it. Pinned any other way: leave the mapping alone.
if not inside or (tensor.is_pinned() and overlapping[0] not in _HOST_REGISTERED_RANGES):
rejected.update(overlapping)
num_skipped += 1
continue
tensors_by_mapping.setdefault(overlapping[0], []).append(tensor.data)

cudart = torch.cuda.cudart()
held = []
for mapping, tensors in tensors_by_mapping.items():
if mapping in _HOST_REGISTERED_RANGES:
_HOST_REGISTERED_RANGES[mapping][0] += 1
held.append(mapping)
elif mapping not in rejected and _register_host_range(cudart, mapping, tensors):
held.append(mapping)
else:
num_skipped += len(tensors)
if num_skipped and not held:
logger.warning(
"`pin_cpu_memory_in_place=True` has no effect: none of the CPU tensors is a view of a memory-mapped file "
"that can be page-locked as a whole (load the model from safetensors with `low_cpu_mem_usage=True`)."
)
elif num_skipped:
logger.info(
f"{num_skipped} CPU tensors are not views of a memory-mapped file that can be page-locked as a whole; "
"they use pinned staging."
)
if held:
weakref.finalize(module, _release_host_ranges, held)


def _clear_last_cuda_error() -> None:
# A failed `cudaHostRegister` leaves its error pending, and PyTorch would raise it at the next kernel launch.
# `torch.cuda.cudart()` does not expose `cudaGetLastError`, so call it on the runtime library that is loaded.
for library, name in (
("libcudart.so.13", "cudaGetLastError"),
("libcudart.so.12", "cudaGetLastError"),
("libcudart.so.11.0", "cudaGetLastError"),
("libamdhip64.so.7", "hipGetLastError"),
("libamdhip64.so.6", "hipGetLastError"),
):
try:
getattr(ctypes.CDLL(library), name)()
return
except (OSError, AttributeError):
continue


def _register_host_range(cudart, mapping: tuple[int, int], keepalive: list[torch.Tensor]) -> bool:
start, end = mapping
# Read-only first: memory-mapped checkpoints are usually mapped without write permission.
for flags in (_CUDA_HOST_REGISTER_READ_ONLY, 0):
if int(cudart.cudaHostRegister(start, end - start, flags)) != 0:
_clear_last_cuda_error()
else:
# The backing tensors (and so their mmap) live as long as the registration: unmapping a still-registered
# range corrupts the runtime's host-memory tracking.
_HOST_REGISTERED_RANGES[mapping] = [1, keepalive]
return True
logger.warning("Could not page-lock a memory-mapped CPU range in place; it will use pinned staging instead.")
return False


def _apply_group_offloading_block_level(module: torch.nn.Module, config: GroupOffloadingConfig) -> None:
Expand Down Expand Up @@ -817,6 +997,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",
)
Expand Down
2 changes: 2 additions & 0 deletions src/diffusers/models/modeling_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -538,6 +538,7 @@ def enable_group_offload(
offload_to_disk_path: str | None = None,
block_modules: str | None = None,
exclude_kwargs: str | None = None,
pin_cpu_memory_in_place: bool = False,
) -> None:
r"""
Activates group offloading for the current model.
Expand Down Expand Up @@ -599,6 +600,7 @@ def enable_group_offload(
offload_to_disk_path=offload_to_disk_path,
block_modules=block_modules,
exclude_kwargs=exclude_kwargs,
pin_cpu_memory_in_place=pin_cpu_memory_in_place,
)

def set_attention_backend(self, backend: str) -> None:
Expand Down
6 changes: 6 additions & 0 deletions src/diffusers/pipelines/pipeline_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,7 @@ def enable_group_offload(
low_cpu_mem_usage=False,
offload_to_disk_path: str | None = None,
exclude_modules: str | list[str] | None = None,
pin_cpu_memory_in_place: bool = False,
) -> None:
r"""
Applies group offloading to the internal layers of a torch.nn.Module. To understand what group offloading is,
Expand Down Expand Up @@ -1412,6 +1413,10 @@ def enable_group_offload(
This option only matters when using streamed CPU offloading (i.e. `use_stream=True`). This can be
useful when the CPU memory is a bottleneck but may counteract the benefits of using streams.
exclude_modules (`Union[str, List[str]]`, defaults to `None`): List of modules to exclude from offloading.
pin_cpu_memory_in_place (`bool`, defaults to `False`):
Only used with `use_stream=True` and `low_cpu_mem_usage=True`. Page-locks the memory-mapped checkpoint
files the offloaded CPU weights live in, instead of copying the weights into a pinned buffer on every
forward pass. See [`~hooks.group_offloading.apply_group_offloading`].

Example:
```python
Expand Down Expand Up @@ -1452,6 +1457,7 @@ def enable_group_offload(
"record_stream": record_stream,
"low_cpu_mem_usage": low_cpu_mem_usage,
"offload_to_disk_path": offload_to_disk_path,
"pin_cpu_memory_in_place": pin_cpu_memory_in_place,
}
for name, component in self.components.items():
if name not in exclude_modules and isinstance(component, torch.nn.Module):
Expand Down
Loading