From f9b4a932d57a60dfdf4aa149c8fe7763c64172c4 Mon Sep 17 00:00:00 2001 From: Nicolas Patry Date: Wed, 23 Nov 2022 15:41:15 +0100 Subject: [PATCH] Fix `convert.py` to handle diffusers, and its transformers part (#105) 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 | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/bindings/python/convert.py b/bindings/python/convert.py index d08abac..c116da0 100644 --- a/bindings/python/convert.py +++ b/bindings/python/convert.py @@ -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}" -- 2.43.0