]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Early bailing when keys mismatch (faster). (#602)
authorNicolas Patry <patry.nicolas@protonmail.com>
Fri, 9 May 2025 07:03:12 +0000 (09:03 +0200)
committerGitHub <noreply@github.com>
Fri, 9 May 2025 07:03:12 +0000 (09:03 +0200)
* Early bailing when keys mismatch (faster).

* Add a few comments.

* NIT.

* Small fix.

bindings/python/py_src/safetensors/torch.py

index c3477aad384eeb56174537900cf0a264c1fc23bc..4b6acbca267b276e2d64372237ab456191b996cf 100644 (file)
@@ -128,7 +128,10 @@ def _remove_duplicate_names(
 
 
 def save_model(
-    model: torch.nn.Module, filename: str, metadata: Optional[Dict[str, str]] = None, force_contiguous: bool = True
+    model: torch.nn.Module,
+    filename: str,
+    metadata: Optional[Dict[str, str]] = None,
+    force_contiguous: bool = True,
 ):
     """
     Saves a given torch model to specified filename.
@@ -174,7 +177,10 @@ def save_model(
 
 
 def load_model(
-    model: torch.nn.Module, filename: Union[str, os.PathLike], strict: bool = True, device: Union[str, int] = "cpu"
+    model: torch.nn.Module,
+    filename: Union[str, os.PathLike],
+    strict: bool = True,
+    device: Union[str, int] = "cpu",
 ) -> Tuple[List[str], List[str]]:
     """
     Loads a given filename onto a torch model.
@@ -202,23 +208,68 @@ def load_model(
     state_dict = load_file(filename, device=device)
     model_state_dict = model.state_dict()
     to_removes = _remove_duplicate_names(model_state_dict, preferred_names=state_dict.keys())
-    missing, unexpected = model.load_state_dict(state_dict, strict=False)
-    missing = set(missing)
-    for to_remove_group in to_removes.values():
+
+    reverse_to_remove = {}
+    for key, to_remove_group in to_removes.items():
         for to_remove in to_remove_group:
-            if to_remove not in missing:
-                unexpected.append(to_remove)
-            else:
-                missing.remove(to_remove)
-    if strict and (missing or unexpected):
+            reverse_to_remove[to_remove] = key
+
+    # We iterate on the model, so we'll add keys we find missing
+    # here
+    missing = set()
+    # We start with all keys on disk declared as unexpected, we'll
+    # slowly remove them when we find them
+    unexpected = set(state_dict.keys())
+    # Some keys can be invalid too.
+    invalid = set()
+
+    for k, mv in model_state_dict.items():
+        actual_k = reverse_to_remove.get(k, None)
+        if actual_k is not None:
+            look_k = actual_k
+        else:
+            look_k = k
+        v = state_dict.get(look_k, None)
+        if v is None:
+            missing.add(k)
+        else:
+            # We can actually check for the shapes while we're at it.
+            # For the device, it's trickier given torch's internals
+            # There might be some Meta device for faster initiation
+            if v.dtype != mv.dtype or v.shape != mv.shape:
+                invalid.add(k)
+            if actual_k is None:
+                unexpected.remove(k)
+
+    missing = set(missing)
+    unexpected = set(unexpected)
+    if strict and (missing or unexpected or invalid):
         missing_keys = ", ".join([f'"{k}"' for k in sorted(missing)])
         unexpected_keys = ", ".join([f'"{k}"' for k in sorted(unexpected)])
+        invalid_keys = ", ".join([f'"{k}"' for k in sorted(invalid)])
         error = f"Error(s) in loading state_dict for {model.__class__.__name__}:"
         if missing:
             error += f"\n    Missing key(s) in state_dict: {missing_keys}"
         if unexpected:
             error += f"\n    Unexpected key(s) in state_dict: {unexpected_keys}"
+        if invalid:
+            error += f"\n    Invalid key(s) in state_dict: {invalid_keys}, mismatched dtypes or shape."
+        del state_dict
         raise RuntimeError(error)
+
+    torch_missing, torch_unexpected = model.load_state_dict(state_dict, strict=False)
+    # Sanity check that the work we've done matches
+    # Pytorch internal loading.
+    torch_missing = set(torch_missing)
+    torch_unexpected = set(torch_unexpected)
+    for to_remove_group in to_removes.values():
+        for to_remove in to_remove_group:
+            if to_remove not in torch_missing:
+                torch_unexpected.add(to_remove)
+            else:
+                torch_missing.remove(to_remove)
+    assert torch_missing == missing, f"{torch_missing} != {missing}"
+    assert torch_unexpected == unexpected, f"{torch_unexpected} != {unexpected}"
     return missing, unexpected