Commit
·
8cf228f
1
Parent(s):
1b9d4e3
Update convert.py
Browse files- convert.py +116 -131
convert.py
CHANGED
|
@@ -3,7 +3,6 @@ import json
|
|
| 3 |
import os
|
| 4 |
import shutil
|
| 5 |
from collections import defaultdict
|
| 6 |
-
from inspect import signature
|
| 7 |
from tempfile import TemporaryDirectory
|
| 8 |
from typing import Dict, List, Optional, Set, Tuple
|
| 9 |
|
|
@@ -11,8 +10,7 @@ import torch
|
|
| 11 |
|
| 12 |
from huggingface_hub import CommitInfo, CommitOperationAdd, Discussion, HfApi, hf_hub_download
|
| 13 |
from huggingface_hub.file_download import repo_folder_name
|
| 14 |
-
from safetensors.torch import load_file,
|
| 15 |
-
from transformers import AutoConfig
|
| 16 |
|
| 17 |
|
| 18 |
COMMIT_DESCRIPTION = """
|
|
@@ -34,20 +32,78 @@ Feel free to ignore this PR.
|
|
| 34 |
|
| 35 |
ConversionResult = Tuple[List["CommitOperationAdd"], List[Tuple[str, "Exception"]]]
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
|
|
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
|
| 52 |
|
| 53 |
def check_file_size(sf_filename: str, pt_filename: str):
|
|
@@ -70,8 +126,8 @@ def rename(pt_filename: str) -> str:
|
|
| 70 |
return local
|
| 71 |
|
| 72 |
|
| 73 |
-
def convert_multi(model_id: str, folder: str, token: Optional[str]) -> ConversionResult:
|
| 74 |
-
filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json", token=token, cache_dir=folder)
|
| 75 |
with open(filename, "r") as f:
|
| 76 |
data = json.load(f)
|
| 77 |
|
|
@@ -82,7 +138,7 @@ def convert_multi(model_id: str, folder: str, token: Optional[str]) -> Conversio
|
|
| 82 |
|
| 83 |
sf_filename = rename(pt_filename)
|
| 84 |
sf_filename = os.path.join(folder, sf_filename)
|
| 85 |
-
convert_file(pt_filename, sf_filename)
|
| 86 |
local_filenames.append(sf_filename)
|
| 87 |
|
| 88 |
index = os.path.join(folder, "model.safetensors.index.json")
|
|
@@ -101,12 +157,12 @@ def convert_multi(model_id: str, folder: str, token: Optional[str]) -> Conversio
|
|
| 101 |
return operations, errors
|
| 102 |
|
| 103 |
|
| 104 |
-
def convert_single(model_id: str, folder: str, token: Optional[str]) -> ConversionResult:
|
| 105 |
pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin", token=token, cache_dir=folder)
|
| 106 |
|
| 107 |
sf_name = "model.safetensors"
|
| 108 |
sf_filename = os.path.join(folder, sf_name)
|
| 109 |
-
convert_file(pt_filename, sf_filename)
|
| 110 |
operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
|
| 111 |
errors: List[Tuple[str, "Exception"]] = []
|
| 112 |
return operations, errors
|
|
@@ -115,21 +171,25 @@ def convert_single(model_id: str, folder: str, token: Optional[str]) -> Conversi
|
|
| 115 |
def convert_file(
|
| 116 |
pt_filename: str,
|
| 117 |
sf_filename: str,
|
|
|
|
| 118 |
):
|
| 119 |
loaded = torch.load(pt_filename, map_location="cpu")
|
| 120 |
if "state_dict" in loaded:
|
| 121 |
loaded = loaded["state_dict"]
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
| 128 |
loaded = {k: v.contiguous() for k, v in loaded.items()}
|
| 129 |
|
| 130 |
dirname = os.path.dirname(sf_filename)
|
| 131 |
os.makedirs(dirname, exist_ok=True)
|
| 132 |
-
save_file(loaded, sf_filename, metadata=
|
| 133 |
check_file_size(sf_filename, pt_filename)
|
| 134 |
reloaded = load_file(sf_filename)
|
| 135 |
for k in loaded:
|
|
@@ -155,87 +215,14 @@ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]])
|
|
| 155 |
return "\n".join(errors)
|
| 156 |
|
| 157 |
|
| 158 |
-
def
|
| 159 |
-
config = hf_hub_download(repo_id=model_id, filename="config.json", token=token, cache_dir=folder)
|
| 160 |
-
shutil.copy(config, os.path.join(folder, "config.json"))
|
| 161 |
-
config = AutoConfig.from_pretrained(folder)
|
| 162 |
-
|
| 163 |
-
import transformers
|
| 164 |
-
|
| 165 |
-
class_ = getattr(transformers, config.architectures[0])
|
| 166 |
-
with torch.device("meta"):
|
| 167 |
-
(pt_model, pt_infos) = class_.from_pretrained(folder, output_loading_info=True)
|
| 168 |
-
(sf_model, sf_infos) = class_.from_pretrained(folder, output_loading_info=True)
|
| 169 |
-
|
| 170 |
-
if pt_infos != sf_infos:
|
| 171 |
-
error_string = create_diff(pt_infos, sf_infos)
|
| 172 |
-
raise ValueError(f"Different infos when reloading the model: {error_string}")
|
| 173 |
-
|
| 174 |
-
#### XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
|
| 175 |
-
#### SKIPPING THE REST OF THE test to save RAM
|
| 176 |
-
return
|
| 177 |
-
pt_params = pt_model.state_dict()
|
| 178 |
-
sf_params = sf_model.state_dict()
|
| 179 |
-
|
| 180 |
-
pt_shared = shared_pointers(pt_params)
|
| 181 |
-
sf_shared = shared_pointers(sf_params)
|
| 182 |
-
if pt_shared != sf_shared:
|
| 183 |
-
raise RuntimeError("The reconstructed model is wrong, shared tensors are different {shared_pt} != {shared_tf}")
|
| 184 |
-
|
| 185 |
-
sig = signature(pt_model.forward)
|
| 186 |
-
input_ids = torch.arange(10).unsqueeze(0)
|
| 187 |
-
pixel_values = torch.randn(1, 3, 224, 224)
|
| 188 |
-
input_values = torch.arange(1000).float().unsqueeze(0)
|
| 189 |
-
# Hardcoded for whisper basically
|
| 190 |
-
input_features = torch.zeros((1, 80, 3000))
|
| 191 |
-
kwargs = {}
|
| 192 |
-
if "input_ids" in sig.parameters:
|
| 193 |
-
kwargs["input_ids"] = input_ids
|
| 194 |
-
if "input_features" in sig.parameters:
|
| 195 |
-
kwargs["input_features"] = input_features
|
| 196 |
-
if "decoder_input_ids" in sig.parameters:
|
| 197 |
-
kwargs["decoder_input_ids"] = input_ids
|
| 198 |
-
if "pixel_values" in sig.parameters:
|
| 199 |
-
kwargs["pixel_values"] = pixel_values
|
| 200 |
-
if "input_values" in sig.parameters:
|
| 201 |
-
kwargs["input_values"] = input_values
|
| 202 |
-
if "bbox" in sig.parameters:
|
| 203 |
-
kwargs["bbox"] = torch.zeros((1, 10, 4)).long()
|
| 204 |
-
if "image" in sig.parameters:
|
| 205 |
-
kwargs["image"] = pixel_values
|
| 206 |
-
|
| 207 |
-
if torch.cuda.is_available():
|
| 208 |
-
pt_model = pt_model.cuda()
|
| 209 |
-
sf_model = sf_model.cuda()
|
| 210 |
-
kwargs = {k: v.cuda() for k, v in kwargs.items()}
|
| 211 |
-
|
| 212 |
-
try:
|
| 213 |
-
pt_logits = pt_model(**kwargs)[0]
|
| 214 |
-
except Exception as e:
|
| 215 |
-
try:
|
| 216 |
-
# Musicgen special exception.
|
| 217 |
-
decoder_input_ids = torch.ones((input_ids.shape[0] * pt_model.decoder.num_codebooks, 1), dtype=torch.long)
|
| 218 |
-
if torch.cuda.is_available():
|
| 219 |
-
decoder_input_ids = decoder_input_ids.cuda()
|
| 220 |
-
|
| 221 |
-
kwargs["decoder_input_ids"] = decoder_input_ids
|
| 222 |
-
pt_logits = pt_model(**kwargs)[0]
|
| 223 |
-
except Exception:
|
| 224 |
-
raise e
|
| 225 |
-
sf_logits = sf_model(**kwargs)[0]
|
| 226 |
-
|
| 227 |
-
torch.testing.assert_close(sf_logits, pt_logits)
|
| 228 |
-
print(f"Model {model_id} is ok !")
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
|
| 232 |
try:
|
| 233 |
-
main_commit = api.list_repo_commits(model_id)[0].commit_id
|
| 234 |
-
discussions = api.get_repo_discussions(repo_id=model_id)
|
| 235 |
except Exception:
|
| 236 |
return None
|
| 237 |
for discussion in discussions:
|
| 238 |
-
if discussion.is_pull_request and discussion.title == pr_title:
|
| 239 |
commits = api.list_repo_commits(model_id, revision=discussion.git_reference)
|
| 240 |
|
| 241 |
if main_commit == commits[1].commit_id:
|
|
@@ -243,7 +230,7 @@ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discuss
|
|
| 243 |
return None
|
| 244 |
|
| 245 |
|
| 246 |
-
def convert_generic(model_id: str, folder: str, filenames: Set[str], token: Optional[str]) -> ConversionResult:
|
| 247 |
operations = []
|
| 248 |
errors = []
|
| 249 |
|
|
@@ -251,7 +238,7 @@ def convert_generic(model_id: str, folder: str, filenames: Set[str], token: Opti
|
|
| 251 |
for filename in filenames:
|
| 252 |
prefix, ext = os.path.splitext(filename)
|
| 253 |
if ext in extensions:
|
| 254 |
-
pt_filename = hf_hub_download(model_id, filename=filename, token=token, cache_dir=folder)
|
| 255 |
dirname, raw_filename = os.path.split(filename)
|
| 256 |
if raw_filename == "pytorch_model.bin":
|
| 257 |
# XXX: This is a special case to handle `transformers` and the
|
|
@@ -261,25 +248,25 @@ def convert_generic(model_id: str, folder: str, filenames: Set[str], token: Opti
|
|
| 261 |
sf_in_repo = f"{prefix}.safetensors"
|
| 262 |
sf_filename = os.path.join(folder, sf_in_repo)
|
| 263 |
try:
|
| 264 |
-
convert_file(pt_filename, sf_filename)
|
| 265 |
operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
|
| 266 |
except Exception as e:
|
| 267 |
errors.append((pt_filename, e))
|
| 268 |
return operations, errors
|
| 269 |
|
| 270 |
|
| 271 |
-
def convert(api: "HfApi", model_id: str, force: bool = False) -> Tuple["CommitInfo", List[Tuple[str, "Exception"]]]:
|
| 272 |
pr_title = "Adding `safetensors` variant of this model"
|
| 273 |
-
info = api.model_info(model_id)
|
| 274 |
filenames = set(s.rfilename for s in info.siblings)
|
| 275 |
|
| 276 |
-
with TemporaryDirectory() as d:
|
| 277 |
folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
|
| 278 |
os.makedirs(folder)
|
| 279 |
new_pr = None
|
| 280 |
try:
|
| 281 |
operations = None
|
| 282 |
-
pr = previous_pr(api, model_id, pr_title)
|
| 283 |
|
| 284 |
library_name = getattr(info, "library_name", None)
|
| 285 |
if any(filename.endswith(".safetensors") for filename in filenames) and not force:
|
|
@@ -289,19 +276,21 @@ def convert(api: "HfApi", model_id: str, force: bool = False) -> Tuple["CommitIn
|
|
| 289 |
new_pr = pr
|
| 290 |
raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
|
| 291 |
elif library_name == "transformers":
|
|
|
|
|
|
|
| 292 |
if "pytorch_model.bin" in filenames:
|
| 293 |
-
operations, errors = convert_single(model_id, folder, token=api.token)
|
| 294 |
elif "pytorch_model.bin.index.json" in filenames:
|
| 295 |
-
operations, errors = convert_multi(model_id, folder, token=api.token)
|
| 296 |
else:
|
| 297 |
raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
|
| 298 |
-
check_final_model(model_id, folder, token=api.token)
|
| 299 |
else:
|
| 300 |
-
operations, errors = convert_generic(model_id, folder, filenames, token=api.token)
|
| 301 |
|
| 302 |
if operations:
|
| 303 |
new_pr = api.create_commit(
|
| 304 |
repo_id=model_id,
|
|
|
|
| 305 |
operations=operations,
|
| 306 |
commit_message=pr_title,
|
| 307 |
commit_description=COMMIT_DESCRIPTION,
|
|
@@ -328,6 +317,11 @@ if __name__ == "__main__":
|
|
| 328 |
type=str,
|
| 329 |
help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
|
| 330 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
parser.add_argument(
|
| 332 |
"--force",
|
| 333 |
action="store_true",
|
|
@@ -350,26 +344,17 @@ if __name__ == "__main__":
|
|
| 350 |
" Continue [Y/n] ?"
|
| 351 |
)
|
| 352 |
if txt.lower() in {"", "y"}:
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
string = f"""
|
| 356 |
### Success 🔥
|
| 357 |
Yay! This model was successfully converted and a PR was open using your token, here:
|
| 358 |
[{commit_info.pr_url}]({commit_info.pr_url})
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
)
|
| 365 |
-
print(string)
|
| 366 |
-
except Exception as e:
|
| 367 |
-
print(
|
| 368 |
-
f"""
|
| 369 |
-
### Error 😢😢😢
|
| 370 |
-
|
| 371 |
-
{e}
|
| 372 |
-
"""
|
| 373 |
)
|
|
|
|
| 374 |
else:
|
| 375 |
print(f"Answer was `{txt}` aborting.")
|
|
|
|
| 3 |
import os
|
| 4 |
import shutil
|
| 5 |
from collections import defaultdict
|
|
|
|
| 6 |
from tempfile import TemporaryDirectory
|
| 7 |
from typing import Dict, List, Optional, Set, Tuple
|
| 8 |
|
|
|
|
| 10 |
|
| 11 |
from huggingface_hub import CommitInfo, CommitOperationAdd, Discussion, HfApi, hf_hub_download
|
| 12 |
from huggingface_hub.file_download import repo_folder_name
|
| 13 |
+
from safetensors.torch import save_file, load_file, _find_shared_tensors, _is_complete
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
COMMIT_DESCRIPTION = """
|
|
|
|
| 32 |
|
| 33 |
ConversionResult = Tuple[List["CommitOperationAdd"], List[Tuple[str, "Exception"]]]
|
| 34 |
|
| 35 |
+
def _remove_duplicate_names(
|
| 36 |
+
state_dict: Dict[str, torch.Tensor],
|
| 37 |
+
*,
|
| 38 |
+
preferred_names: List[str] = None,
|
| 39 |
+
discard_names: List[str] = None,
|
| 40 |
+
) -> Dict[str, List[str]]:
|
| 41 |
+
if preferred_names is None:
|
| 42 |
+
preferred_names = []
|
| 43 |
+
preferred_names = set(preferred_names)
|
| 44 |
+
if discard_names is None:
|
| 45 |
+
discard_names = []
|
| 46 |
+
discard_names = set(discard_names)
|
| 47 |
+
|
| 48 |
+
shareds = _find_shared_tensors(state_dict)
|
| 49 |
+
to_remove = defaultdict(list)
|
| 50 |
+
for shared in shareds:
|
| 51 |
+
complete_names = set(
|
| 52 |
+
[name for name in shared if _is_complete(state_dict[name])]
|
| 53 |
+
)
|
| 54 |
+
if not complete_names:
|
| 55 |
+
if len(shared) == 1:
|
| 56 |
+
# Force contiguous
|
| 57 |
+
name = list(shared)[0]
|
| 58 |
+
state_dict[name] = state_dict[name].clone()
|
| 59 |
+
complete_names = {name}
|
| 60 |
+
else:
|
| 61 |
+
raise RuntimeError(
|
| 62 |
+
f"Error while trying to find names to remove to save state dict, but found no suitable name to keep for saving amongst: {shared}. None is covering the entire storage.Refusing to save/load the model since you could be storing much more memory than needed. Please refer to https://huggingface.co/docs/safetensors/torch_shared_tensors for more information. Or open an issue."
|
| 63 |
+
)
|
| 64 |
|
| 65 |
+
keep_name = sorted(list(complete_names))[0]
|
| 66 |
+
|
| 67 |
+
# Mecanism to preferentially select keys to keep
|
| 68 |
+
# coming from the on-disk file to allow
|
| 69 |
+
# loading models saved with a different choice
|
| 70 |
+
# of keep_name
|
| 71 |
+
preferred = complete_names.difference(discard_names)
|
| 72 |
+
if preferred:
|
| 73 |
+
keep_name = sorted(list(preferred))[0]
|
| 74 |
+
|
| 75 |
+
if preferred_names:
|
| 76 |
+
preferred = preferred_names.intersection(complete_names)
|
| 77 |
+
if preferred:
|
| 78 |
+
keep_name = sorted(list(preferred))[0]
|
| 79 |
+
for name in sorted(shared):
|
| 80 |
+
if name != keep_name:
|
| 81 |
+
to_remove[keep_name].append(name)
|
| 82 |
+
return to_remove
|
| 83 |
+
|
| 84 |
+
def get_discard_names(model_id: str, revision: Optional[str], folder: str, token: Optional[str]) -> List[str]:
|
| 85 |
+
try:
|
| 86 |
+
import transformers
|
| 87 |
+
import json
|
| 88 |
+
|
| 89 |
+
config_filename = hf_hub_download(
|
| 90 |
+
model_id, revision=revision, filename="config.json", token=token, cache_dir=folder
|
| 91 |
+
)
|
| 92 |
+
with open(config_filename, "r") as f:
|
| 93 |
+
config = json.load(f)
|
| 94 |
+
architecture = config["architectures"][0]
|
| 95 |
|
| 96 |
+
class_ = getattr(transformers, architecture)
|
| 97 |
|
| 98 |
+
# Name for this varible depends on transformers version.
|
| 99 |
+
discard_names = getattr(class_, "_tied_weights_keys", [])
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
discard_names = []
|
| 103 |
+
return discard_names
|
| 104 |
+
|
| 105 |
+
class AlreadyExists(Exception):
|
| 106 |
+
pass
|
| 107 |
|
| 108 |
|
| 109 |
def check_file_size(sf_filename: str, pt_filename: str):
|
|
|
|
| 126 |
return local
|
| 127 |
|
| 128 |
|
| 129 |
+
def convert_multi(model_id: str, *, revision=Optional[str], folder: str, token: Optional[str], discard_names: List[str]) -> ConversionResult:
|
| 130 |
+
filename = hf_hub_download(repo_id=model_id, revision=revision, filename="pytorch_model.bin.index.json", token=token, cache_dir=folder)
|
| 131 |
with open(filename, "r") as f:
|
| 132 |
data = json.load(f)
|
| 133 |
|
|
|
|
| 138 |
|
| 139 |
sf_filename = rename(pt_filename)
|
| 140 |
sf_filename = os.path.join(folder, sf_filename)
|
| 141 |
+
convert_file(pt_filename, sf_filename, discard_names=discard_names)
|
| 142 |
local_filenames.append(sf_filename)
|
| 143 |
|
| 144 |
index = os.path.join(folder, "model.safetensors.index.json")
|
|
|
|
| 157 |
return operations, errors
|
| 158 |
|
| 159 |
|
| 160 |
+
def convert_single(model_id: str, *, revision: Optional[str], folder: str, token: Optional[str], discard_names: List[str]) -> ConversionResult:
|
| 161 |
pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin", token=token, cache_dir=folder)
|
| 162 |
|
| 163 |
sf_name = "model.safetensors"
|
| 164 |
sf_filename = os.path.join(folder, sf_name)
|
| 165 |
+
convert_file(pt_filename, sf_filename, discard_names)
|
| 166 |
operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
|
| 167 |
errors: List[Tuple[str, "Exception"]] = []
|
| 168 |
return operations, errors
|
|
|
|
| 171 |
def convert_file(
|
| 172 |
pt_filename: str,
|
| 173 |
sf_filename: str,
|
| 174 |
+
discard_names: List[str],
|
| 175 |
):
|
| 176 |
loaded = torch.load(pt_filename, map_location="cpu")
|
| 177 |
if "state_dict" in loaded:
|
| 178 |
loaded = loaded["state_dict"]
|
| 179 |
+
to_removes = _remove_duplicate_names(loaded, discard_names=discard_names)
|
| 180 |
+
|
| 181 |
+
metadata = {"format": "pt"}
|
| 182 |
+
for kept_name, to_remove_group in to_removes.items():
|
| 183 |
+
for to_remove in to_remove_group:
|
| 184 |
+
if to_remove not in metadata:
|
| 185 |
+
metadata[to_remove] = kept_name
|
| 186 |
+
del loaded[to_remove]
|
| 187 |
+
# Force tensors to be contiguous
|
| 188 |
loaded = {k: v.contiguous() for k, v in loaded.items()}
|
| 189 |
|
| 190 |
dirname = os.path.dirname(sf_filename)
|
| 191 |
os.makedirs(dirname, exist_ok=True)
|
| 192 |
+
save_file(loaded, sf_filename, metadata=metadata)
|
| 193 |
check_file_size(sf_filename, pt_filename)
|
| 194 |
reloaded = load_file(sf_filename)
|
| 195 |
for k in loaded:
|
|
|
|
| 215 |
return "\n".join(errors)
|
| 216 |
|
| 217 |
|
| 218 |
+
def previous_pr(api: "HfApi", model_id: str, pr_title: str, revision=Optional[str]) -> Optional["Discussion"]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
try:
|
| 220 |
+
main_commit = api.list_repo_commits(model_id, revision=revision)[0].commit_id
|
| 221 |
+
discussions = api.get_repo_discussions(repo_id=model_id, revision=revision)
|
| 222 |
except Exception:
|
| 223 |
return None
|
| 224 |
for discussion in discussions:
|
| 225 |
+
if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
|
| 226 |
commits = api.list_repo_commits(model_id, revision=discussion.git_reference)
|
| 227 |
|
| 228 |
if main_commit == commits[1].commit_id:
|
|
|
|
| 230 |
return None
|
| 231 |
|
| 232 |
|
| 233 |
+
def convert_generic(model_id: str, *, revision=Optional[str], folder: str, filenames: Set[str], token: Optional[str]) -> ConversionResult:
|
| 234 |
operations = []
|
| 235 |
errors = []
|
| 236 |
|
|
|
|
| 238 |
for filename in filenames:
|
| 239 |
prefix, ext = os.path.splitext(filename)
|
| 240 |
if ext in extensions:
|
| 241 |
+
pt_filename = hf_hub_download(model_id, revision=revision, filename=filename, token=token, cache_dir=folder)
|
| 242 |
dirname, raw_filename = os.path.split(filename)
|
| 243 |
if raw_filename == "pytorch_model.bin":
|
| 244 |
# XXX: This is a special case to handle `transformers` and the
|
|
|
|
| 248 |
sf_in_repo = f"{prefix}.safetensors"
|
| 249 |
sf_filename = os.path.join(folder, sf_in_repo)
|
| 250 |
try:
|
| 251 |
+
convert_file(pt_filename, sf_filename, discard_names=[])
|
| 252 |
operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
|
| 253 |
except Exception as e:
|
| 254 |
errors.append((pt_filename, e))
|
| 255 |
return operations, errors
|
| 256 |
|
| 257 |
|
| 258 |
+
def convert(api: "HfApi", model_id: str, revision: Optional[str] = None, force: bool = False) -> Tuple["CommitInfo", List[Tuple[str, "Exception"]]]:
|
| 259 |
pr_title = "Adding `safetensors` variant of this model"
|
| 260 |
+
info = api.model_info(model_id, revision=revision)
|
| 261 |
filenames = set(s.rfilename for s in info.siblings)
|
| 262 |
|
| 263 |
+
with TemporaryDirectory(prefix=os.getenv("HF_HOME", "") + "/") as d:
|
| 264 |
folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
|
| 265 |
os.makedirs(folder)
|
| 266 |
new_pr = None
|
| 267 |
try:
|
| 268 |
operations = None
|
| 269 |
+
pr = previous_pr(api, model_id, pr_title, revision=revision)
|
| 270 |
|
| 271 |
library_name = getattr(info, "library_name", None)
|
| 272 |
if any(filename.endswith(".safetensors") for filename in filenames) and not force:
|
|
|
|
| 276 |
new_pr = pr
|
| 277 |
raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
|
| 278 |
elif library_name == "transformers":
|
| 279 |
+
|
| 280 |
+
discard_names = get_discard_names(model_id, revision=revision, folder=folder, token=api.token)
|
| 281 |
if "pytorch_model.bin" in filenames:
|
| 282 |
+
operations, errors = convert_single(model_id, revision=revision, folder=folder, token=api.token, discard_names = discard_names)
|
| 283 |
elif "pytorch_model.bin.index.json" in filenames:
|
| 284 |
+
operations, errors = convert_multi(model_id, revision=revision, folder=folder, token=api.token, discard_names = discard_names)
|
| 285 |
else:
|
| 286 |
raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
|
|
|
|
| 287 |
else:
|
| 288 |
+
operations, errors = convert_generic(model_id, revision=revision, folder=folder, filenames=filenames, token=api.token)
|
| 289 |
|
| 290 |
if operations:
|
| 291 |
new_pr = api.create_commit(
|
| 292 |
repo_id=model_id,
|
| 293 |
+
revision=revision,
|
| 294 |
operations=operations,
|
| 295 |
commit_message=pr_title,
|
| 296 |
commit_description=COMMIT_DESCRIPTION,
|
|
|
|
| 317 |
type=str,
|
| 318 |
help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
|
| 319 |
)
|
| 320 |
+
parser.add_argument(
|
| 321 |
+
"--revision",
|
| 322 |
+
type=str,
|
| 323 |
+
help="The revision to convert",
|
| 324 |
+
)
|
| 325 |
parser.add_argument(
|
| 326 |
"--force",
|
| 327 |
action="store_true",
|
|
|
|
| 344 |
" Continue [Y/n] ?"
|
| 345 |
)
|
| 346 |
if txt.lower() in {"", "y"}:
|
| 347 |
+
commit_info, errors = convert(api, model_id, revision=args.revision, force=args.force)
|
| 348 |
+
string = f"""
|
|
|
|
| 349 |
### Success 🔥
|
| 350 |
Yay! This model was successfully converted and a PR was open using your token, here:
|
| 351 |
[{commit_info.pr_url}]({commit_info.pr_url})
|
| 352 |
+
"""
|
| 353 |
+
if errors:
|
| 354 |
+
string += "\nErrors during conversion:\n"
|
| 355 |
+
string += "\n".join(
|
| 356 |
+
f"Error while converting {filename}: {e}, skipped conversion" for filename, e in errors
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 357 |
)
|
| 358 |
+
print(string)
|
| 359 |
else:
|
| 360 |
print(f"Answer was `{txt}` aborting.")
|