From cfdeeb12fc78752da883e2e8ffc88feb84f1556c Mon Sep 17 00:00:00 2001 From: Mert Kaya <47145541+mertkayacs@users.noreply.github.com> Date: Wed, 2 Dec 2026 17:49:20 +0300 Subject: [PATCH] fix(models): accept torch.device for safetensors map_location --- src/diffusers/models/model_loading_utils.py | 3 ++- tests/others/test_utils.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/diffusers/models/model_loading_utils.py b/src/diffusers/models/model_loading_utils.py index 74fbe9c61f91..09a1a01ea960 100644 --- a/src/diffusers/models/model_loading_utils.py +++ b/src/diffusers/models/model_loading_utils.py @@ -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) diff --git a/tests/others/test_utils.py b/tests/others/test_utils.py index dd4ed7c6c1ae..01f69e87a2cd 100755 --- a/tests/others/test_utils.py +++ b/tests/others/test_utils.py @@ -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