Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

download-model.py 9.0 KB

You have to be logged in to leave a comment. Sign In
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
  1. '''
  2. Downloads models from Hugging Face to models/model-name.
  3. Example:
  4. python download-model.py facebook/opt-1.3b
  5. NOTE: this file is based on https://github.com/oobabooga/text-generation-webui/blob/main/download-model.py and heavily modified for:
  6. - accelerate download speed by using aria2c
  7. - include unusual file types (4bit, GGML etc.)
  8. - misc fixes to adapt to environments
  9. Will sync upstream from time to time
  10. '''
  11. import argparse
  12. import base64
  13. import datetime
  14. import json
  15. import re
  16. import sys
  17. from pathlib import Path
  18. import subprocess
  19. import requests
  20. import tqdm
  21. from tqdm.contrib.concurrent import thread_map
  22. import os
  23. # import aria2p
  24. # aria2 = aria2p.API(
  25. # aria2p.Client(
  26. # host="http://IP",
  27. # port=0,
  28. # secret="TODO"
  29. # )
  30. # )
  31. parser = argparse.ArgumentParser()
  32. parser.add_argument('MODEL', type=str, default=None, nargs='?')
  33. parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.')
  34. parser.add_argument('--threads', type=int, default=8, help='Number of files to download simultaneously.')
  35. parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).')
  36. parser.add_argument('--output', type=str, default=None, help='The folder where the model should be saved.')
  37. args = parser.parse_args()
  38. def get_file(url, output_folder):
  39. r = requests.get(url, stream=True)
  40. with open(output_folder / Path(url.rsplit('/', 1)[1]), 'wb') as f:
  41. total_size = int(r.headers.get('content-length', 0))
  42. block_size = 1024
  43. with tqdm.tqdm(total=total_size, unit='iB', unit_scale=True, bar_format='{l_bar}{bar}| {n_fmt:6}/{total_fmt:6} {rate_fmt:6}') as t:
  44. for data in r.iter_content(block_size):
  45. t.update(len(data))
  46. f.write(data)
  47. def get_file_by_aria2(url, output_folder):
  48. filename = url.split('/')[-1]
  49. # r = requests.get(url, stream=True)
  50. # total_size = int(r.headers.get('content-length', 0))
  51. if (output_folder / Path(filename)).exists() and not (output_folder / Path(f"{filename}.aria2")).exists():
  52. print(f"Downloaded: {filename}")
  53. return
  54. # full_dir = f"{Path('/app/text-generation-webui/') / output_folder}"
  55. # print(f"aria2p downloading {url} to {full_dir} as {filename}")
  56. # aria2.add_uris(url, options={'dir': full_dir, 'out': filename})
  57. # /app/text-generation-webui/models
  58. aria_command = f"aria2c -c -x 16 -s 16 -k 1M {url} -d {output_folder} -o {filename}"
  59. print(f"Running: {aria_command}")
  60. # # call command line aria2c to download
  61. subprocess.run(aria_command, shell=True, check=True)
  62. def sanitize_branch_name(branch_name):
  63. pattern = re.compile(r"^[a-zA-Z0-9._-]+$")
  64. if pattern.match(branch_name):
  65. return branch_name
  66. else:
  67. raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.")
  68. def select_model_from_default_options():
  69. models = {
  70. "Pygmalion 6B original": ("PygmalionAI", "pygmalion-6b", "b8344bb4eb76a437797ad3b19420a13922aaabe1"),
  71. "Pygmalion 6B main": ("PygmalionAI", "pygmalion-6b", "main"),
  72. "Pygmalion 6B dev": ("PygmalionAI", "pygmalion-6b", "dev"),
  73. "Pygmalion 2.7B": ("PygmalionAI", "pygmalion-2.7b", "main"),
  74. "Pygmalion 1.3B": ("PygmalionAI", "pygmalion-1.3b", "main"),
  75. "Pygmalion 350m": ("PygmalionAI", "pygmalion-350m", "main"),
  76. "OPT 6.7b": ("facebook", "opt-6.7b", "main"),
  77. "OPT 2.7b": ("facebook", "opt-2.7b", "main"),
  78. "OPT 1.3b": ("facebook", "opt-1.3b", "main"),
  79. "OPT 350m": ("facebook", "opt-350m", "main"),
  80. }
  81. choices = {}
  82. print("Select the model that you want to download:\n")
  83. for i,name in enumerate(models):
  84. char = chr(ord('A')+i)
  85. choices[char] = name
  86. print(f"{char}) {name}")
  87. char = chr(ord('A')+len(models))
  88. print(f"{char}) None of the above")
  89. print()
  90. print("Input> ", end='')
  91. choice = input()[0].strip().upper()
  92. if choice == char:
  93. print("""\nThen type the name of your desired Hugging Face model in the format organization/name.
  94. Examples:
  95. PygmalionAI/pygmalion-6b
  96. facebook/opt-1.3b
  97. """)
  98. print("Input> ", end='')
  99. model = input()
  100. branch = "main"
  101. else:
  102. arr = models[choices[choice]]
  103. model = f"{arr[0]}/{arr[1]}"
  104. branch = arr[2]
  105. return model, branch
  106. def get_download_links_from_huggingface(model, branch):
  107. base = "https://huggingface.co"
  108. page = f"/api/models/{model}/tree/{branch}"
  109. cursor = b""
  110. links = []
  111. sha256 = []
  112. classifications = []
  113. has_pytorch = False
  114. has_pt = False
  115. has_safetensors = False
  116. is_lora = False
  117. while True:
  118. api_url = f"{base}{page}"
  119. if cursor != b"":
  120. api_url = f"{api_url}?cursor={cursor.decode()}"
  121. # print(api_url)
  122. content = requests.get(api_url).content
  123. # print(content)
  124. dict = json.loads(content)
  125. if len(dict) == 0:
  126. break
  127. for i in range(len(dict)):
  128. fname = dict[i]['path']
  129. if not is_lora and fname.endswith(('adapter_config.json', 'adapter_model.bin')):
  130. is_lora = True
  131. is_pytorch = re.match("(pytorch|adapter)_model.*\.bin", fname)
  132. is_safetensors = re.match(".*\.safetensors", fname)
  133. is_pt = re.match(".*\.pt", fname)
  134. is_tokenizer = re.match("tokenizer.*\.model", fname)
  135. is_text = re.match(".*\.(txt|json|py|md)", fname) or is_tokenizer
  136. is_4bit = re.match("int4.*\.bin", fname)
  137. is_ggml = re.match(".*(ggml|GGML).*\.bin", fname)
  138. if any((is_pytorch, is_safetensors, is_pt, is_tokenizer, is_text, is_ggml, is_4bit)):
  139. if 'lfs' in dict[i]:
  140. sha256.append([fname, dict[i]['lfs']['oid']])
  141. if is_text:
  142. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  143. classifications.append('text')
  144. continue
  145. if not args.text_only:
  146. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  147. if is_safetensors:
  148. has_safetensors = True
  149. classifications.append('safetensors')
  150. elif is_pytorch:
  151. has_pytorch = True
  152. classifications.append('pytorch')
  153. elif is_pt:
  154. has_pt = True
  155. classifications.append('pt')
  156. else:
  157. print(f'Skipping: {fname}')
  158. cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50'
  159. cursor = base64.b64encode(cursor)
  160. cursor = cursor.replace(b'=', b'%3D')
  161. # If both pytorch and safetensors are available, download safetensors only
  162. if (has_pytorch or has_pt) and has_safetensors:
  163. for i in range(len(classifications)-1, -1, -1):
  164. if classifications[i] in ['pytorch', 'pt']:
  165. links.pop(i)
  166. return links, sha256, is_lora
  167. def download_files(file_list, output_folder, num_threads=8):
  168. thread_map(lambda url: get_file_by_aria2(url, output_folder), file_list, max_workers=num_threads)
  169. if __name__ == '__main__':
  170. # determine the root of the repo and cd to it
  171. ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')
  172. os.chdir(ROOT)
  173. print(f"Working directory changed to: {ROOT}")
  174. model = args.MODEL
  175. branch = args.branch
  176. if model is None:
  177. model, branch = select_model_from_default_options()
  178. else:
  179. if model[-1] == '/':
  180. model = model[:-1]
  181. branch = args.branch
  182. if branch is None:
  183. branch = "main"
  184. else:
  185. try:
  186. branch = sanitize_branch_name(branch)
  187. except ValueError as err_branch:
  188. print(f"Error: {err_branch}")
  189. sys.exit()
  190. links, sha256, is_lora = get_download_links_from_huggingface(model, branch)
  191. if args.output is not None:
  192. base_folder = args.output
  193. else:
  194. base_folder = 'models' if not is_lora else 'loras'
  195. output_folder = f"{'_'.join(model.split('/')[-2:])}"
  196. if branch != 'main':
  197. output_folder += f'_{branch}'
  198. # Creating the folder and writing the metadata
  199. output_folder = Path(base_folder) / output_folder
  200. if not output_folder.exists():
  201. output_folder.mkdir(parents=True)
  202. with open(output_folder / 'huggingface-metadata.txt', 'w') as f:
  203. f.write(f'url: https://huggingface.co/{model}\n')
  204. f.write(f'branch: {branch}\n')
  205. f.write(f'download date: {str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}\n')
  206. sha256_str = ''
  207. for i in range(len(sha256)):
  208. sha256_str += f' {sha256[i][1]} {sha256[i][0]}\n'
  209. if sha256_str != '':
  210. f.write(f'sha256sum:\n{sha256_str}')
  211. # Downloading the files
  212. print(f"Downloading the model to {output_folder}")
  213. download_files(links, output_folder, args.threads)
  214. print()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...