Narsil HF staff commited on
Commit
b273b9d
1 Parent(s): a61923f

Update convert.py

Browse files
Files changed (1) hide show
  1. convert.py +116 -47
convert.py CHANGED
@@ -2,42 +2,53 @@ import argparse
2
  import json
3
  import os
4
  import shutil
 
 
 
 
5
 
6
  import torch
7
 
8
- from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download
9
  from huggingface_hub.file_download import repo_folder_name
10
- from safetensors.torch import save_file
11
  from transformers import AutoConfig
12
  from transformers.pipelines.base import infer_framework_load_model
 
13
 
14
 
15
- def check_file_size(sf_filename, pt_filename):
 
 
 
 
 
 
 
 
 
 
16
  sf_size = os.stat(sf_filename).st_size
17
  pt_size = os.stat(pt_filename).st_size
18
 
19
  if (sf_size - pt_size) / pt_size > 0.01:
20
- raise RuntimeError(
21
- f"""The file size different is more than 1%:
22
  - {sf_filename}: {sf_size}
23
  - {pt_filename}: {pt_size}
24
- """
25
- )
26
 
27
 
28
- def rename(pt_filename) -> str:
29
  local = pt_filename.replace(".bin", ".safetensors")
30
  local = local.replace("pytorch_model", "model")
31
  return local
32
 
33
 
34
- def convert_multi(model_id, folder):
35
  filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
36
  with open(filename, "r") as f:
37
  data = json.load(f)
38
 
39
  filenames = set(data["weight_map"].values())
40
- local_filenames = []
41
  for filename in filenames:
42
  cached_filename = hf_hub_download(repo_id=model_id, filename=filename)
43
  loaded = torch.load(cached_filename)
@@ -56,19 +67,25 @@ def convert_multi(model_id, folder):
56
  json.dump(newdata, f)
57
  local_filenames.append(index)
58
 
59
- operations = [
60
- CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames
61
- ]
62
 
63
  return operations
64
 
65
 
66
- def convert_single(model_id, folder):
67
  sf_filename = "model.safetensors"
68
  filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
69
  loaded = torch.load(filename)
70
 
71
  local = os.path.join(folder, sf_filename)
 
 
 
 
 
 
 
 
72
  save_file(loaded, local, metadata={"format": "pt"})
73
 
74
  check_file_size(local, filename)
@@ -76,50 +93,97 @@ def convert_single(model_id, folder):
76
  operations = [CommitOperationAdd(path_in_repo=sf_filename, path_or_fileobj=local)]
77
  return operations
78
 
79
-
80
- def check_final_model(model_id, folder):
81
  config = hf_hub_download(repo_id=model_id, filename="config.json")
82
  shutil.copy(config, os.path.join(folder, "config.json"))
83
  config = AutoConfig.from_pretrained(folder)
84
- _, sf_model = infer_framework_load_model(folder, config)
85
  _, pt_model = infer_framework_load_model(model_id, config)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
- input_ids = torch.arange(10).long().unsqueeze(0)
88
- sf_logits = sf_model(input_ids)
89
- pt_logits = pt_model(input_ids)
90
  torch.testing.assert_close(sf_logits, pt_logits)
91
  print(f"Model {model_id} is ok !")
92
 
 
 
 
 
93
 
94
- def convert(api, model_id):
 
 
95
  info = api.model_info(model_id)
96
  filenames = set(s.rfilename for s in info.siblings)
97
 
98
- folder = repo_folder_name(repo_id=model_id, repo_type="models")
99
- os.makedirs(folder)
100
- new_pr = None
101
- try:
102
- operations = None
103
- if "model.safetensors" in filenames or "model_index.safetensors.index.json" in filenames:
104
- raise RuntimeError(f"Model {model_id} is already converted, skipping..")
105
- elif "pytorch_model.bin" in filenames:
106
- operations = convert_single(model_id, folder)
107
- elif "pytorch_model.bin.index.json" in filenames:
108
- operations = convert_multi(model_id, folder)
109
- else:
110
- raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
111
-
112
- if operations:
113
- check_final_model(model_id, folder)
114
- new_pr = api.create_commit(
115
- repo_id=model_id,
116
- operations=operations,
117
- commit_message="Adding `safetensors` variant of this model",
118
- create_pr=True,
119
- )
120
- finally:
121
- shutil.rmtree(folder)
122
- return new_pr
 
 
 
 
 
 
123
 
124
 
125
  if __name__ == "__main__":
@@ -135,7 +199,12 @@ if __name__ == "__main__":
135
  type=str,
136
  help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
137
  )
 
 
 
 
 
138
  args = parser.parse_args()
139
  model_id = args.model_id
140
  api = HfApi()
141
- convert(api, model_id)
 
2
  import json
3
  import os
4
  import shutil
5
+ from tempfile import TemporaryDirectory
6
+ from collections import defaultdict
7
+ from inspect import signature
8
+ from typing import Optional, List
9
 
10
  import torch
11
 
12
+ from huggingface_hub import CommitOperationAdd, HfApi, hf_hub_download, get_repo_discussions
13
  from huggingface_hub.file_download import repo_folder_name
 
14
  from transformers import AutoConfig
15
  from transformers.pipelines.base import infer_framework_load_model
16
+ from safetensors.torch import save_file
17
 
18
 
19
+ def shared_pointers(tensors):
20
+ ptrs = defaultdict(list)
21
+ for k, v in tensors.items():
22
+ ptrs[v.data_ptr()].append(k)
23
+ failing = []
24
+ for ptr, names in ptrs.items():
25
+ if len(names) > 1:
26
+ failing.append(names)
27
+ return failing
28
+
29
+ def check_file_size(sf_filename: str, pt_filename: str):
30
  sf_size = os.stat(sf_filename).st_size
31
  pt_size = os.stat(pt_filename).st_size
32
 
33
  if (sf_size - pt_size) / pt_size > 0.01:
34
+ raise RuntimeError(f"""The file size different is more than 1%:
 
35
  - {sf_filename}: {sf_size}
36
  - {pt_filename}: {pt_size}
37
+ """)
 
38
 
39
 
40
+ def rename(pt_filename: str) -> str:
41
  local = pt_filename.replace(".bin", ".safetensors")
42
  local = local.replace("pytorch_model", "model")
43
  return local
44
 
45
 
46
+ def convert_multi(model_id: str) -> List["CommitOperationAdd"]:
47
  filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin.index.json")
48
  with open(filename, "r") as f:
49
  data = json.load(f)
50
 
51
  filenames = set(data["weight_map"].values())
 
52
  for filename in filenames:
53
  cached_filename = hf_hub_download(repo_id=model_id, filename=filename)
54
  loaded = torch.load(cached_filename)
 
67
  json.dump(newdata, f)
68
  local_filenames.append(index)
69
 
70
+ operations = [CommitOperationAdd(path_in_repo=local.split("/")[-1], path_or_fileobj=local) for local in local_filenames]
 
 
71
 
72
  return operations
73
 
74
 
75
+ def convert_single(model_id: str, folder: str) -> List["CommitOperationAdd"]:
76
  sf_filename = "model.safetensors"
77
  filename = hf_hub_download(repo_id=model_id, filename="pytorch_model.bin")
78
  loaded = torch.load(filename)
79
 
80
  local = os.path.join(folder, sf_filename)
81
+ shared = shared_pointers(loaded)
82
+ for shared_weights in shared:
83
+ for name in shared_weights[1:]:
84
+ loaded.pop(name)
85
+
86
+ # For tensors to be contiguous
87
+ loaded = {k: v.contiguous() for k, v in loaded.items()}
88
+
89
  save_file(loaded, local, metadata={"format": "pt"})
90
 
91
  check_file_size(local, filename)
 
93
  operations = [CommitOperationAdd(path_in_repo=sf_filename, path_or_fileobj=local)]
94
  return operations
95
 
96
+ def check_final_model(model_id: str, folder: str):
 
97
  config = hf_hub_download(repo_id=model_id, filename="config.json")
98
  shutil.copy(config, os.path.join(folder, "config.json"))
99
  config = AutoConfig.from_pretrained(folder)
100
+
101
  _, pt_model = infer_framework_load_model(model_id, config)
102
+ _, sf_model = infer_framework_load_model(folder, config)
103
+
104
+ pt_model = pt_model
105
+ sf_model = sf_model
106
+
107
+ pt_params = pt_model.state_dict()
108
+ sf_params = sf_model.state_dict()
109
+
110
+ pt_shared = shared_pointers(pt_params)
111
+ sf_shared = shared_pointers(sf_params)
112
+ if pt_shared != sf_shared:
113
+ raise RuntimeError("The reconstructed model is wrong, shared tensors are different {shared_pt} != {shared_tf}")
114
+
115
+ sig = signature(pt_model.forward)
116
+ input_ids = torch.arange(10).unsqueeze(0)
117
+ pixel_values = torch.randn(1, 3, 224, 224)
118
+ input_values = torch.arange(1000).float().unsqueeze(0)
119
+ kwargs = {}
120
+ if "input_ids" in sig.parameters:
121
+ kwargs["input_ids"] = input_ids
122
+ if "decoder_input_ids" in sig.parameters:
123
+ kwargs["decoder_input_ids"] = input_ids
124
+ if "pixel_values" in sig.parameters:
125
+ kwargs["pixel_values"] = pixel_values
126
+ if "input_values" in sig.parameters:
127
+ kwargs["input_values"] = input_values
128
+ if "bbox" in sig.parameters:
129
+ kwargs["bbox"] = torch.zeros((1, 10, 4)).long()
130
+ if "image" in sig.parameters:
131
+ kwargs["image"] = pixel_values
132
+
133
+
134
+ if torch.cuda.is_available():
135
+ pt_model = pt_model.cuda()
136
+ sf_model = sf_model.cuda()
137
+ kwargs = {k: v.cuda() for k, v in kwargs.items()}
138
+
139
+ pt_logits = pt_model(**kwargs)[0]
140
+ sf_logits = sf_model(**kwargs)[0]
141
 
 
 
 
142
  torch.testing.assert_close(sf_logits, pt_logits)
143
  print(f"Model {model_id} is ok !")
144
 
145
+ def previous_pr(model_id: str, pr_title: str) -> Optional["Discussion"]:
146
+ for discussion in get_repo_discussions(repo_id=model_id):
147
+ if discussion.status == "open" and discussion.is_pull_request and discussion.title == pr_title:
148
+ return discussion
149
 
150
+
151
+ def convert(api: "HfApi", model_id: str, force: bool=False) -> Optional["CommitInfo"]:
152
+ pr_title = "Adding `safetensors` variant of this model"
153
  info = api.model_info(model_id)
154
  filenames = set(s.rfilename for s in info.siblings)
155
 
156
+ with TemporaryDirectory() as d:
157
+ folder = os.path.join(d, repo_folder_name(repo_id=model_id, repo_type="models"))
158
+ os.makedirs(folder)
159
+ new_pr = None
160
+ try:
161
+ operations = None
162
+ pr = previous_pr(model_id, pr_title)
163
+ if ("model.safetensors" in filenames or "model_index.safetensors.index.json" in filenames) and not force:
164
+ raise RuntimeError(f"Model {model_id} is already converted, skipping..")
165
+ elif pr is not None and not force:
166
+ url = f"https://huggingface.co/{model_id}/discussions/{pr.num}"
167
+ new_pr = pr
168
+ raise RuntimeError(f"Model {model_id} already has an open PR check out {url}")
169
+ elif "pytorch_model.bin" in filenames:
170
+ operations = convert_single(model_id, folder)
171
+ elif "pytorch_model.bin.index.json" in filenames:
172
+ operations = convert_multi(model_id, folder)
173
+ else:
174
+ raise RuntimeError(f"Model {model_id} doesn't seem to be a valid pytorch model. Cannot convert")
175
+
176
+ if operations:
177
+ check_final_model(model_id, folder)
178
+ new_pr = api.create_commit(
179
+ repo_id=model_id,
180
+ operations=operations,
181
+ commit_message=pr_title,
182
+ create_pr=True,
183
+ )
184
+ finally:
185
+ shutil.rmtree(folder)
186
+ return new_pr
187
 
188
 
189
  if __name__ == "__main__":
 
199
  type=str,
200
  help="The name of the model on the hub to convert. E.g. `gpt2` or `facebook/wav2vec2-base-960h`",
201
  )
202
+ parser.add_argument(
203
+ "--force",
204
+ action="store_true",
205
+ help="Create the PR even if it already exists of if the model was already converted.",
206
+ )
207
  args = parser.parse_args()
208
  model_id = args.model_id
209
  api = HfApi()
210
+ convert(api, model_id, force=args.force)