From a89edf5efeb1791bab8bdb7ad11d6f1907d96168 Mon Sep 17 00:00:00 2001 From: "Liu, Sylvan" Date: Thu, 12 Nov 2026 11:37:10 +0800 Subject: [PATCH 1/3] Optimize streamed low_cpu_mem_usage group offloading with a reused pinned staging buffer --- src/diffusers/hooks/group_offloading.py | 52 +++++++++++++++++-- tests/hooks/test_group_offloading.py | 46 ++++++++++++++++ .../test_models_autoencoder_magvit.py | 13 +++++ .../test_models_autoencoder_mmaudio.py | 6 +++ .../test_models_autoencoder_wan.py | 13 +++++ .../test_models_kandinsky6_vocoder.py | 6 +++ tests/models/testing_utils/memory.py | 37 +++++++++++++ 7 files changed, 169 insertions(+), 4 deletions(-) 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..01cc2a7a343f 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 @@ -711,3 +712,48 @@ def test_conditional_modules_with_stream(self, offload_type: str): assert torch.allclose(out_ref_no_opt2, out_no_opt2, atol=1e-5), ( f"[{offload_type}] Outputs do not match on third pass (back to no optional_input)." ) + + +@require_torch_accelerator +class TestGroupOffloadingLowCpuMemStaging: + 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. + class MixedBlock(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 MixedModel(ModelMixin): + def __init__(self): + super().__init__() + self.blocks = torch.nn.ModuleList([MixedBlock() for _ in range(3)]) + + def forward(self, x): + for block in self.blocks: + x = block(x) + return x + + model = MixedModel().eval() + model_ref = MixedModel().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() 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"]) From c7b8f23c1cd9727466fbf4e7b72c30c89fe6a620 Mon Sep 17 00:00:00 2001 From: Sylvan Liu Date: Mon, 30 Nov 2026 17:44:43 +0800 Subject: [PATCH 2/3] Add pin_cpu_memory_in_place to page-lock offloaded CPU weights where they live Each memory-mapped file that holds the module's CPU tensors is page-locked as a whole with cudaHostRegister, so streamed onloading copies straight from the page cache. Whole mappings are registered, never page-rounded tensor spans: a host copy that lies partly inside a registration is rejected, which broke unregistered neighbours sharing the edge pages. Registrations are reference-counted across modules and released when the last module using them is collected. --- src/diffusers/hooks/group_offloading.py | 117 ++++++++++++++++++++ src/diffusers/models/modeling_utils.py | 2 + src/diffusers/pipelines/pipeline_utils.py | 6 + tests/hooks/test_group_offloading.py | 129 +++++++++++++++++++++- 4 files changed, 253 insertions(+), 1 deletion(-) diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index 5ab177c0256e..3e4e51ece192 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -12,7 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +import bisect import hashlib +import itertools import os import weakref from contextlib import contextmanager, nullcontext @@ -40,6 +42,9 @@ _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: @@ -129,6 +134,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: @@ -624,6 +630,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 @@ -688,6 +695,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 @@ -725,6 +740,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'.") @@ -748,6 +767,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) @@ -759,6 +779,103 @@ 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 _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: + # 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: diff --git a/src/diffusers/models/modeling_utils.py b/src/diffusers/models/modeling_utils.py index 858b967d774e..f119ea5457b9 100644 --- a/src/diffusers/models/modeling_utils.py +++ b/src/diffusers/models/modeling_utils.py @@ -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. @@ -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: diff --git a/src/diffusers/pipelines/pipeline_utils.py b/src/diffusers/pipelines/pipeline_utils.py index a6da30255485..56ee7d8a7de4 100644 --- a/src/diffusers/pipelines/pipeline_utils.py +++ b/src/diffusers/pipelines/pipeline_utils.py @@ -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, @@ -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 @@ -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): diff --git a/tests/hooks/test_group_offloading.py b/tests/hooks/test_group_offloading.py index 01cc2a7a343f..b417ab731d77 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -17,11 +17,12 @@ import logging import pytest +import safetensors.torch import torch from diffusers import AutoencoderKL from diffusers.hooks import HookRegistry, ModelHook -from diffusers.hooks.group_offloading import _STREAM_PINNED_STAGING +from diffusers.hooks.group_offloading import _HOST_REGISTERED_RANGES, _STREAM_PINNED_STAGING from diffusers.models import ModelMixin from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.utils import logging as diffusers_logging @@ -757,3 +758,129 @@ def forward(self, 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() + + +@require_torch_accelerator +class TestGroupOffloadingPinCpuMemoryInPlace: + def test_pin_in_place_skips_staging_and_matches_reference(self, tmp_path): + model = DummyModel(16, 32, 16, num_layers=3).eval() + ckpt = tmp_path / "dummy.safetensors" + safetensors.torch.save_file(model.state_dict(), str(ckpt)) + model.load_state_dict(safetensors.torch.load_file(str(ckpt), device="cpu"), assign=True) + orig_ptrs = {name: param.data_ptr() for name, param in model.named_parameters()} + + model_ref = DummyModel(16, 32, 16, num_layers=3).eval() + model_ref.load_state_dict(model.state_dict(), strict=True) + 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, + pin_cpu_memory_in_place=True, + ) + for name, param in model.named_parameters(): + assert param.device.type == "cpu" + assert param.data_ptr() == orig_ptrs[name] + assert param.is_pinned(), name + + x = torch.randn(4, 16, device=torch_device) + with torch.no_grad(): + for _ in range(3): + assert torch.allclose(model(x), model_ref(x), atol=1e-5) + + block_hook = model.blocks[0]._diffusers_hook.get_hook("group_offloading") + assert _STREAM_PINNED_STAGING.get(block_hook.group.stream) is None + for name, param in model.named_parameters(): + assert param.data_ptr() == orig_ptrs[name] + + def test_pin_in_place_requires_streamed_low_cpu_mem_usage(self): + model = DummyModel(16, 32, 16, num_layers=1) + with pytest.raises(ValueError, match="pin_cpu_memory_in_place"): + model.enable_group_offload( + torch_device, offload_type="block_level", num_blocks_per_group=1, pin_cpu_memory_in_place=True + ) + + def test_pin_in_place_shared_pages_stay_registered_until_last_owner(self, tmp_path): + # Both models view the same mmap, so their page ranges overlap. + ckpt = tmp_path / "dummy.safetensors" + safetensors.torch.save_file(DummyModel(16, 32, 16, num_layers=2).state_dict(), str(ckpt)) + shared = safetensors.torch.load_file(str(ckpt), device="cpu") + first, second = DummyModel(16, 32, 16, num_layers=2).eval(), DummyModel(16, 32, 16, num_layers=2).eval() + for model in (first, second): + model.load_state_dict(shared, assign=True) + del model, shared + kwargs = { + "offload_type": "block_level", + "num_blocks_per_group": 1, + "use_stream": True, + "low_cpu_mem_usage": True, + "pin_cpu_memory_in_place": True, + } + gc.collect() + before = len(_HOST_REGISTERED_RANGES) + first.enable_group_offload(torch_device, **kwargs) + second.enable_group_offload(torch_device, **kwargs) + x = torch.randn(4, 16, device=torch_device) + with torch.no_grad(): + expected = second(x) + + del first + gc.collect() + assert all(param.is_pinned() for param in second.parameters()) + with torch.no_grad(): + assert torch.equal(second(x), expected) + + del second + gc.collect() + assert len(_HOST_REGISTERED_RANGES) == before + + def test_pin_in_place_never_partially_covers_a_tensor(self, tmp_path): + # Odd sizes: the last weight shares a page with "zzz_other", which safetensors stores after it and which + # extends past that page. + model = DummyModel(15, 33, 17, num_layers=2).eval() + ckpt = tmp_path / "dummy.safetensors" + safetensors.torch.save_file({**model.state_dict(), "zzz_other": torch.randn(64, 32)}, str(ckpt)) + loaded = safetensors.torch.load_file(str(ckpt), device="cpu") + other = loaded.pop("zzz_other") + model.load_state_dict(loaded, assign=True) + model.enable_group_offload( + torch_device, + offload_type="block_level", + num_blocks_per_group=1, + use_stream=True, + low_cpu_mem_usage=True, + pin_cpu_memory_in_place=True, + ) + assert all(param.is_pinned() for param in model.parameters()) + + for tensor in [other, *loaded.values()]: + begin = tensor.untyped_storage().data_ptr() + end = begin + tensor.untyped_storage().nbytes() + overlapping = [(s, e) for s, e in _HOST_REGISTERED_RANGES if s < end and begin < e] + assert len(overlapping) == 1 and overlapping[0][0] <= begin and end <= overlapping[0][1] + assert torch.equal(other.to(torch_device).cpu(), other) + + def test_pin_in_place_leaves_tensors_not_in_a_file_to_staging(self): + model = DummyModel(16, 32, 16, num_layers=2).eval() + model_ref = DummyModel(16, 32, 16, num_layers=2).eval() + model_ref.load_state_dict(model.state_dict()) + model_ref.to(torch_device) + gc.collect() + before = len(_HOST_REGISTERED_RANGES) + model.enable_group_offload( + torch_device, + offload_type="block_level", + num_blocks_per_group=1, + use_stream=True, + low_cpu_mem_usage=True, + pin_cpu_memory_in_place=True, + ) + assert len(_HOST_REGISTERED_RANGES) == before + assert not any(param.is_pinned() for param in model.parameters()) + x = torch.randn(4, 16, device=torch_device) + with torch.no_grad(): + assert torch.equal(model(x), model_ref(x)) From a405aa397c80d3f8c704cfdd6293bf5d55a34250 Mon Sep 17 00:00:00 2001 From: Sylvan Liu Date: Thu, 3 Dec 2026 09:48:37 +0800 Subject: [PATCH 3/3] [group offloading] Clear the pending error after a failed cudaHostRegister attempt --- src/diffusers/hooks/group_offloading.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index 3e4e51ece192..f91b1a35cd4f 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -13,6 +13,7 @@ # limitations under the License. import bisect +import ctypes import hashlib import itertools import os @@ -865,11 +866,30 @@ def _pin_cpu_tensors_in_place(module: torch.nn.Module) -> None: 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: + 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]