Fix duplicate safetensors.load_file call in _onload_from_disk when st…#13851
Conversation
…ream is None Signed-off-by: Gagan Dhakrey <[email protected]>
|
Hey @AryanV @sayakpaul, I found a bug in |
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
|
Thanks @DN6 for the review, looks like CI is green as well , just checking if there is anything else needed from my side so this can be merged |
|
|
||
| if self.stream is not None: | ||
| # Load to CPU first, pin memory, then async copy to the target device | ||
| loaded_tensors = safetensors.torch.load_file(self.safetensors_file_path, device="cpu") |
There was a problem hiding this comment.
Why should it have to be conditioned on if self.strea is not None?
There was a problem hiding this comment.
@sayakpaul these two branches handle tensors differently after loading , the stream is not None branch needs device="cpu" specifically because it calls .pin_memory() on the tensor before doing a non_blocking async copy to the device — pinned memory is required for async host->device transfers to work correctly, the else branch loads directly to the target device and assigns immediately with no intermediate step, so there's no need to go through cpu at all , making the load unconditional with "cpu" would add an unnecessary CPU->device transfer in the no-stream path
#13851) Fix duplicate safetensors.load_file call in _onload_from_disk when stream is None Signed-off-by: Gagan Dhakrey <[email protected]> Co-authored-by: Sayak Paul <[email protected]>
Fix: Duplicate
safetensors.load_fileCall in_onload_from_diskProblem
In
src/diffusers/hooks/group_offloading.py,ModuleGroup._onload_from_diskcalledsafetensors.torch.load_file()twice whenstream is None(the default, non-streaming path):The first load result was immediately overwritten and garbage collected. As a result, every
_onload_from_diskinvocation in the default (use_stream=False) path performed two full tensor loads from disk while only using the second result.Since
offload_to_disk_pathis typically used without streaming, this affected the documented and most common usage pattern.Impact
_onload_from_diskcall, 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.