From 8824faa84665420c6e6e4bda084c91cc55c63c6f Mon Sep 17 00:00:00 2001 From: "Lin, KuanTing" Date: Wed, 18 Nov 2026 14:11:26 +0800 Subject: [PATCH 1/3] [group offloading] keep buffer values when offloading to disk Disk offloading replaced every offloaded tensor with an uninitialized torch.empty_like tensor. Buffers read without calling the module's forward (e.g. a VAE's batch norm running statistics read by the FLUX.2 pipelines) are never onloaded, so they held garbage. Keep buffer values on the offload device, as memory offloading does, and add a regression test. Signed-off-by: Lin, KuanTing --- src/diffusers/hooks/group_offloading.py | 17 ++++++- tests/hooks/test_group_offloading.py | 60 +++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 1 deletion(-) diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index 2c3ac131e4d8..349f90155be4 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -164,6 +164,10 @@ 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 = {} + self._disk_buffers = list( + dict.fromkeys([buffer for module in self.modules for buffer in module.buffers()] + self.buffers) + ) + self._offloaded_buffer_dict = None else: self.cpu_param_dict = self._init_cpu_param_dict() @@ -309,9 +313,20 @@ 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 + # Buffers are small and can be read without calling the module's forward (e.g. a pipeline reading a VAE's + # batch norm running statistics), so no onload happens. Keep their values on the offload device, as memory + # offloading does, instead of leaving uninitialized tensors. + if self._offloaded_buffer_dict is None: + self._offloaded_buffer_dict = { + buffer: buffer.data.to(self.offload_device) for buffer in self._disk_buffers + } + # We do this to free up the RAM which is still holding the up tensor data. 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._offloaded_buffer_dict: + tensor_obj.data = self._offloaded_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 08d3f4ed10b8..07adeb0dd9b6 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -694,3 +694,63 @@ 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) + return self.linear_2(x) + + +@require_torch_accelerator +class TestDirectBufferAccessGroupOffload: + in_features = 64 + hidden_features = 256 + out_features = 64 + num_layers = 2 + + 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("offload_to_disk", [False, True], ids=["memory", "disk"]) + def test_buffers_read_without_forward_keep_their_values(self, offload_type: str, offload_to_disk: bool, tmp_path): + """Buffers of a module whose forward is never called are never onloaded, so their offloaded copy must hold + the real values. + """ + 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, + 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(): + for _ in range(2): + model(x) + assert torch.equal(model.bn.running_mean.cpu(), running_mean) + assert torch.equal(model.bn.running_var.cpu(), running_var) From 94befe5a11670721b24dba140f7e0ec2301a92f3 Mon Sep 17 00:00:00 2001 From: "Lin, KuanTing" Date: Wed, 18 Nov 2026 14:22:51 +0800 Subject: [PATCH 2/3] [group offloading] build the buffer copies at init, cover streams in the test Build cpu_buffer_dict in __init__ next to cpu_param_dict instead of lazily, fix the comments (buffers are not always small), and parametrize the regression test over use_stream. Signed-off-by: Lin, KuanTing --- src/diffusers/hooks/group_offloading.py | 23 ++++++++--------------- tests/hooks/test_group_offloading.py | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/src/diffusers/hooks/group_offloading.py b/src/diffusers/hooks/group_offloading.py index 349f90155be4..50e5cfb0f913 100644 --- a/src/diffusers/hooks/group_offloading.py +++ b/src/diffusers/hooks/group_offloading.py @@ -164,10 +164,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 = {} - self._disk_buffers = list( - dict.fromkeys([buffer for module in self.modules for buffer in module.buffers()] + self.buffers) - ) - self._offloaded_buffer_dict = None + # 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,18 +314,10 @@ 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 - # Buffers are small and can be read without calling the module's forward (e.g. a pipeline reading a VAE's - # batch norm running statistics), so no onload happens. Keep their values on the offload device, as memory - # offloading does, instead of leaving uninitialized tensors. - if self._offloaded_buffer_dict is None: - self._offloaded_buffer_dict = { - buffer: buffer.data.to(self.offload_device) for buffer in self._disk_buffers - } - - # 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(): - if tensor_obj in self._offloaded_buffer_dict: - tensor_obj.data = self._offloaded_buffer_dict[tensor_obj] + 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) diff --git a/tests/hooks/test_group_offloading.py b/tests/hooks/test_group_offloading.py index 07adeb0dd9b6..9424804ad050 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -725,6 +725,10 @@ class TestDirectBufferAccessGroupOffload: 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( @@ -732,11 +736,17 @@ def get_model(self): ) @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, offload_to_disk: bool, tmp_path): - """Buffers of a module whose forward is never called are never onloaded, so their offloaded copy must hold - the real values. + 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. """ + 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 = self.get_model() running_mean = model.bn.running_mean.clone() running_var = model.bn.running_var.clone() @@ -745,6 +755,7 @@ def test_buffers_read_without_forward_keep_their_values(self, offload_type: str, 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, ) From 61a2a26a5663b4bb41e86cd4a6330dc9fd085003 Mon Sep 17 00:00:00 2001 From: "Lin, KuanTing" Date: Fri, 4 Dec 2026 16:41:20 +0800 Subject: [PATCH 3/3] [group offloading] compare outputs with and without offloading in the buffer test Signed-off-by: Lin, KuanTing --- tests/hooks/test_group_offloading.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/hooks/test_group_offloading.py b/tests/hooks/test_group_offloading.py index 9424804ad050..43c97d833507 100644 --- a/tests/hooks/test_group_offloading.py +++ b/tests/hooks/test_group_offloading.py @@ -715,7 +715,11 @@ def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.linear_1(x) for block in self.blocks: x = block(x) - return self.linear_2(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 @@ -742,11 +746,12 @@ 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. + 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() @@ -761,7 +766,9 @@ def test_buffers_read_without_forward_keep_their_values( x = torch.randn(4, self.in_features).to(torch_device) with torch.no_grad(): + out_ref = model_ref(x) for _ in range(2): - model(x) + 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."