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
52 changes: 48 additions & 4 deletions src/diffusers/hooks/group_offloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import hashlib
import os
import weakref
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass, replace
from enum import Enum
Expand All @@ -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.
Expand Down Expand Up @@ -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__()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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)

Copy link
Copy Markdown
Member

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?

Copy link
Copy Markdown
Contributor Author

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 gets staging[offset : offset + nbytes].view(dtype).reshape(shape). Added a one-line comment.

_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 +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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If offload_to_disk_path isn't specified then cpu_param_dict is always supposed to be populated. Isn't it better to check against offload_to_disk_path because stream and cpu_param_dict doesn't seem related from the code which is what makes the conditional a bit confusing to understand.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checking offload_to_disk_path can't tell the two branches apart here: offload_() only calls _offload_to_memory when offload_to_disk_path is None. Without a disk path, cpu_param_dict is empty when there is no stream and low_cpu_mem_usage=False. That group is moved back with .to(offload_device) (the else branch). I agree the old condition hid this, so it is now one flag set in __init__, keep_cpu_copies = stream is not None or low_cpu_mem_usage. Both the place that fills cpu_param_dict and this branch use it.

self._torch_accelerator_module.current_stream().synchronize()

for group_module in self.modules:
Expand Down Expand Up @@ -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",
)
Expand Down
45 changes: 45 additions & 0 deletions tests/hooks/test_group_offloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

from diffusers import AutoencoderKL
from diffusers.hooks import HookRegistry, ModelHook
from diffusers.hooks.group_offloading import _STREAM_PINNED_STAGING
from diffusers.models import ModelMixin
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
from diffusers.utils import logging as diffusers_logging
Expand Down Expand Up @@ -231,6 +232,27 @@ def forward(self, x: torch.Tensor) -> torch.Tensor:
return x


class MixedDtypeBlock(torch.nn.Module):
def __init__(self):
super().__init__()
self.half_scale = torch.nn.Parameter(torch.randn(7, dtype=torch.float16))
self.linear = torch.nn.Linear(7, 7)

def forward(self, x):
return self.linear(x) * self.half_scale.float()


class MixedDtypeModel(ModelMixin):
def __init__(self):
super().__init__()
self.blocks = torch.nn.ModuleList([MixedDtypeBlock() for _ in range(3)])

def forward(self, x):
for block in self.blocks:
x = block(x)
return x


@require_torch_accelerator
class TestGroupOffload:
in_features = 64
Expand Down Expand Up @@ -576,6 +598,29 @@ def test_nested_container_parameters_offloading(self):
f"Outputs do not match at iteration {i} for nested parameters."
)

def test_low_cpu_mem_usage_staging_handles_mixed_dtypes_with_odd_sizes(self):
# An odd number of fp16 elements followed by fp32 tensors must not misalign the fp32 views.
model = MixedDtypeModel().eval()
model_ref = MixedDtypeModel().eval()
model_ref.load_state_dict(model.state_dict())
model_ref.to(torch_device)
model.enable_group_offload(
torch_device,
offload_type="block_level",
num_blocks_per_group=1,
use_stream=True,
record_stream=True,
low_cpu_mem_usage=True,
)
x = torch.randn(2, 7, device=torch_device)
with torch.no_grad():
for _ in range(2):
assert torch.equal(model(x), model_ref(x))

block_hook = model.blocks[0]._diffusers_hook.get_hook("group_offloading")
staging = _STREAM_PINNED_STAGING.get(block_hook.group.stream)
assert staging is not None and staging.is_pinned()

def get_autoencoder_kl_config(self, block_out_channels=None, norm_num_groups=None):
block_out_channels = block_out_channels or [2, 4]
norm_num_groups = norm_num_groups or 2
Expand Down
13 changes: 13 additions & 0 deletions tests/models/autoencoders/test_models_autoencoder_magvit.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@
from .testing_utils import AutoencoderTesterMixin


LEAF_LEVEL_CONV_IN_STAYS_ONLOADED = pytest.mark.xfail(
reason="Leaf-level offloading with a stream leaves `decoder.conv_in` onloaded after the forward pass.",
raises=AssertionError,
strict=True,
)


enable_full_determinism()


Expand Down Expand Up @@ -98,6 +105,12 @@ def test_gradient_checkpointing_equivalence(self):
class TestAutoencoderKLMagvitMemory(AutoencoderKLMagvitTesterConfig, MemoryTesterMixin):
"""Memory optimization tests for AutoencoderKLMagvit."""

@pytest.mark.parametrize(
"offload_type", ["block_level", pytest.param("leaf_level", marks=LEAF_LEVEL_CONV_IN_STAYS_ONLOADED)]
)
def test_group_offloading_low_cpu_mem_usage_with_stream(self, base_model_output, offload_type):
super().test_group_offloading_low_cpu_mem_usage_with_stream(base_model_output, offload_type)


class TestAutoencoderKLMagvitSlicingTiling(AutoencoderKLMagvitTesterConfig, AutoencoderTesterMixin):
"""Slicing and tiling tests for AutoencoderKLMagvit."""
Expand Down
6 changes: 6 additions & 0 deletions tests/models/autoencoders/test_models_autoencoder_mmaudio.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,12 @@ def test_group_offloading_with_layerwise_casting(self, record_stream, offload_ty
def test_group_offloading_with_disk(self, tmp_path, record_stream, offload_type):
super().test_group_offloading_with_disk(tmp_path, record_stream, offload_type)

@pytest.mark.parametrize(
"offload_type", ["block_level", pytest.param("leaf_level", marks=NORMALIZATION_BUFFER_OFFLOAD)]
)
def test_group_offloading_low_cpu_mem_usage_with_stream(self, base_model_output, offload_type):
super().test_group_offloading_low_cpu_mem_usage_with_stream(base_model_output, offload_type)

@INCOMPLETE_DEVICE_MAP
def test_cpu_offload(self, base_model_output, tmp_path):
super().test_cpu_offload(base_model_output, tmp_path)
Expand Down
13 changes: 13 additions & 0 deletions tests/models/autoencoders/test_models_autoencoder_wan.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@
from .testing_utils import AutoencoderTesterMixin


LEAF_LEVEL_CONV_IN_STAYS_ONLOADED = pytest.mark.xfail(
reason="Leaf-level offloading with a stream leaves `decoder.conv_in` onloaded after the forward pass.",
raises=AssertionError,
strict=True,
)


enable_full_determinism()


Expand Down Expand Up @@ -89,6 +96,12 @@ def test_layerwise_casting_memory(self):
def test_layerwise_casting_training(self):
pass

@pytest.mark.parametrize(
"offload_type", ["block_level", pytest.param("leaf_level", marks=LEAF_LEVEL_CONV_IN_STAYS_ONLOADED)]
)
def test_group_offloading_low_cpu_mem_usage_with_stream(self, base_model_output, offload_type):
super().test_group_offloading_low_cpu_mem_usage_with_stream(base_model_output, offload_type)


class TestAutoencoderKLWanSlicingTiling(AutoencoderKLWanTesterConfig, AutoencoderTesterMixin):
"""Slicing and tiling tests for AutoencoderKLWan."""
Expand Down
6 changes: 6 additions & 0 deletions tests/models/autoencoders/test_models_kandinsky6_vocoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ def test_group_offloading_with_layerwise_casting(self, record_stream, offload_ty
def test_group_offloading_with_disk(self, tmp_path, record_stream, offload_type):
super().test_group_offloading_with_disk(tmp_path, record_stream, offload_type)

@pytest.mark.parametrize(
"offload_type", [pytest.param("block_level", marks=NESTED_UPSAMPLER_OFFLOAD), "leaf_level"]
)
def test_group_offloading_low_cpu_mem_usage_with_stream(self, base_model_output, offload_type):
super().test_group_offloading_low_cpu_mem_usage_with_stream(base_model_output, offload_type)


class TestMMAudioVocoderTorchCompile(MMAudioVocoderTesterConfig, TorchCompileTesterMixin):
@pytest.mark.xfail(
Expand Down
37 changes: 37 additions & 0 deletions tests/models/testing_utils/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,43 @@ def run_forward(model):
msg="Output should match with leaf-level offloading with stream",
)

@require_group_offload_support
@pytest.mark.parametrize("offload_type", ["block_level", "leaf_level"])
@torch.no_grad()
def test_group_offloading_low_cpu_mem_usage_with_stream(self, base_model_output, offload_type, atol=1e-5, rtol=0):
torch.manual_seed(0)
init_dict = self.get_init_dict()
inputs_dict = self.get_dummy_inputs()
model = self.model_class(**init_dict)
model.eval()
cpu_data_ptrs = {name: param.data_ptr() for name, param in model.named_parameters()}

group_offload_kwargs = {"num_blocks_per_group": 1} if offload_type == "block_level" else {}
model.enable_group_offload(
torch_device,
offload_type=offload_type,
use_stream=True,
record_stream=True,
low_cpu_mem_usage=True,
**group_offload_kwargs,
)
for _ in range(2):
reseed_generator_input(model, inputs_dict)
output = model(**inputs_dict)[0]
assert_tensors_close(
base_model_output,
output,
atol=atol,
rtol=rtol,
msg=f"Output should match with {offload_type} offloading with low_cpu_mem_usage and stream",
)

# Offloading must restore the original CPU tensors, not copy the weights back or pin them.
for name, param in model.named_parameters():
assert param.device.type == "cpu", f"{name} is not offloaded"
assert param.data_ptr() == cpu_data_ptrs[name], f"{name} no longer uses its original CPU storage"
assert not param.is_pinned(), f"{name} was pinned"

@require_group_offload_support
@pytest.mark.parametrize("record_stream", [False, True])
@pytest.mark.parametrize("offload_type", ["block_level", "leaf_level"])
Expand Down
Loading