Narsil HF staff julien-c HF staff commited on
Commit
dd5ad09
0 Parent(s):

Duplicate from safetensors/convert

Browse files

Co-authored-by: Julien Chaumond <julien-c@users.noreply.huggingface.co>

Files changed (7) hide show
  1. .gitattributes +33 -0
  2. .gitignore +1 -0
  3. .vscode/settings.json +4 -0
  4. README.md +17 -0
  5. app.py +100 -0
  6. convert.py +333 -0
  7. requirements.txt +6 -0
.gitattributes ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
11
+ *.model filter=lfs diff=lfs merge=lfs -text
12
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
13
+ *.npy filter=lfs diff=lfs merge=lfs -text
14
+ *.npz filter=lfs diff=lfs merge=lfs -text
15
+ *.onnx filter=lfs diff=lfs merge=lfs -text
16
+ *.ot filter=lfs diff=lfs merge=lfs -text
17
+ *.parquet filter=lfs diff=lfs merge=lfs -text
18
+ *.pb filter=lfs diff=lfs merge=lfs -text
19
+ *.pickle filter=lfs diff=lfs merge=lfs -text
20
+ *.pkl filter=lfs diff=lfs merge=lfs -text
21
+ *.pt filter=lfs diff=lfs merge=lfs -text
22
+ *.pth filter=lfs diff=lfs merge=lfs -text
23
+ *.rar filter=lfs diff=lfs merge=lfs -text
24
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
25
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
26
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
27
+ *.tflite filter=lfs diff=lfs merge=lfs -text
28
+ *.tgz filter=lfs diff=lfs merge=lfs -text
29
+ *.wasm filter=lfs diff=lfs merge=lfs -text
30
+ *.xz filter=lfs diff=lfs merge=lfs -text
31
+ *.zip filter=lfs diff=lfs merge=lfs -text
32
+ *.zst filter=lfs diff=lfs merge=lfs -text
33
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .env/
.vscode/settings.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {
2
+ "editor.formatOnSave": true,
3
+ "python.formatting.provider": "black"
4
+ }
README.md ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Convert to Safetensors
3
+ emoji: 🐶
4
+ colorFrom: yellow
5
+ colorTo: red
6
+ sdk: gradio
7
+ sdk_version: 3.33.1
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ models: []
12
+ datasets:
13
+ - safetensors/conversions
14
+ duplicated_from: safetensors/convert
15
+ ---
16
+
17
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import csv
2
+ from datetime import datetime
3
+ import os
4
+ from typing import Optional
5
+ import gradio as gr
6
+
7
+ from convert import convert
8
+ from huggingface_hub import HfApi, Repository
9
+
10
+
11
+ DATASET_REPO_URL = "https://huggingface.co/datasets/safetensors/conversions"
12
+ DATA_FILENAME = "data.csv"
13
+ DATA_FILE = os.path.join("data", DATA_FILENAME)
14
+
15
+ HF_TOKEN = os.environ.get("HF_TOKEN")
16
+
17
+ repo: Optional[Repository] = None
18
+ # TODO
19
+ if False and HF_TOKEN:
20
+ repo = Repository(local_dir="data", clone_from=DATASET_REPO_URL, token=HF_TOKEN)
21
+
22
+
23
+ def run(token: str, model_id: str) -> str:
24
+ if token == "" or model_id == "":
25
+ return """
26
+ ### Invalid input 🐞
27
+
28
+ Please fill a token and model_id.
29
+ """
30
+ try:
31
+ api = HfApi(token=token)
32
+ is_private = api.model_info(repo_id=model_id).private
33
+ print("is_private", is_private)
34
+
35
+ commit_info, errors = convert(api=api, model_id=model_id)
36
+ print("[commit_info]", commit_info)
37
+
38
+ # save in a (public) dataset:
39
+ # TODO False because of LFS bug.
40
+ if False and repo is not None and not is_private:
41
+ repo.git_pull(rebase=True)
42
+ print("pulled")
43
+ with open(DATA_FILE, "a") as csvfile:
44
+ writer = csv.DictWriter(
45
+ csvfile, fieldnames=["model_id", "pr_url", "time"]
46
+ )
47
+ writer.writerow(
48
+ {
49
+ "model_id": model_id,
50
+ "pr_url": commit_info.pr_url,
51
+ "time": str(datetime.now()),
52
+ }
53
+ )
54
+ commit_url = repo.push_to_hub()
55
+ print("[dataset]", commit_url)
56
+
57
+ string = f"""
58
+ ### Success 🔥
59
+
60
+ Yay! This model was successfully converted and a PR was open using your token, here:
61
+
62
+ [{commit_info.pr_url}]({commit_info.pr_url})
63
+ """
64
+ if errors:
65
+ string += "\nErrors during conversion:\n"
66
+ string += "\n".join(f"Error while converting {filename}: {e}, skipped conversion" for filename, e in errors)
67
+ return string
68
+ except Exception as e:
69
+ return f"""
70
+ ### Error 😢😢😢
71
+
72
+ {e}
73
+ """
74
+
75
+
76
+ DESCRIPTION = """
77
+ The steps are the following:
78
+
79
+ - Paste a read-access token from hf.co/settings/tokens. Read access is enough given that we will open a PR against the source repo.
80
+ - Input a model id from the Hub
81
+ - Click "Submit"
82
+ - That's it! You'll get feedback if it works or not, and if it worked, you'll get the URL of the opened PR 🔥
83
+
84
+ ⚠️ For now only `pytorch_model.bin` files are supported but we'll extend in the future.
85
+ """
86
+
87
+ demo = gr.Interface(
88
+ title="Convert any model to Safetensors and open a PR",
89
+ description=DESCRIPTION,
90
+ allow_flagging="never",
91
+ article="Check out the [Safetensors repo on GitHub](https://github.com/huggingface/safetensors)",
92
+ inputs=[
93
+ gr.Text(max_lines=1, label="your_hf_token"),
94
+ gr.Text(max_lines=1, label="model_id"),
95
+ ],
96
+ outputs=[gr.Markdown(label="output")],
97
+ fn=run,
98
+ ).queue(max_size=10, concurrency_count=1)
99
+
100
+ demo.launch(show_api=True)
convert.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ 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
+
10
+ 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, save_file
15
+ from transformers import AutoConfig
16
+ from transformers.pipelines.base import infer_framework_load_model
17
+
18
+
19
+ COMMIT_DESCRIPTION = """
20
+ This is an automated PR created with https://huggingface.co/spaces/safetensors/convert
21
+
22
+ This new file is equivalent to `pytorch_model.bin` but safe in the sense that
23
+ no arbitrary code can be put into it.
24
+
25
+ These files also happen to load much faster than their pytorch counterpart:
26
+ https://colab.research.google.com/github/huggingface/notebooks/blob/main/safetensors_doc/en/speed.ipynb
27
+
28
+ The widgets on your model page will run using this model even if this is not merged
29
+ making sure the file actually works.
30
+
31
+ If you find any issues: please report here: https://huggingface.co/spaces/safetensors/convert/discussions
32
+
33
+ Feel free to ignore this PR.
34
+ """
35
+
36
+ ConversionResult = Tuple[List["CommitOperationAdd"], List[Tuple[str, "Exception"]]]
37
+
38
+
39
+ class AlreadyExists(Exception):
40
+ pass
41
+
42
+
43
+ def shared_pointers(tensors):
44
+ ptrs = defaultdict(list)
45
+ for k, v in tensors.items():
46
+ ptrs[v.data_ptr()].append(k)
47
+ failing = []
48
+ for ptr, names in ptrs.items():
49
+ if len(names) > 1:
50
+ failing.append(names)
51
+ return failing
52
+
53
+
54
+ def check_file_size(sf_filename: str, pt_filename: str):
55
+ sf_size = os.stat(sf_filename).st_size
56
+ pt_size = os.stat(pt_filename).st_size
57
+
58
+ if (sf_size - pt_size) / pt_size > 0.01:
59
+ raise RuntimeError(
60
+ f"""The file size different is more than 1%:
61
+ - {sf_filename}: {sf_size}
62
+ - {pt_filename}: {pt_size}
63
+ """
64
+ )
65
+
66
+
67
+ def rename(pt_filename: str) -> str:
68
+ filename, ext = os.path.splitext(pt_filename)
69
+ local = f"{filename}.safetensors"
70
+ local = local.replace("pytorch_model", "model")
71
+ return local
72
+
73
+
74
+ def convert_multi(model_id: str, folder: str) -> ConversionResult:
75
+ filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
76
+ with open(filename, "r") as f:
77
+ data = json.load(f)
78
+
79
+ filenames = set(data["weight_map"].values())
80
+ local_filenames = []
81
+ for filename in filenames:
82
+ pt_filename = hf_hub_download(repo_id=model_id, filename=filename)
83
+
84
+ sf_filename = rename(pt_filename)
85
+ sf_filename = os.path.join(folder, sf_filename)
86
+ convert_file(pt_filename, sf_filename)
87
+ local_filenames.append(sf_filename)
88
+
89
+ index = os.path.join(folder, "model.safetensors.index.json")
90
+ with open(index, "w") as f:
91
+ newdata = {k: v for k, v in data.items()}
92
+ newmap = {k: rename(v) for k, v in data["weight_map"].items()}
93
+ newdata["weight_map"] = newmap
94
+ json.dump(newdata, f, indent=4)
95
+ local_filenames.append(index)
96
+
97
+ operations = [
98
+ CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
99
+ ]
100
+ errors: List[Tuple[str, "Exception"]] = []
101
+
102
+ return operations, errors
103
+
104
+
105
+ def convert_single(model_id: str, folder: str) -> ConversionResult:
106
+ pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
107
+
108
+ sf_name = "model.safetensors"
109
+ sf_filename = os.path.join(folder, sf_name)
110
+ convert_file(pt_filename, sf_filename)
111
+ operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
112
+ errors: List[Tuple[str, "Exception"]] = []
113
+ return operations, errors
114
+
115
+
116
+ def convert_file(
117
+ pt_filename: str,
118
+ sf_filename: str,
119
+ ):
120
+ loaded = torch.load(pt_filename, map_location="cpu")
121
+ if "state_dict" in loaded:
122
+ loaded = loaded["state_dict"]
123
+ shared = shared_pointers(loaded)
124
+ for shared_weights in shared:
125
+ for name in shared_weights[1:]:
126
+ loaded.pop(name)
127
+
128
+ # For tensors to be contiguous
129
+ loaded = {k: v.contiguous() for k, v in loaded.items()}
130
+
131
+ dirname = os.path.dirname(sf_filename)
132
+ os.makedirs(dirname, exist_ok=True)
133
+ save_file(loaded, sf_filename, metadata={"format": "pt"})
134
+ check_file_size(sf_filename, pt_filename)
135
+ reloaded = load_file(sf_filename)
136
+ for k in loaded:
137
+ pt_tensor = loaded[k]
138
+ sf_tensor = reloaded[k]
139
+ if not torch.equal(pt_tensor, sf_tensor):
140
+ raise RuntimeError(f"The output tensors do not match for key {k}")
141
+
142
+
143
+ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
144
+ errors = []
145
+ for key in ["missing_keys", "mismatched_keys", "unexpected_keys"]:
146
+ pt_set = set(pt_infos[key])
147
+ sf_set = set(sf_infos[key])
148
+
149
+ pt_only = pt_set - sf_set
150
+ sf_only = sf_set - pt_set
151
+
152
+ if pt_only:
153
+ errors.append(f"{key} : PT warnings contain {pt_only} which are not present in SF warnings")
154
+ if sf_only:
155
+ errors.append(f"{key} : SF warnings contain {sf_only} which are not present in PT warnings")
156
+ return "\n".join(errors)
157
+
158
+
159
+ def check_final_model(model_id: str, folder: str):
160
+ config = hf_hub_download(repo_id=model_id, filename="config.json")
161
+ shutil.copy(config, os.path.join(folder, "config.json"))
162
+ config = AutoConfig.from_pretrained(folder)
163
+
164
+ _, (pt_model, pt_infos) = infer_framework_load_model(model_id, config, output_loading_info=True)
165
+ _, (sf_model, sf_infos) = infer_framework_load_model(folder, config, output_loading_info=True)
166
+
167
+ if pt_infos != sf_infos:
168
+ error_string = create_diff(pt_infos, sf_infos)
169
+ raise ValueError(f"Different infos when reloading the model: {error_string}")
170
+
171
+ pt_params = pt_model.state_dict()
172
+ sf_params = sf_model.state_dict()
173
+
174
+ pt_shared = shared_pointers(pt_params)
175
+ sf_shared = shared_pointers(sf_params)
176
+ if pt_shared != sf_shared:
177
+ raise RuntimeError("The reconstructed model is wrong, shared tensors are different {shared_pt} != {shared_tf}")
178
+
179
+ sig = signature(pt_model.forward)
180
+ input_ids = torch.arange(10).unsqueeze(0)
181
+ pixel_values = torch.randn(1, 3, 224, 224)
182
+ input_values = torch.arange(1000).float().unsqueeze(0)
183
+ kwargs = {}
184
+ if "input_ids" in sig.parameters:
185
+ kwargs["input_ids"] = input_ids
186
+ if "decoder_input_ids" in sig.parameters:
187
+ kwargs["decoder_input_ids"] = input_ids
188
+ if "pixel_values" in sig.parameters:
189
+ kwargs["pixel_values"] = pixel_values
190
+ if "input_values" in sig.parameters:
191
+ kwargs["input_values"] = input_values
192
+ if "bbox" in sig.parameters:
193
+ kwargs["bbox"] = torch.zeros((1, 10, 4)).long()
194
+ if "image" in sig.parameters:
195
+ kwargs["image"] = pixel_values
196
+
197
+ if torch.cuda.is_available():
198
+ pt_model = pt_model.cuda()
199
+ sf_model = sf_model.cuda()
200
+ kwargs = {k: v.cuda() for k, v in kwargs.items()}
201
+
202
+ pt_logits = pt_model(**kwargs)[0]
203
+ sf_logits = sf_model(**kwargs)[0]
204
+
205
+ torch.testing.assert_close(sf_logits, pt_logits)
206
+ print(f"Model {model_id} is ok !")
207
+
208
+
209
+ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
210
+ try:
211
+ main_commit = api.list_repo_commits(model_id)[0].commit_id
212
+ discussions = api.get_repo_discussions(repo_id=model_id)
213
+ except Exception:
214
+ return None
215
+ for discussion in discussions:
216
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
217
+ commits = api.list_repo_commits(model_id, revision=discussion.git_reference)
218
+
219
+ if main_commit == commits[1].commit_id:
220
+ return discussion
221
+ return None
222
+
223
+
224
+ def convert_generic(model_id: str, folder: str, filenames: Set[str]) -> ConversionResult:
225
+ operations = []
226
+ errors = []
227
+
228
+ extensions = set([".bin", ".ckpt"])
229
+ for filename in filenames:
230
+ prefix, ext = os.path.splitext(filename)
231
+ if ext in extensions:
232
+ pt_filename = hf_hub_download(model_id, filename=filename)
233
+ dirname, raw_filename = os.path.split(filename)
234
+ if raw_filename == "pytorch_model.bin":
235
+ # XXX: This is a special case to handle `transformers` and the
236
+ # `transformers` part of the model which is actually loaded by `transformers`.
237
+ sf_in_repo = os.path.join(dirname, "model.safetensors")
238
+ else:
239
+ sf_in_repo = f"{prefix}.safetensors"
240
+ sf_filename = os.path.join(folder, sf_in_repo)
241
+ try:
242
+ convert_file(pt_filename, sf_filename)
243
+ operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
244
+ except Exception as e:
245
+ errors.append((pt_filename, e))
246
+ return operations, errors
247
+
248
+
249
+ def convert(api: "HfApi", model_id: str, force: bool = False) -> Tuple["CommitInfo", List["Exception"]]:
250
+ pr_title = "Adding `safetensors` variant of this model"
251
+ info = api.model_info(model_id)
252
+ filenames = set(s.rfilename for s in info.siblings)
253
+
254
+ with TemporaryDirectory() as d:
255
+ folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
256
+ os.makedirs(folder)
257
+ new_pr = None
258
+ try:
259
+ operations = None
260
+ pr = previous_pr(api, model_id, pr_title)
261
+
262
+ library_name = getattr(info, "library_name", None)
263
+ if any(filename.endswith(".safetensors") for filename in filenames) and not force:
264
+ raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
265
+ elif pr is not None and not force:
266
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
267
+ new_pr = pr
268
+ raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
269
+ elif library_name == "transformers":
270
+ if "pytorch_model.bin" in filenames:
271
+ operations, errors = convert_single(model_id, folder)
272
+ elif "pytorch_model.bin.index.json" in filenames:
273
+ operations, errors = convert_multi(model_id, folder)
274
+ else:
275
+ raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
276
+ check_final_model(model_id, folder)
277
+ else:
278
+ operations, errors = convert_generic(model_id, folder, filenames)
279
+
280
+ if operations:
281
+ new_pr = api.create_commit(
282
+ repo_id=model_id,
283
+ operations=operations,
284
+ commit_message=pr_title,
285
+ commit_description=COMMIT_DESCRIPTION,
286
+ create_pr=True,
287
+ )
288
+ print(f"Pr created at {new_pr.pr_url}")
289
+ else:
290
+ print("No files to convert")
291
+ finally:
292
+ shutil.rmtree(folder)
293
+ return new_pr, errors
294
+
295
+
296
+ if __name__ == "__main__":
297
+ DESCRIPTION = """
298
+ Simple utility tool to convert automatically some weights on the hub to `safetensors` format.
299
+ It is PyTorch exclusive for now.
300
+ It works by downloading the weights (PT), converting them locally, and uploading them back
301
+ as a PR on the hub.
302
+ """
303
+ parser = argparse.ArgumentParser(description=DESCRIPTION)
304
+ parser.add_argument(
305
+ "model_id",
306
+ type=str,
307
+ help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
308
+ )
309
+ parser.add_argument(
310
+ "--force",
311
+ action="store_true",
312
+ help="Create the PR even if it already exists of if the model was already converted.",
313
+ )
314
+ parser.add_argument(
315
+ "-y",
316
+ action="store_true",
317
+ help="Ignore safety prompt",
318
+ )
319
+ args = parser.parse_args()
320
+ model_id = args.model_id
321
+ api = HfApi()
322
+ if args.y:
323
+ txt = "y"
324
+ else:
325
+ txt = input(
326
+ "This conversion script will unpickle a pickled file, which is inherently unsafe. If you do not trust this file, we invite you to use"
327
+ " https://huggingface.co/spaces/safetensors/convert or google colab or other hosted solution to avoid potential issues with this file."
328
+ " Continue [Y/n] ?"
329
+ )
330
+ if txt.lower() in {"", "y"}:
331
+ _commit_info, _errors = convert(api, model_id, force=args.force)
332
+ else:
333
+ print(f"Answer was `{txt}` aborting.")
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ huggingface_hub
2
+ setuptools_rust
3
+ safetensors>=0.3
4
+ torch==1.13.1
5
+ transformers
6
+ pytorch_lightning