diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index c9c56e23f143..5ab177c0256e 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -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: 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", ) diff --git a/tests/hooks/test_group_offloading.py b/tests/hooks/test_group_offloading.py index 799da9b0999f..c4741069303f 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -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 @@ -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 @@ -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 diff --git a/tests/models/autoencoders/test_models_autoencoder_magvit.py b/tests/models/autoencoders/test_models_autoencoder_magvit.py index bd16c0e03dad..10867e886e7e 100644 --- a/tests/models/autoencoders/test_models_autoencoder_magvit.py +++ b/tests/models/autoencoders/test_models_autoencoder_magvit.py @@ -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() @@ -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.""" diff --git a/tests/models/autoencoders/test_models_autoencoder_mmaudio.py b/tests/models/autoencoders/test_models_autoencoder_mmaudio.py index 45f47322a312..b1aea6f32ede 100644 --- a/tests/models/autoencoders/test_models_autoencoder_mmaudio.py +++ b/tests/models/autoencoders/test_models_autoencoder_mmaudio.py @@ -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) diff --git a/tests/models/autoencoders/test_models_autoencoder_wan.py b/tests/models/autoencoders/test_models_autoencoder_wan.py index b8026f575e49..aec272459c96 100644 --- a/tests/models/autoencoders/test_models_autoencoder_wan.py +++ b/tests/models/autoencoders/test_models_autoencoder_wan.py @@ -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() @@ -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.""" diff --git a/tests/models/autoencoders/test_models_kandinsky6_vocoder.py b/tests/models/autoencoders/test_models_kandinsky6_vocoder.py index 6cd66b51e218..011af3d3b240 100644 --- a/tests/models/autoencoders/test_models_kandinsky6_vocoder.py +++ b/tests/models/autoencoders/test_models_kandinsky6_vocoder.py @@ -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( diff --git a/tests/models/testing_utils/memory.py b/tests/models/testing_utils/memory.py index 79b1ea2e8739..5eb122684023 100644 --- a/tests/models/testing_utils/memory.py +++ b/tests/models/testing_utils/memory.py @@ -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"])