Syed-Hasan-8503 commited on
Commit
181f391
Β·
verified Β·
1 Parent(s): 4fc7b97

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +2 -8
  2. app.py +291 -0
  3. requirements.txt +1 -0
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
- title: Model Converter BIN-SafeTensors
3
- emoji: πŸ†
4
- colorFrom: red
5
- colorTo: purple
6
  sdk: gradio
7
  sdk_version: 4.19.1
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: Model_Converter_BIN-SafeTensors
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 4.19.1
 
 
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import csv
19
+ from datetime import datetime
20
+ import os
21
+ from typing import Optional
22
+ from huggingface_hub import HfApi, Repository
23
+
24
+ import gradio as gr
25
+
26
+ class AlreadyExists(Exception):
27
+ pass
28
+
29
+
30
+ def shared_pointers(tensors):
31
+ ptrs = defaultdict(list)
32
+ for k, v in tensors.items():
33
+ ptrs[v.data_ptr()].append(k)
34
+ failing = []
35
+ for ptr, names in ptrs.items():
36
+ if len(names) > 1:
37
+ failing.append(names)
38
+ return failing
39
+
40
+
41
+ def check_file_size(sf_filename: str, pt_filename: str):
42
+ sf_size = os.stat(sf_filename).st_size
43
+ pt_size = os.stat(pt_filename).st_size
44
+
45
+ if (sf_size - pt_size) / pt_size > 0.01:
46
+ raise RuntimeError(
47
+ f"""The file size different is more than 1%:
48
+ - {sf_filename}: {sf_size}
49
+ - {pt_filename}: {pt_size}
50
+ """
51
+ )
52
+
53
+
54
+ def rename(pt_filename: str) -> str:
55
+ filename, ext = os.path.splitext(pt_filename)
56
+ local = f"{filename}.safetensors"
57
+ local = local.replace("pytorch_model", "model")
58
+ return local
59
+
60
+
61
+ def convert_multi(model_id: str, folder: str) -> List["CommitOperationAdd"]:
62
+ filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
63
+ with open(filename, "r") as f:
64
+ data = json.load(f)
65
+
66
+ filenames = set(data["weight_map"].values())
67
+ local_filenames = []
68
+ for filename in filenames:
69
+ pt_filename = hf_hub_download(repo_id=model_id, filename=filename)
70
+
71
+ sf_filename = rename(pt_filename)
72
+ sf_filename = os.path.join(folder, sf_filename)
73
+ convert_file(pt_filename, sf_filename)
74
+ local_filenames.append(sf_filename)
75
+
76
+ index = os.path.join(folder, "model.safetensors.index.json")
77
+ with open(index, "w") as f:
78
+ newdata = {k: v for k, v in data.items()}
79
+ newmap = {k: rename(v) for k, v in data["weight_map"].items()}
80
+ newdata["weight_map"] = newmap
81
+ json.dump(newdata, f, indent=4)
82
+ local_filenames.append(index)
83
+
84
+ operations = [
85
+ CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
86
+ ]
87
+
88
+ return operations
89
+
90
+
91
+ def convert_single(model_id: str, folder: str) -> List["CommitOperationAdd"]:
92
+ pt_filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
93
+
94
+ sf_name = "model.safetensors"
95
+ sf_filename = os.path.join(folder, sf_name)
96
+ convert_file(pt_filename, sf_filename)
97
+ operations = [CommitOperationAdd(path_in_repo=sf_name, path_or_fileobj=sf_filename)]
98
+ return operations
99
+
100
+
101
+ def convert_file(
102
+ pt_filename: str,
103
+ sf_filename: str,
104
+ ):
105
+ loaded = torch.load(pt_filename, map_location="cpu")
106
+ if "state_dict" in loaded:
107
+ loaded = loaded["state_dict"]
108
+ shared = shared_pointers(loaded)
109
+ for shared_weights in shared:
110
+ for name in shared_weights[1:]:
111
+ loaded.pop(name)
112
+
113
+ # For tensors to be contiguous
114
+ loaded = {k: v.contiguous() for k, v in loaded.items()}
115
+
116
+ dirname = os.path.dirname(sf_filename)
117
+ os.makedirs(dirname, exist_ok=True)
118
+ save_file(loaded, sf_filename, metadata={"format": "pt"})
119
+ check_file_size(sf_filename, pt_filename)
120
+ reloaded = load_file(sf_filename)
121
+ for k in loaded:
122
+ pt_tensor = loaded[k]
123
+ sf_tensor = reloaded[k]
124
+ if not torch.equal(pt_tensor, sf_tensor):
125
+ raise RuntimeError(f"The output tensors do not match for key {k}")
126
+
127
+
128
+ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
129
+ errors = []
130
+ for key in ["missing_keys", "mismatched_keys", "unexpected_keys"]:
131
+ pt_set = set(pt_infos[key])
132
+ sf_set = set(sf_infos[key])
133
+
134
+ pt_only = pt_set - sf_set
135
+ sf_only = sf_set - pt_set
136
+
137
+ if pt_only:
138
+ errors.append(f"{key} : PT warnings contain {pt_only} which are not present in SF warnings")
139
+ if sf_only:
140
+ errors.append(f"{key} : SF warnings contain {sf_only} which are not present in PT warnings")
141
+ return "\n".join(errors)
142
+
143
+ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
144
+ try:
145
+ discussions = api.get_repo_discussions(repo_id=model_id)
146
+ except Exception:
147
+ return None
148
+ for discussion in discussions:
149
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
150
+ return discussion
151
+
152
+
153
+ def convert_generic(model_id: str, folder: str, filenames: Set[str]) -> List["CommitOperationAdd"]:
154
+ operations = []
155
+
156
+ extensions = set([".bin", ".ckpt"])
157
+ for filename in filenames:
158
+ prefix, ext = os.path.splitext(filename)
159
+ if ext in extensions:
160
+ pt_filename = hf_hub_download(model_id, filename=filename)
161
+ dirname, raw_filename = os.path.split(filename)
162
+ if raw_filename == "pytorch_model.bin":
163
+ # XXX: This is a special case to handle `transformers` and the
164
+ # `transformers` part of the model which is actually loaded by `transformers`.
165
+ sf_in_repo = os.path.join(dirname, "model.safetensors")
166
+ else:
167
+ sf_in_repo = f"{prefix}.safetensors"
168
+ sf_filename = os.path.join(folder, sf_in_repo)
169
+ convert_file(pt_filename, sf_filename)
170
+ return sf_filename
171
+
172
+
173
+ def convert(api: "HfApi", model_id: str, force: bool = False) -> Optional["CommitInfo"]:
174
+ pr_title = "Adding `safetensors` variant of this model"
175
+ info = api.model_info(model_id)
176
+
177
+ def is_valid_filename(filename):
178
+ return len(filename.split("/")) > 1 or filename in ["pytorch_model.bin", "diffusion_pytorch_model.bin"]
179
+ filenames = set(s.rfilename for s in info.siblings if is_valid_filename(s.rfilename))
180
+
181
+ print(filenames)
182
+
183
+
184
+ folder = os.path.join("./", repo_folder_name(repo_id=model_id, repo_type="models"))
185
+ os.makedirs(folder)
186
+ print(folder)
187
+ new_pr = None
188
+ try:
189
+ operations = None
190
+ pr = previous_pr(api, model_id, pr_title)
191
+
192
+ library_name = getattr(info, "library_name", None)
193
+ if any(filename.endswith(".safetensors") for filename in filenames) and not force:
194
+ raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
195
+ elif pr is not None and not force:
196
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
197
+ new_pr = pr
198
+ raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
199
+ else:
200
+ print("Convert generic")
201
+ operations = convert_generic(model_id, folder, filenames)
202
+
203
+ finally:
204
+ print(folder)
205
+ return folder
206
+
207
+
208
+
209
+
210
+
211
+
212
+ DATASET_REPO_URL = "https://huggingface.co/datasets/safetensors/conversions"
213
+ DATA_FILENAME = "data.csv"
214
+ DATA_FILE = os.path.join("data", DATA_FILENAME)
215
+
216
+ HF_TOKEN = os.environ.get("HF_TOKEN")
217
+
218
+ repo: Optional[Repository] = None
219
+ if HF_TOKEN:
220
+ repo = Repository(local_dir="data", clone_from=DATASET_REPO_URL, token=HF_TOKEN)
221
+
222
+
223
+ def run(token: str, model_id: str) -> str:
224
+ if token == "" or model_id == "":
225
+ return """
226
+ ### Invalid input 🐞
227
+
228
+ Please fill a token and model_id.
229
+ """
230
+ try:
231
+ api = HfApi(token=token)
232
+ is_private = api.model_info(repo_id=model_id).private
233
+ folder = convert(api=api, model_id=model_id, force=True)
234
+
235
+ return folder
236
+
237
+ except Exception as e:
238
+ return f"""
239
+ ### Error 😒😒😒
240
+
241
+ {e}
242
+ """
243
+
244
+ def conversion(hf_token, Model, Username, Repo_name):
245
+ repo_id = Username + "/" + Repo_name
246
+ folder = run(hf_token, Model)
247
+
248
+ api = HfApi()
249
+
250
+ api.create_repo(
251
+ repo_id = repo_id,
252
+ token = hf_token,
253
+ repo_type = "model",
254
+ exist_ok = True
255
+ )
256
+
257
+ api.upload_file(
258
+ path_or_fileobj= folder + "/model.safetensors",
259
+ path_in_repo = "model.safetensors",
260
+ token = hf_token,
261
+ repo_id = repo_id,
262
+ repo_type = "model",
263
+ )
264
+
265
+ shutil.rmtree(folder)
266
+ return "Successfully converted to safeTensors"
267
+
268
+
269
+ inputs = [gr.Textbox(label="hf_token", elem_classes="inputs"),
270
+ gr.Textbox(label="Model_id_to_convert", elem_classes="inputs"),
271
+ gr.Textbox(label="hf_username", elem_classes="inputs"),
272
+ gr.Textbox(label="Repo_name", elem_classes="inputs")]
273
+
274
+
275
+ desc = "This Gradio app **GreetLucky** takes a *name as input* and creates " \
276
+ "a friendly greeting along with a randomly assigned ***lucky number between 1 and 100.***"
277
+
278
+ article = "The Hugging Face Model Converter is a powerful tool designed to streamline the conversion process from PyTorch.bin format to SafeTensors." \
279
+ "This Gradio app offers a user-friendly interface where users can effortlessly input their Hugging Face model details," \
280
+ "including the Hugging Face token, model ID, username, and repository name. With just a click of a button, the conversion process is initiated"
281
+
282
+ demo = gr.Interface(fn=conversion,
283
+ inputs=inputs,
284
+ outputs=[gr.Textbox(label="Status")],
285
+ title="Hugging Face Model Converter: PyTorch.bin to SafeTensors",
286
+ description=desc,
287
+ article=article,
288
+ theme=gr.Theme.from_hub('HaleyCH/HaleyCH_Theme')
289
+ )
290
+
291
+ demo.launch(debug=True)
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ gradio