Max julien-c HF staff commited on
Commit
0f84b07
0 Parent(s):

Duplicate from safetensors/convert

Browse files

Co-authored-by: Julien Chaumond <[email protected]>

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 +96 -0
  6. convert.py +306 -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.25.0
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,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 = 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
+ return 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
+ except Exception as e:
65
+ return f"""
66
+ ### Error 😢😢😢
67
+
68
+ {e}
69
+ """
70
+
71
+
72
+ DESCRIPTION = """
73
+ The steps are the following:
74
+
75
+ - 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.
76
+ - Input a model id from the Hub
77
+ - Click "Submit"
78
+ - 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 🔥
79
+
80
+ ⚠️ For now only `pytorch_model.bin` files are supported but we'll extend in the future.
81
+ """
82
+
83
+ demo = gr.Interface(
84
+ title="Convert any model to Safetensors and open a PR",
85
+ description=DESCRIPTION,
86
+ allow_flagging="never",
87
+ article="Check out the [Safetensors repo on GitHub](https://github.com/huggingface/safetensors)",
88
+ inputs=[
89
+ gr.Text(max_lines=1, label="your_hf_token"),
90
+ gr.Text(max_lines=1, label="model_id"),
91
+ ],
92
+ outputs=[gr.Markdown(label="output")],
93
+ fn=run,
94
+ ).queue(max_size=10, concurrency_count=1)
95
+
96
+ demo.launch(show_api=True)
convert.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
+
37
+ class AlreadyExists(Exception):
38
+ pass
39
+
40
+
41
+ def shared_pointers(tensors):
42
+ ptrs = defaultdict(list)
43
+ for k, v in tensors.items():
44
+ ptrs[v.data_ptr()].append(k)
45
+ failing = []
46
+ for ptr, names in ptrs.items():
47
+ if len(names) > 1:
48
+ failing.append(names)
49
+ return failing
50
+
51
+
52
+ def check_file_size(sf_filename: str, pt_filename: str):
53
+ sf_size = os.stat(sf_filename).st_size
54
+ pt_size = os.stat(pt_filename).st_size
55
+
56
+ if (sf_size - pt_size) / pt_size > 0.01:
57
+ raise RuntimeError(
58
+ f"""The file size different is more than 1%:
59
+ - {sf_filename}: {sf_size}
60
+ - {pt_filename}: {pt_size}
61
+ """
62
+ )
63
+
64
+
65
+ def rename(pt_filename: str) -> str:
66
+ filename, ext = os.path.splitext(pt_filename)
67
+ local = f"{filename}.safetensors"
68
+ local = local.replace("pytorch_model", "model")
69
+ return local
70
+
71
+
72
+ def convert_multi(model_id: str, folder: str) -> List["CommitOperationAdd"]:
73
+ filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
74
+ with open(filename, "r") as f:
75
+ data = json.load(f)
76
+
77
+ filenames = set(data["weight_map"].values())
78
+ local_filenames = []
79
+ for filename in filenames:
80
+ pt_filename = hf_hub_download(repo_id=model_id, filename=filename)
81
+
82
+ sf_filename = rename(pt_filename)
83
+ sf_filename = os.path.join(folder, sf_filename)
84
+ convert_file(pt_filename, sf_filename)
85
+ local_filenames.append(sf_filename)
86
+
87
+ index = os.path.join(folder, "model.safetensors.index.json")
88
+ with open(index, "w") as f:
89
+ newdata = {k: v for k, v in data.items()}
90
+ newmap = {k: rename(v) for k, v in data["weight_map"].items()}
91
+ newdata["weight_map"] = newmap
92
+ json.dump(newdata, f, indent=4)
93
+ local_filenames.append(index)
94
+
95
+ operations = [
96
+ CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
97
+ ]
98
+
99
+ return operations
100
+
101
+
102
+ def convert_single(model_id: str, folder: str) -> List["CommitOperationAdd"]:
103
+ pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
104
+
105
+ sf_name = "model.safetensors"
106
+ sf_filename = os.path.join(folder, sf_name)
107
+ convert_file(pt_filename, sf_filename)
108
+ operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
109
+ return operations
110
+
111
+
112
+ def convert_file(
113
+ pt_filename: str,
114
+ sf_filename: str,
115
+ ):
116
+ loaded = torch.load(pt_filename, map_location="cpu")
117
+ if "state_dict" in loaded:
118
+ loaded = loaded["state_dict"]
119
+ shared = shared_pointers(loaded)
120
+ for shared_weights in shared:
121
+ for name in shared_weights[1:]:
122
+ loaded.pop(name)
123
+
124
+ # For tensors to be contiguous
125
+ loaded = {k: v.contiguous() for k, v in loaded.items()}
126
+
127
+ dirname = os.path.dirname(sf_filename)
128
+ os.makedirs(dirname, exist_ok=True)
129
+ save_file(loaded, sf_filename, metadata={"format": "pt"})
130
+ check_file_size(sf_filename, pt_filename)
131
+ reloaded = load_file(sf_filename)
132
+ for k in loaded:
133
+ pt_tensor = loaded[k]
134
+ sf_tensor = reloaded[k]
135
+ if not torch.equal(pt_tensor, sf_tensor):
136
+ raise RuntimeError(f"The output tensors do not match for key {k}")
137
+
138
+
139
+ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
140
+ errors = []
141
+ for key in ["missing_keys", "mismatched_keys", "unexpected_keys"]:
142
+ pt_set = set(pt_infos[key])
143
+ sf_set = set(sf_infos[key])
144
+
145
+ pt_only = pt_set - sf_set
146
+ sf_only = sf_set - pt_set
147
+
148
+ if pt_only:
149
+ errors.append(f"{key} : PT warnings contain {pt_only} which are not present in SF warnings")
150
+ if sf_only:
151
+ errors.append(f"{key} : SF warnings contain {sf_only} which are not present in PT warnings")
152
+ return "\n".join(errors)
153
+
154
+
155
+ def check_final_model(model_id: str, folder: str):
156
+ config = hf_hub_download(repo_id=model_id, filename="config.json")
157
+ shutil.copy(config, os.path.join(folder, "config.json"))
158
+ config = AutoConfig.from_pretrained(folder)
159
+
160
+ _, (pt_model, pt_infos) = infer_framework_load_model(model_id, config, output_loading_info=True)
161
+ _, (sf_model, sf_infos) = infer_framework_load_model(folder, config, output_loading_info=True)
162
+
163
+ if pt_infos != sf_infos:
164
+ error_string = create_diff(pt_infos, sf_infos)
165
+ raise ValueError(f"Different infos when reloading the model: {error_string}")
166
+
167
+ pt_params = pt_model.state_dict()
168
+ sf_params = sf_model.state_dict()
169
+
170
+ pt_shared = shared_pointers(pt_params)
171
+ sf_shared = shared_pointers(sf_params)
172
+ if pt_shared != sf_shared:
173
+ raise RuntimeError("The reconstructed model is wrong, shared tensors are different {shared_pt} != {shared_tf}")
174
+
175
+ sig = signature(pt_model.forward)
176
+ input_ids = torch.arange(10).unsqueeze(0)
177
+ pixel_values = torch.randn(1, 3, 224, 224)
178
+ input_values = torch.arange(1000).float().unsqueeze(0)
179
+ kwargs = {}
180
+ if "input_ids" in sig.parameters:
181
+ kwargs["input_ids"] = input_ids
182
+ if "decoder_input_ids" in sig.parameters:
183
+ kwargs["decoder_input_ids"] = input_ids
184
+ if "pixel_values" in sig.parameters:
185
+ kwargs["pixel_values"] = pixel_values
186
+ if "input_values" in sig.parameters:
187
+ kwargs["input_values"] = input_values
188
+ if "bbox" in sig.parameters:
189
+ kwargs["bbox"] = torch.zeros((1, 10, 4)).long()
190
+ if "image" in sig.parameters:
191
+ kwargs["image"] = pixel_values
192
+
193
+ if torch.cuda.is_available():
194
+ pt_model = pt_model.cuda()
195
+ sf_model = sf_model.cuda()
196
+ kwargs = {k: v.cuda() for k, v in kwargs.items()}
197
+
198
+ pt_logits = pt_model(**kwargs)[0]
199
+ sf_logits = sf_model(**kwargs)[0]
200
+
201
+ torch.testing.assert_close(sf_logits, pt_logits)
202
+ print(f"Model {model_id} is ok !")
203
+
204
+
205
+ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
206
+ try:
207
+ discussions = api.get_repo_discussions(repo_id=model_id)
208
+ except Exception:
209
+ return None
210
+ for discussion in discussions:
211
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
212
+ details = api.get_discussion_details(repo_id=model_id, discussion_num=discussion.num)
213
+ if details.target_branch == "refs/heads/main":
214
+ return discussion
215
+
216
+
217
+ def convert_generic(model_id: str, folder: str, filenames: Set[str]) -> List["CommitOperationAdd"]:
218
+ operations = []
219
+
220
+ extensions = set([".bin", ".ckpt"])
221
+ for filename in filenames:
222
+ prefix, ext = os.path.splitext(filename)
223
+ if ext in extensions:
224
+ pt_filename = hf_hub_download(model_id, filename=filename)
225
+ dirname, raw_filename = os.path.split(filename)
226
+ if raw_filename == "pytorch_model.bin":
227
+ # XXX: This is a special case to handle `transformers` and the
228
+ # `transformers` part of the model which is actually loaded by `transformers`.
229
+ sf_in_repo = os.path.join(dirname, "model.safetensors")
230
+ else:
231
+ sf_in_repo = f"{prefix}.safetensors"
232
+ sf_filename = os.path.join(folder, sf_in_repo)
233
+ convert_file(pt_filename, sf_filename)
234
+ operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
235
+ return operations
236
+
237
+
238
+ def convert(api: "HfApi", model_id: str, force: bool = False) -> Optional["CommitInfo"]:
239
+ pr_title = "Adding `safetensors` variant of this model"
240
+ info = api.model_info(model_id)
241
+ filenames = set(s.rfilename for s in info.siblings)
242
+
243
+ with TemporaryDirectory() as d:
244
+ folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
245
+ os.makedirs(folder)
246
+ new_pr = None
247
+ try:
248
+ operations = None
249
+ pr = previous_pr(api, model_id, pr_title)
250
+
251
+ library_name = getattr(info, "library_name", None)
252
+ if any(filename.endswith(".safetensors") for filename in filenames) and not force:
253
+ raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
254
+ elif pr is not None and not force:
255
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
256
+ new_pr = pr
257
+ raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
258
+ elif library_name == "transformers":
259
+ if "pytorch_model.bin" in filenames:
260
+ operations = convert_single(model_id, folder)
261
+ elif "pytorch_model.bin.index.json" in filenames:
262
+ operations = convert_multi(model_id, folder)
263
+ else:
264
+ raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
265
+ check_final_model(model_id, folder)
266
+ else:
267
+ operations = convert_generic(model_id, folder, filenames)
268
+
269
+ if operations:
270
+ new_pr = api.create_commit(
271
+ repo_id=model_id,
272
+ operations=operations,
273
+ commit_message=pr_title,
274
+ commit_description=COMMIT_DESCRIPTION,
275
+ create_pr=True,
276
+ )
277
+ print(f"Pr created at {new_pr.pr_url}")
278
+ else:
279
+ print("No files to convert")
280
+ finally:
281
+ shutil.rmtree(folder)
282
+ return new_pr
283
+
284
+
285
+ if __name__ == "__main__":
286
+ DESCRIPTION = """
287
+ Simple utility tool to convert automatically some weights on the hub to `safetensors` format.
288
+ It is PyTorch exclusive for now.
289
+ It works by downloading the weights (PT), converting them locally, and uploading them back
290
+ as a PR on the hub.
291
+ """
292
+ parser = argparse.ArgumentParser(description=DESCRIPTION)
293
+ parser.add_argument(
294
+ "model_id",
295
+ type=str,
296
+ help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
297
+ )
298
+ parser.add_argument(
299
+ "--force",
300
+ action="store_true",
301
+ help="Create the PR even if it already exists of if the model was already converted.",
302
+ )
303
+ args = parser.parse_args()
304
+ model_id = args.model_id
305
+ api = HfApi()
306
+ convert(api, model_id, force=args.force)
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