Skip to content
Merged
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
12 changes: 10 additions & 2 deletions src/diffusers/hooks/group_offloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Comment on lines +171 to +175

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.

But this does have the risk of pressurizing the memory a little bit right?

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.

Yes, by the buffers' size and nothing else; parameters still get empty_like. With a 256 MiB parameter + 256 MiB buffer model, RSS after disk offload is 1138 MiB on main vs 1394 MiB here. Buffer bytes of the models I checked (fp32 as built from config; a bf16 load halves SD3's pos_embed, which is in the checkpoint, while the Wan RoPE tables are built at init and stay fp32): FLUX.2 Klein VAE 1 KiB (the three bn buffers); FLUX.2 Klein, FLUX.1 and Qwen-Image transformers, FLUX.1 and Wan VAEs 0; Wan2.2 transformer 1 MiB (RoPE); SD3 Medium pos_embed 216 MiB (2.8% of its parameters), SD3.5 Large 342 MiB (1.1%).

else:
self.cpu_param_dict = self._init_cpu_param_dict()

Expand Down Expand Up @@ -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.

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.

This is fine as long as buffers don't contribute too much.

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.

Agreed. SD3's pos_embed is the largest I know of; the other models I checked are at most 1 MiB.

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:
Expand Down
78 changes: 78 additions & 0 deletions tests/hooks/test_group_offloading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(

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.

Should also do an assert on the outputs with and without offloading.

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.

Added. The dummy forward now reads bn.running_mean / running_var directly, as the FLUX.2 pipelines do, and the test compares the output with a model without offloading. On main the output assert alone fails for the leaf_level disk cases; with block_level, bn is in the unmatched group that is onloaded for the forward, so the output is right and only the direct read after the forward sees the uninitialized buffers, which the buffer asserts cover.

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."
Loading