Skip to content

Fix duplicate safetensors.load_file call in _onload_from_disk #3

Open
gagandhakrey wants to merge 1 commit into
yfyang007:mainfrom
gagandhakrey:fix/group-offloading-duplicate-disk-load
Open

Fix duplicate safetensors.load_file call in _onload_from_disk #3
gagandhakrey wants to merge 1 commit into
yfyang007:mainfrom
gagandhakrey:fix/group-offloading-duplicate-disk-load

Conversation

@gagandhakrey

Copy link
Copy Markdown

In src/diffusers/hooks/group_offloading.py, ModuleGroup._onload_from_disk called safetensors.torch.load_file() twice when stream is None (the default, non-streaming path):

Called unconditionally — result discarded when stream is None

device = str(self.onload_device) if self.stream is None else "cpu"
loaded_tensors = safetensors.torch.load_file(
self.safetensors_file_path,
device=device,
)

if self.stream is not None:
...
else:
onload_device = (
self.onload_device.type
if isinstance(self.onload_device, torch.device)
else self.onload_device
)

# Second load — overwrites the first, which is silently discarded
loaded_tensors = safetensors.torch.load_file(
    self.safetensors_file_path,
    device=onload_device,
)

The first load result was immediately overwritten and garbage collected. As a result, every _onload_from_disk invocation in the default (use_stream=False) path performed two full tensor loads from disk while only using the second result.

Since offload_to_disk_path is typically used without streaming, this affected the documented and most common usage pattern.

Impact
2× disk I/O on every group load, slowing inference when disk offloading is enabled.
Transient 2× memory usage during loading (CPU memory and potentially VRAM depending on the target device), increasing the risk of OOM on memory-constrained systems.
Triggered on every _onload_from_disk call, which can occur hundreds or thousands of times during an inference run depending on model size and denoising steps.
Solution
Move the load_file() call into the corresponding execution branch so that tensors are loaded exactly once using the correct device argument for that path.

This removes the redundant disk read and avoids allocating an unused copy of the loaded tensors while preserving existing behavior.

…ream is None

Signed-off-by: Gagan Dhakrey <gagandhakrey@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant