hdeldar commited on
Commit
8ab6a1f
1 Parent(s): 8c78166

add convertor files

Browse files
Files changed (6) hide show
  1. .gitattributes +0 -2
  2. .gitignore +1 -0
  3. README.md +10 -5
  4. app.py +91 -4
  5. convert.py +231 -0
  6. requirements.txt +6 -0
.gitattributes CHANGED
@@ -2,7 +2,6 @@
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
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
  *.ftz filter=lfs diff=lfs merge=lfs -text
7
  *.gz filter=lfs diff=lfs merge=lfs -text
8
  *.h5 filter=lfs diff=lfs merge=lfs -text
@@ -25,7 +24,6 @@
25
  *.safetensors filter=lfs diff=lfs merge=lfs -text
26
  saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
  *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
  *.tflite filter=lfs diff=lfs merge=lfs -text
30
  *.tgz filter=lfs diff=lfs merge=lfs -text
31
  *.wasm 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
 
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
.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ .env/
README.md CHANGED
@@ -1,12 +1,17 @@
1
  ---
2
- title: Convert
3
- emoji: 🐢
4
- colorFrom: purple
5
- colorTo: green
6
  sdk: gradio
7
- sdk_version: 3.44.4
8
  app_file: app.py
9
  pinned: false
 
 
 
 
 
10
  ---
11
 
12
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Convert to Safetensors
3
+ emoji: 🐶
4
+ colorFrom: yellow
5
+ colorTo: red
6
  sdk: gradio
7
+ sdk_version: 3.8.1
8
  app_file: app.py
9
  pinned: false
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 CHANGED
@@ -1,7 +1,94 @@
 
 
 
 
1
  import gradio as gr
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if HF_TOKEN:
19
+ repo = Repository(local_dir="data", clone_from=DATASET_REPO_URL, token=HF_TOKEN)
20
+
21
+
22
+ def run(token: str, model_id: str) -> str:
23
+ if token == "" or model_id == "":
24
+ return """
25
+ ### Invalid input 🐞
26
+
27
+ Please fill a token and model_id.
28
+ """
29
+ try:
30
+ api = HfApi(token=token)
31
+ is_private = api.model_info(repo_id=model_id).private
32
+ print("is_private", is_private)
33
+
34
+ commit_info = convert(api=api, model_id=model_id, force=True)
35
+ print("[commit_info]", commit_info)
36
+
37
+ # save in a (public) dataset:
38
+ if repo is not None and not is_private:
39
+ repo.git_pull(rebase=True)
40
+ print("pulled")
41
+ with open(DATA_FILE, "a") as csvfile:
42
+ writer = csv.DictWriter(
43
+ csvfile, fieldnames=["model_id", "pr_url", "time"]
44
+ )
45
+ writer.writerow(
46
+ {
47
+ "model_id": model_id,
48
+ "pr_url": commit_info.pr_url,
49
+ "time": str(datetime.now()),
50
+ }
51
+ )
52
+ commit_url = repo.push_to_hub()
53
+ print("[dataset]", commit_url)
54
+
55
+ return f"""
56
+ ### Success 🔥
57
+
58
+ Yay! This model was successfully converted and a PR was open using your token, here:
59
+
60
+ [{commit_info.pr_url}]({commit_info.pr_url})
61
+ """
62
+ except Exception as e:
63
+ return f"""
64
+ ### Error 😢😢😢
65
+
66
+ {e}
67
+ """
68
+
69
+
70
+ DESCRIPTION = """
71
+ The steps are the following:
72
+
73
+ - 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.
74
+ - Input a model id from the Hub
75
+ - Click "Submit"
76
+ - 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 🔥
77
+
78
+ ⚠️ For now only `pytorch_model.bin` files are supported but we'll extend in the future.
79
+ """
80
+
81
+ demo = gr.Interface(
82
+ title="Convert any model to Safetensors and open a PR",
83
+ description=DESCRIPTION,
84
+ allow_flagging="never",
85
+ article="Check out the [Safetensors repo on GitHub](https://github.com/huggingface/safetensors)",
86
+ inputs=[
87
+ gr.Text(max_lines=1, label="your_hf_token"),
88
+ gr.Text(max_lines=1, label="model_id"),
89
+ ],
90
+ outputs=[gr.Markdown(label="output")],
91
+ fn=run,
92
+ )
93
+
94
+ demo.launch()
convert.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ class AlreadyExists(Exception):
20
+ pass
21
+
22
+
23
+ def shared_pointers(tensors):
24
+ ptrs = defaultdict(list)
25
+ for k, v in tensors.items():
26
+ ptrs[v.data_ptr()].append(k)
27
+ failing = []
28
+ for ptr, names in ptrs.items():
29
+ if len(names) > 1:
30
+ failing.append(names)
31
+ return failing
32
+
33
+
34
+ def check_file_size(sf_filename: str, pt_filename: str):
35
+ sf_size = os.stat(sf_filename).st_size
36
+ pt_size = os.stat(pt_filename).st_size
37
+
38
+ if (sf_size - pt_size) / pt_size > 0.01:
39
+ raise RuntimeError(
40
+ f"""The file size different is more than 1%:
41
+ - {sf_filename}: {sf_size}
42
+ - {pt_filename}: {pt_size}
43
+ """
44
+ )
45
+
46
+
47
+ def rename(pt_filename: str) -> str:
48
+ filename, ext = os.path.splitext(pt_filename)
49
+ local = f"{filename}.safetensors"
50
+ local = local.replace("pytorch_model", "model")
51
+ return local
52
+
53
+
54
+ def convert_multi(model_id: str, folder: str) -> List["CommitOperationAdd"]:
55
+ filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
56
+ with open(filename, "r") as f:
57
+ data = json.load(f)
58
+
59
+ filenames = set(data["weight_map"].values())
60
+ local_filenames = []
61
+ for filename in filenames:
62
+ pt_filename = hf_hub_download(repo_id=model_id, filename=filename)
63
+
64
+ sf_filename = rename(pt_filename)
65
+ sf_filename = os.path.join(folder, sf_filename)
66
+ convert_file(pt_filename, sf_filename)
67
+ local_filenames.append(sf_filename)
68
+
69
+ index = os.path.join(folder, "model.safetensors.index.json")
70
+ with open(index, "w") as f:
71
+ newdata = {k: v for k, v in data.items()}
72
+ newmap = {k: rename(v) for k, v in data["weight_map"].items()}
73
+ newdata["weight_map"] = newmap
74
+ json.dump(newdata, f, indent=4)
75
+ local_filenames.append(index)
76
+
77
+ operations = [
78
+ CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
79
+ ]
80
+
81
+ return operations
82
+
83
+
84
+ def convert_single(model_id: str, folder: str) -> List["CommitOperationAdd"]:
85
+ pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
86
+
87
+ sf_name = "model.safetensors"
88
+ sf_filename = os.path.join(folder, sf_name)
89
+ convert_file(pt_filename, sf_filename)
90
+ operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
91
+ return operations
92
+
93
+
94
+ def convert_file(
95
+ pt_filename: str,
96
+ sf_filename: str,
97
+ ):
98
+ loaded = torch.load(pt_filename, map_location="cpu")
99
+ if "state_dict" in loaded:
100
+ loaded = loaded["state_dict"]
101
+ shared = shared_pointers(loaded)
102
+ for shared_weights in shared:
103
+ for name in shared_weights[1:]:
104
+ loaded.pop(name)
105
+
106
+ # For tensors to be contiguous
107
+ loaded = {k: v.contiguous() for k, v in loaded.items()}
108
+
109
+ dirname = os.path.dirname(sf_filename)
110
+ os.makedirs(dirname, exist_ok=True)
111
+ save_file(loaded, sf_filename, metadata={"format": "pt"})
112
+ check_file_size(sf_filename, pt_filename)
113
+ reloaded = load_file(sf_filename)
114
+ for k in loaded:
115
+ pt_tensor = loaded[k]
116
+ sf_tensor = reloaded[k]
117
+ if not torch.equal(pt_tensor, sf_tensor):
118
+ raise RuntimeError(f"The output tensors do not match for key {k}")
119
+
120
+
121
+ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
122
+ errors = []
123
+ for key in ["missing_keys", "mismatched_keys", "unexpected_keys"]:
124
+ pt_set = set(pt_infos[key])
125
+ sf_set = set(sf_infos[key])
126
+
127
+ pt_only = pt_set - sf_set
128
+ sf_only = sf_set - pt_set
129
+
130
+ if pt_only:
131
+ errors.append(f"{key} : PT warnings contain {pt_only} which are not present in SF warnings")
132
+ if sf_only:
133
+ errors.append(f"{key} : SF warnings contain {sf_only} which are not present in PT warnings")
134
+ return "\n".join(errors)
135
+
136
+ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
137
+ try:
138
+ discussions = api.get_repo_discussions(repo_id=model_id)
139
+ except Exception:
140
+ return None
141
+ for discussion in discussions:
142
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
143
+ return discussion
144
+
145
+
146
+ def convert_generic(model_id: str, folder: str, filenames: Set[str]) -> List["CommitOperationAdd"]:
147
+ operations = []
148
+
149
+ extensions = set([".bin", ".ckpt"])
150
+ for filename in filenames:
151
+ prefix, ext = os.path.splitext(filename)
152
+ if ext in extensions:
153
+ pt_filename = hf_hub_download(model_id, filename=filename)
154
+ dirname, raw_filename = os.path.split(filename)
155
+ if raw_filename == "pytorch_model.bin":
156
+ # XXX: This is a special case to handle `transformers` and the
157
+ # `transformers` part of the model which is actually loaded by `transformers`.
158
+ sf_in_repo = os.path.join(dirname, "model.safetensors")
159
+ else:
160
+ sf_in_repo = f"{prefix}.safetensors"
161
+ sf_filename = os.path.join(folder, sf_in_repo)
162
+ convert_file(pt_filename, sf_filename)
163
+ operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
164
+ return operations
165
+
166
+
167
+ def convert(api: "HfApi", model_id: str, force: bool = False) -> Optional["CommitInfo"]:
168
+ pr_title = "Adding `safetensors` variant of this model"
169
+ info = api.model_info(model_id)
170
+
171
+ def is_valid_filename(filename):
172
+ return len(filename.split("/")) > 1 or filename in ["pytorch_model.bin", "diffusion_pytorch_model.bin"]
173
+ filenames = set(s.rfilename for s in info.siblings if is_valid_filename(s.rfilename))
174
+
175
+ print(filenames)
176
+ with TemporaryDirectory() as d:
177
+ folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
178
+ os.makedirs(folder)
179
+ new_pr = None
180
+ try:
181
+ operations = None
182
+ pr = previous_pr(api, model_id, pr_title)
183
+
184
+ library_name = getattr(info, "library_name", None)
185
+ if any(filename.endswith(".safetensors") for filename in filenames) and not force:
186
+ raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
187
+ elif pr is not None and not force:
188
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
189
+ new_pr = pr
190
+ raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
191
+ else:
192
+ print("Convert generic")
193
+ operations = convert_generic(model_id, folder, filenames)
194
+
195
+ if operations:
196
+ new_pr = api.create_commit(
197
+ repo_id=model_id,
198
+ operations=operations,
199
+ commit_message=pr_title,
200
+ create_pr=True,
201
+ )
202
+ print(f"Pr created at {new_pr.pr_url}")
203
+ else:
204
+ print("No files to convert")
205
+ finally:
206
+ shutil.rmtree(folder)
207
+ return new_pr
208
+
209
+
210
+ if __name__ == "__main__":
211
+ DESCRIPTION = """
212
+ Simple utility tool to convert automatically some weights on the hub to `safetensors` format.
213
+ It is PyTorch exclusive for now.
214
+ It works by downloading the weights (PT), converting them locally, and uploading them back
215
+ as a PR on the hub.
216
+ """
217
+ parser = argparse.ArgumentParser(description=DESCRIPTION)
218
+ parser.add_argument(
219
+ "model_id",
220
+ type=str,
221
+ help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
222
+ )
223
+ parser.add_argument(
224
+ "--force",
225
+ action="store_true",
226
+ help="Create the PR even if it already exists of if the model was already converted.",
227
+ )
228
+ args = parser.parse_args()
229
+ model_id = args.model_id
230
+ api = HfApi()
231
+ convert(api, model_id, force=args.force)
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ huggingface_hub
2
+ setuptools_rust
3
+ safetensors
4
+ torch==1.13.1
5
+ transformers
6
+ pytorch_lightning