]> khamidou — GitHub mirrors - safetensors.git/commitdiff
Fix `convert.py` to handle diffusers, and its transformers part (#105)
authorNicolas Patry <patry.nicolas@protonmail.com>
Wed, 23 Nov 2022 14:41:15 +0000 (15:41 +0100)
committerGitHub <noreply@github.com>
Wed, 23 Nov 2022 14:41:15 +0000 (15:41 +0100)
Turns out `diffusers` does rely on `transformers`:

`pytorch_model.safetensors` was not a recognized filename by
`transformers` which expects it to be named `model.safetensors`.

The convert_generic works by simply creating the new files and changing
the extension, which broke this.

Current proposed fix is to handle specially files named
`pytorch_model.bin` since they are more likely to be `transformers`
files.

This is however not necessarily true, we might want to protect with
checking against `model_info.library_name` though I feel like this is
better to just check against the name, since it's still likely to be a
transformers/diffusers/sentence-transformers thing.

bindings/python/convert.py

index d08abac17a0e7dad8bd550f5347526add1fadcbf..c116da02116d8b3d7b98799b27c9a81bb7c26e83 100644 (file)
@@ -200,7 +200,13 @@ def convert_generic(model_id: str, folder: str, filenames: Set[str]) -> List["Co
         prefix, ext = os.path.splitext(filename)
         if ext in extensions:
             pt_filename = hf_hub_download(model_id, filename=filename)
-            sf_in_repo = f"{prefix}.safetensors"
+            _, raw_filename = os.path.split(filename)
+            if raw_filename == "pytorch_model.bin":
+                # XXX: This is a special case to handle `transformers` and the
+                # `transformers` part of the model which is actually loaded by `transformers`.
+                sf_in_repo = "model.safetensors"
+            else:
+                sf_in_repo = f"{prefix}.safetensors"
             sf_filename = os.path.join(folder, sf_in_repo)
             convert_file(pt_filename, sf_filename)
             operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
@@ -219,7 +225,7 @@ def convert(api: "HfApi", model_id: str, force: bool = False) -> Optional["Commi
         try:
             operations = None
             pr = previous_pr(api, model_id, pr_title)
-            if ("model.safetensors" in filenames or "model_index.safetensors.index.json" in filenames) and not force:
+            if any(filename.endswith(".safetensors") for filename in filenames) and not force:
                 raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
             elif pr is not None and not force:
                 url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"