Panchovix commited on
Commit
926e34f
1 Parent(s): f6a28b6

old convert and lazy-way to convert to safetensors script

Browse files
Files changed (1) hide show
  1. bin2safetensors/convert_old.py +324 -0
bin2safetensors/convert_old.py ADDED
@@ -0,0 +1,324 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+
18
+ COMMIT_DESCRIPTION = """
19
+ This is an automated PR created with https://huggingface.co/spaces/safetensors/convert
20
+
21
+ This new file is equivalent to `pytorch_model.bin` but safe in the sense that
22
+ no arbitrary code can be put into it.
23
+
24
+ These files also happen to load much faster than their pytorch counterpart:
25
+ https://colab.research.google.com/github/huggingface/notebooks/blob/main/safetensors_doc/en/speed.ipynb
26
+
27
+ The widgets on your model page will run using this model even if this is not merged
28
+ making sure the file actually works.
29
+
30
+ If you find any issues: please report here: https://huggingface.co/spaces/safetensors/convert/discussions
31
+
32
+ Feel free to ignore this PR.
33
+ """
34
+
35
+ ConversionResult = Tuple[List["CommitOperationAdd"], List[Tuple[str, "Exception"]]]
36
+
37
+
38
+ class AlreadyExists(Exception):
39
+ pass
40
+
41
+
42
+ def shared_pointers(tensors):
43
+ ptrs = defaultdict(list)
44
+ for k, v in tensors.items():
45
+ ptrs[v.data_ptr()].append(k)
46
+ failing = []
47
+ for ptr, names in ptrs.items():
48
+ if len(names) > 1:
49
+ failing.append(names)
50
+ return failing
51
+
52
+
53
+ def check_file_size(sf_filename: str, pt_filename: str):
54
+ sf_size = os.stat(sf_filename).st_size
55
+ pt_size = os.stat(pt_filename).st_size
56
+
57
+ if (sf_size - pt_size) / pt_size > 0.01:
58
+ raise RuntimeError(
59
+ f"""The file size different is more than 1%:
60
+ - {sf_filename}: {sf_size}
61
+ - {pt_filename}: {pt_size}
62
+ """
63
+ )
64
+
65
+
66
+ def rename(pt_filename: str) -> str:
67
+ filename, ext = os.path.splitext(pt_filename)
68
+ local = f"{filename}.safetensors"
69
+ local = local.replace("pytorch_model", "model")
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
+
78
+ filenames = set(data["weight_map"].values())
79
+ local_filenames = []
80
+ for filename in filenames:
81
+ pt_filename = hf_hub_download(repo_id=model_id, filename=filename, token=token, cache_dir=folder)
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")
89
+ with open(index, "w") as f:
90
+ newdata = {k: v for k, v in data.items()}
91
+ newmap = {k: rename(v) for k, v in data["weight_map"].items()}
92
+ newdata["weight_map"] = newmap
93
+ json.dump(newdata, f, indent=4)
94
+ local_filenames.append(index)
95
+
96
+ operations = [
97
+ CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
98
+ ]
99
+ errors: List[Tuple[str, "Exception"]] = []
100
+
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
113
+
114
+
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
+ shared = shared_pointers(loaded)
123
+ for shared_weights in shared:
124
+ for name in shared_weights[1:]:
125
+ loaded.pop(name)
126
+
127
+ # For tensors to be contiguous
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={"format": "pt"})
133
+ check_file_size(sf_filename, pt_filename)
134
+ reloaded = load_file(sf_filename)
135
+ for k in loaded:
136
+ pt_tensor = loaded[k]
137
+ sf_tensor = reloaded[k]
138
+ if not torch.equal(pt_tensor, sf_tensor):
139
+ raise RuntimeError(f"The output tensors do not match for key {k}")
140
+
141
+
142
+ def create_diff(pt_infos: Dict[str, List[str]], sf_infos: Dict[str, List[str]]) -> str:
143
+ errors = []
144
+ for key in ["missing_keys", "mismatched_keys", "unexpected_keys"]:
145
+ pt_set = set(pt_infos[key])
146
+ sf_set = set(sf_infos[key])
147
+
148
+ pt_only = pt_set - sf_set
149
+ sf_only = sf_set - pt_set
150
+
151
+ if pt_only:
152
+ errors.append(f"{key} : PT warnings contain {pt_only} which are not present in SF warnings")
153
+ if sf_only:
154
+ errors.append(f"{key} : SF warnings contain {sf_only} which are not present in PT warnings")
155
+ return "\n".join(errors)
156
+
157
+
158
+ def check_final_model(model_id: str, folder: str, token: Optional[str]):
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
+ (pt_model, pt_infos) = class_.from_pretrained(folder, output_loading_info=True)
167
+ (sf_model, sf_infos) = class_.from_pretrained(folder, output_loading_info=True)
168
+
169
+ if pt_infos != sf_infos:
170
+ error_string = create_diff(pt_infos, sf_infos)
171
+ raise ValueError(f"Different infos when reloading the model: {error_string}")
172
+
173
+ pt_params = pt_model.state_dict()
174
+ sf_params = sf_model.state_dict()
175
+
176
+ pt_shared = shared_pointers(pt_params)
177
+ sf_shared = shared_pointers(sf_params)
178
+ if pt_shared != sf_shared:
179
+ raise RuntimeError("The reconstructed model is wrong, shared tensors are different {shared_pt} != {shared_tf}")
180
+
181
+ sig = signature(pt_model.forward)
182
+ input_ids = torch.arange(10).unsqueeze(0)
183
+ pixel_values = torch.randn(1, 3, 224, 224)
184
+ input_values = torch.arange(1000).float().unsqueeze(0)
185
+ # Hardcoded for whisper basically
186
+ input_features = torch.zeros((1, 80, 3000))
187
+ kwargs = {}
188
+ if "input_ids" in sig.parameters:
189
+ kwargs["input_ids"] = input_ids
190
+ if "input_features" in sig.parameters:
191
+ kwargs["input_features"] = input_features
192
+ if "decoder_input_ids" in sig.parameters:
193
+ kwargs["decoder_input_ids"] = input_ids
194
+ if "pixel_values" in sig.parameters:
195
+ kwargs["pixel_values"] = pixel_values
196
+ if "input_values" in sig.parameters:
197
+ kwargs["input_values"] = input_values
198
+ if "bbox" in sig.parameters:
199
+ kwargs["bbox"] = torch.zeros((1, 10, 4)).long()
200
+ if "image" in sig.parameters:
201
+ kwargs["image"] = pixel_values
202
+
203
+ if torch.cuda.is_available():
204
+ pt_model = pt_model.cuda()
205
+ sf_model = sf_model.cuda()
206
+ kwargs = {k: v.cuda() for k, v in kwargs.items()}
207
+
208
+ try:
209
+ pt_logits = pt_model(**kwargs)[0]
210
+ except Exception as e:
211
+ try:
212
+ # Musicgen special exception.
213
+ decoder_input_ids = torch.ones((input_ids.shape[0] * pt_model.decoder.num_codebooks, 1), dtype=torch.long)
214
+ if torch.cuda.is_available():
215
+ decoder_input_ids = decoder_input_ids.cuda()
216
+
217
+ kwargs["decoder_input_ids"] = decoder_input_ids
218
+ pt_logits = pt_model(**kwargs)[0]
219
+ except Exception:
220
+ raise e
221
+ sf_logits = sf_model(**kwargs)[0]
222
+
223
+ torch.testing.assert_close(sf_logits, pt_logits)
224
+ print(f"Model {model_id} is ok !")
225
+
226
+
227
+ def previous_pr(api: "HfApi", model_id: str, pr_title: str) -> Optional["Discussion"]:
228
+ try:
229
+ main_commit = api.list_repo_commits(model_id)[0].commit_id
230
+ discussions = api.get_repo_discussions(repo_id=model_id)
231
+ except Exception:
232
+ return None
233
+ for discussion in discussions:
234
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
235
+ commits = api.list_repo_commits(model_id, revision=discussion.git_reference)
236
+
237
+ if main_commit == commits[1].commit_id:
238
+ return discussion
239
+ return None
240
+
241
+
242
+ def convert_generic(model_id: str, folder: str, filenames: Set[str], token: Optional[str]) -> ConversionResult:
243
+ operations = []
244
+ errors = []
245
+
246
+ extensions = set([".bin", ".ckpt"])
247
+ for filename in filenames:
248
+ prefix, ext = os.path.splitext(filename)
249
+ if ext in extensions:
250
+ pt_filename = hf_hub_download(model_id, filename=filename, token=token, cache_dir=folder)
251
+ dirname, raw_filename = os.path.split(filename)
252
+ if raw_filename == "pytorch_model.bin":
253
+ # XXX: This is a special case to handle `transformers` and the
254
+ # `transformers` part of the model which is actually loaded by `transformers`.
255
+ sf_in_repo = os.path.join(dirname, "model.safetensors")
256
+ else:
257
+ sf_in_repo = f"{prefix}.safetensors"
258
+ sf_filename = os.path.join(folder, sf_in_repo)
259
+ try:
260
+ convert_file(pt_filename, sf_filename)
261
+ operations.append(CommitOperationAdd(path_in_repo=sf_in_repo, path_or_fileobj=sf_filename))
262
+ except Exception as e:
263
+ errors.append((pt_filename, e))
264
+ return operations, errors
265
+
266
+
267
+ def convert(api: "HfApi", model_id: str, force: bool = False) -> Tuple["CommitInfo", List[Tuple[str, "Exception"]]]:
268
+ pr_title = "Adding `safetensors` variant of this model"
269
+ info = api.model_info(model_id)
270
+ filenames = set(s.rfilename for s in info.siblings)
271
+
272
+ with TemporaryDirectory() as d:
273
+ folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
274
+ os.makedirs(folder)
275
+ new_pr = None
276
+ try:
277
+ operations = None
278
+ pr = previous_pr(api, model_id, pr_title)
279
+
280
+ library_name = getattr(info, "library_name", None)
281
+ if any(filename.endswith(".safetensors") for filename in filenames) and not force:
282
+ raise AlreadyExists(f"Model {model_id} is already converted, skipping..")
283
+ elif pr is not None and not force:
284
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
285
+ new_pr = pr
286
+ raise AlreadyExists(f"Model {model_id} already has an open PR check out {url}")
287
+ elif library_name == "transformers":
288
+ if "pytorch_model.bin" in filenames:
289
+ operations, errors = convert_single(model_id, folder, token=api.token)
290
+ elif "pytorch_model.bin.index.json" in filenames:
291
+ operations, errors = convert_multi(model_id, folder, token=api.token)
292
+ else:
293
+ raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
294
+ # check_final_model(model_id, folder, token=api.token)
295
+ else:
296
+ operations, errors = convert_generic(model_id, folder, filenames, token=api.token)
297
+
298
+ if operations:
299
+ new_pr = api.create_commit(
300
+ repo_id=model_id,
301
+ operations=operations,
302
+ commit_message=pr_title,
303
+ commit_description=COMMIT_DESCRIPTION,
304
+ create_pr=True,
305
+ )
306
+ print(f"Pr created at {new_pr.pr_url}")
307
+ else:
308
+ print("No files to convert")
309
+ finally:
310
+ shutil.rmtree(folder)
311
+ return new_pr, errors
312
+
313
+
314
+ if __name__ == "__main__":
315
+ DESCRIPTION = """
316
+ Simple utility tool to convert automatically some weights on the hub to `safetensors` format.
317
+ It is PyTorch exclusive for now.
318
+ It works by downloading the weights (PT), converting them locally, and uploading them back
319
+ as a PR on the hub.
320
+ """
321
+ for i in range(1, 16): # Range starts at 1 and ends at 15
322
+ input_filename = f"jondurbin_airoboros-l2-70b-gpt4-1.4.1/pytorch_model-{i:05d}-of-00015.bin"
323
+ output_filename = f"pytorch_model-{i:05d}-of-00015.safetensors"
324
+ convert_file(input_filename, output_filename)