Skip to content
Open
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
3 changes: 2 additions & 1 deletion src/diffusers/models/model_loading_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,8 @@ def load_state_dict(
if file_extension == SAFETENSORS_FILE_EXTENSION:
# `pread` reads tensor bytes with pread(2) instead of mapping the file.
backend = "pread" if disable_mmap else "mmap"
with safetensors.safe_open(checkpoint_file, framework="pt", device=map_location, backend=backend) as f:
device = str(map_location) if isinstance(map_location, torch.device) else map_location
with safetensors.safe_open(checkpoint_file, framework="pt", device=device, backend=backend) as f:
metadata = f.metadata() or {}
state_dict = f.get_tensors()
return _TorchStateDict(state_dict, metadata=metadata)
Expand Down
17 changes: 17 additions & 0 deletions tests/others/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,23 @@ def test_load_state_dict_carries_safetensors_metadata(self, tmp_path, disable_mm
assert list(state_dict.keys()) == ["weight"], f"Unexpected keys: {list(state_dict.keys())}"
assert state_dict.metadata == {"format": "pt", "alpha": "8"}, f"Unexpected metadata: {state_dict.metadata}"

@pytest.mark.parametrize("disable_mmap", [False, True])
@pytest.mark.parametrize("map_location", ["cpu", torch.device("cpu")], ids=["str", "torch.device"])
def test_load_state_dict_safetensors_map_location(self, tmp_path, disable_mmap, map_location):
import safetensors.torch

from diffusers.models.model_loading_utils import load_state_dict

checkpoint_file = os.path.join(tmp_path, "model.safetensors")
weight = torch.ones(2, 2, device="cpu")
metadata = {"format": "pt", "alpha": "8"}
safetensors.torch.save_file({"weight": weight}, checkpoint_file, metadata=metadata)

state_dict = load_state_dict(checkpoint_file, disable_mmap=disable_mmap, map_location=map_location)

torch.testing.assert_close(state_dict["weight"], weight)
assert state_dict.metadata == metadata

def test_load_state_dict_without_metadata(self, tmp_path):
import safetensors.torch
import torch
Expand Down