diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index c9c56e23f143..994d846ef359 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -168,6 +168,11 @@ def __init__( self.tensor_to_key = {tensor: f"tensor_{i}" for i, tensor in enumerate(all_tensors)} self.key_to_tensor = {v: k for k, v in self.tensor_to_key.items()} self.cpu_param_dict = {} + # Buffers can be read without calling the forward of the module that owns them (e.g. a pipeline reading a + # VAE's batch norm running statistics), so they may never be onloaded. Keep their values on the offload + # device instead of the uninitialized tensors that offloaded parameters get. + buffers = [buffer for module in self.modules for buffer in module.buffers()] + self.buffers + self.cpu_buffer_dict = {buffer: buffer.data.to(self.offload_device) for buffer in buffers} else: self.cpu_param_dict = self._init_cpu_param_dict() @@ -313,9 +318,12 @@ def _offload_to_disk(self): # The group is now considered offloaded to disk for the rest of the session. self._is_offloaded_to_disk = True - # We do this to free up the RAM which is still holding the up tensor data. + # Free the RAM held by the parameters; they are reloaded from disk on onload. Buffers keep their values. for tensor_obj in self.tensor_to_key.keys(): - tensor_obj.data = torch.empty_like(tensor_obj.data, device=self.offload_device) + if tensor_obj in self.cpu_buffer_dict: + tensor_obj.data = self.cpu_buffer_dict[tensor_obj] + else: + tensor_obj.data = torch.empty_like(tensor_obj.data, device=self.offload_device) def _offload_to_memory(self): if self.stream is not None: diff --git a/tests/hooks/test_group_offloading.py b/tests/hooks/test_group_offloading.py index 799da9b0999f..9d7b0fccb650 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -711,3 +711,81 @@ 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)." ) + + +# Model whose batch norm running statistics are read directly, without calling the batch norm's forward, like +# pipelines reading `vae.bn.running_mean` / `vae.bn.running_var` of `AutoencoderKLFlux2`. +class DummyModelWithStandaloneBatchNorm(ModelMixin): + def __init__(self, in_features: int, hidden_features: int, out_features: int, num_layers: int) -> None: + super().__init__() + + self.linear_1 = torch.nn.Linear(in_features, hidden_features) + self.blocks = torch.nn.ModuleList( + [DummyBlock(hidden_features, hidden_features, hidden_features) for _ in range(num_layers)] + ) + self.linear_2 = torch.nn.Linear(hidden_features, out_features) + self.bn = torch.nn.BatchNorm1d(out_features, affine=False, track_running_stats=True) + self.bn.running_mean.copy_(torch.linspace(-1.0, 1.0, out_features)) + self.bn.running_var.copy_(torch.linspace(0.5, 2.0, out_features)) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = self.linear_1(x) + for block in self.blocks: + x = block(x) + x = self.linear_2(x) + # Read the running statistics directly instead of calling `self.bn`, like the FLUX.2 pipelines do. + mean = self.bn.running_mean.to(x.device, x.dtype) + var = self.bn.running_var.to(x.device, x.dtype) + return (x - mean) / torch.sqrt(var + self.bn.eps) + + +@require_torch_accelerator +class TestDirectBufferAccessGroupOffload: + in_features = 64 + hidden_features = 256 + out_features = 64 + num_layers = 2 + + def teardown_method(self): + gc.collect() + backend_empty_cache(torch_device) + + def get_model(self): + torch.manual_seed(0) + return DummyModelWithStandaloneBatchNorm( + self.in_features, self.hidden_features, self.out_features, self.num_layers + ) + + @pytest.mark.parametrize("offload_type", ["leaf_level", "block_level"]) + @pytest.mark.parametrize("use_stream", [False, True], ids=["no_stream", "stream"]) + @pytest.mark.parametrize("offload_to_disk", [False, True], ids=["memory", "disk"]) + def test_buffers_read_without_forward_keep_their_values( + self, offload_type: str, use_stream: bool, offload_to_disk: bool, tmp_path + ): + """Buffers read directly, without calling the forward of the module that owns them, must hold their real + values while offloaded, and the outputs must match the model without offloading. + """ + if use_stream and torch.device(torch_device).type not in ["cuda", "xpu"]: + pytest.skip("Test requires a CUDA or XPU device for streams.") + + model_ref = self.get_model().to(torch_device) + model = self.get_model() + running_mean = model.bn.running_mean.clone() + running_var = model.bn.running_var.clone() + + model.enable_group_offload( + torch_device, + offload_type=offload_type, + num_blocks_per_group=1, + use_stream=use_stream, + offload_to_disk_path=str(tmp_path) if offload_to_disk else None, + ) + + x = torch.randn(4, self.in_features).to(torch_device) + with torch.no_grad(): + out_ref = model_ref(x) + for _ in range(2): + out = model(x) + assert torch.equal(model.bn.running_mean.cpu(), running_mean) + assert torch.equal(model.bn.running_var.cpu(), running_var) + assert torch.allclose(out_ref, out, atol=1e-5), "Outputs do not match with and without offloading."