download-model.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. '''
  2. Downloads models from Hugging Face to models/model-name.
  3. Example:
  4. python download-model.py facebook/opt-1.3b
  5. '''
  6. import argparse
  7. import base64
  8. import datetime
  9. import hashlib
  10. import json
  11. import re
  12. import sys
  13. from pathlib import Path
  14. import requests
  15. import tqdm
  16. from tqdm.contrib.concurrent import thread_map
  17. parser = argparse.ArgumentParser()
  18. parser.add_argument('MODEL', type=str, default=None, nargs='?')
  19. parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.')
  20. parser.add_argument('--threads', type=int, default=1, help='Number of files to download simultaneously.')
  21. parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).')
  22. parser.add_argument('--output', type=str, default=None, help='The folder where the model should be saved.')
  23. parser.add_argument('--clean', action='store_true', help='Does not resume the previous download.')
  24. parser.add_argument('--check', action='store_true', help='Validates the checksums of model files.')
  25. args = parser.parse_args()
  26. def get_file(url, output_folder):
  27. filename = Path(url.rsplit('/', 1)[1])
  28. output_path = output_folder / filename
  29. if output_path.exists() and not args.clean:
  30. # Check if the file has already been downloaded completely
  31. r = requests.get(url, stream=True)
  32. total_size = int(r.headers.get('content-length', 0))
  33. if output_path.stat().st_size >= total_size:
  34. return
  35. # Otherwise, resume the download from where it left off
  36. headers = {'Range': f'bytes={output_path.stat().st_size}-'}
  37. mode = 'ab'
  38. else:
  39. headers = {}
  40. mode = 'wb'
  41. r = requests.get(url, stream=True, headers=headers)
  42. with open(output_path, mode) as f:
  43. total_size = int(r.headers.get('content-length', 0))
  44. block_size = 1024
  45. 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:
  46. for data in r.iter_content(block_size):
  47. t.update(len(data))
  48. f.write(data)
  49. def sanitize_branch_name(branch_name):
  50. pattern = re.compile(r"^[a-zA-Z0-9._-]+$")
  51. if pattern.match(branch_name):
  52. return branch_name
  53. else:
  54. raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.")
  55. def select_model_from_default_options():
  56. models = {
  57. "Pygmalion 6B original": ("PygmalionAI", "pygmalion-6b", "b8344bb4eb76a437797ad3b19420a13922aaabe1"),
  58. "Pygmalion 6B main": ("PygmalionAI", "pygmalion-6b", "main"),
  59. "Pygmalion 6B dev": ("PygmalionAI", "pygmalion-6b", "dev"),
  60. "Pygmalion 2.7B": ("PygmalionAI", "pygmalion-2.7b", "main"),
  61. "Pygmalion 1.3B": ("PygmalionAI", "pygmalion-1.3b", "main"),
  62. "Pygmalion 350m": ("PygmalionAI", "pygmalion-350m", "main"),
  63. "OPT 6.7b": ("facebook", "opt-6.7b", "main"),
  64. "OPT 2.7b": ("facebook", "opt-2.7b", "main"),
  65. "OPT 1.3b": ("facebook", "opt-1.3b", "main"),
  66. "OPT 350m": ("facebook", "opt-350m", "main"),
  67. }
  68. choices = {}
  69. print("Select the model that you want to download:\n")
  70. for i,name in enumerate(models):
  71. char = chr(ord('A')+i)
  72. choices[char] = name
  73. print(f"{char}) {name}")
  74. char = chr(ord('A')+len(models))
  75. print(f"{char}) None of the above")
  76. print()
  77. print("Input> ", end='')
  78. choice = input()[0].strip().upper()
  79. if choice == char:
  80. print("""\nThen type the name of your desired Hugging Face model in the format organization/name.
  81. Examples:
  82. PygmalionAI/pygmalion-6b
  83. facebook/opt-1.3b
  84. """)
  85. print("Input> ", end='')
  86. model = input()
  87. branch = "main"
  88. else:
  89. arr = models[choices[choice]]
  90. model = f"{arr[0]}/{arr[1]}"
  91. branch = arr[2]
  92. return model, branch
  93. def get_download_links_from_huggingface(model, branch):
  94. base = "https://huggingface.co"
  95. page = f"/api/models/{model}/tree/{branch}?cursor="
  96. cursor = b""
  97. links = []
  98. sha256 = []
  99. classifications = []
  100. has_pytorch = False
  101. has_pt = False
  102. has_ggml = False
  103. has_safetensors = False
  104. is_lora = False
  105. while True:
  106. content = requests.get(f"{base}{page}{cursor.decode()}").content
  107. dict = json.loads(content)
  108. if len(dict) == 0:
  109. break
  110. for i in range(len(dict)):
  111. fname = dict[i]['path']
  112. if not is_lora and fname.endswith(('adapter_config.json', 'adapter_model.bin')):
  113. is_lora = True
  114. is_pytorch = re.match("(pytorch|adapter)_model.*\.bin", fname)
  115. is_safetensors = re.match(".*\.safetensors", fname)
  116. is_pt = re.match(".*\.pt", fname)
  117. is_ggml = re.match("ggml.*\.bin", fname)
  118. is_tokenizer = re.match("tokenizer.*\.model", fname)
  119. is_text = re.match(".*\.(txt|json|py|md)", fname) or is_tokenizer
  120. if any((is_pytorch, is_safetensors, is_pt, is_tokenizer, is_text)):
  121. if 'lfs' in dict[i]:
  122. sha256.append([fname, dict[i]['lfs']['oid']])
  123. if is_text:
  124. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  125. classifications.append('text')
  126. continue
  127. if not args.text_only:
  128. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  129. if is_safetensors:
  130. has_safetensors = True
  131. classifications.append('safetensors')
  132. elif is_pytorch:
  133. has_pytorch = True
  134. classifications.append('pytorch')
  135. elif is_pt:
  136. has_pt = True
  137. classifications.append('pt')
  138. elif is_ggml:
  139. has_ggml = True
  140. classifications.append('ggml')
  141. cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50'
  142. cursor = base64.b64encode(cursor)
  143. cursor = cursor.replace(b'=', b'%3D')
  144. # If both pytorch and safetensors are available, download safetensors only
  145. if (has_pytorch or has_pt) and has_safetensors:
  146. for i in range(len(classifications)-1, -1, -1):
  147. if classifications[i] in ['pytorch', 'pt']:
  148. links.pop(i)
  149. return links, sha256, is_lora
  150. def download_files(file_list, output_folder, num_threads=8):
  151. thread_map(lambda url: get_file(url, output_folder), file_list, max_workers=num_threads, disable=True)
  152. if __name__ == '__main__':
  153. model = args.MODEL
  154. branch = args.branch
  155. if model is None:
  156. model, branch = select_model_from_default_options()
  157. else:
  158. if model[-1] == '/':
  159. model = model[:-1]
  160. branch = args.branch
  161. if branch is None:
  162. branch = "main"
  163. else:
  164. try:
  165. branch = sanitize_branch_name(branch)
  166. except ValueError as err_branch:
  167. print(f"Error: {err_branch}")
  168. sys.exit()
  169. links, sha256, is_lora = get_download_links_from_huggingface(model, branch)
  170. if args.output is not None:
  171. base_folder = args.output
  172. else:
  173. base_folder = 'models' if not is_lora else 'loras'
  174. output_folder = f"{'_'.join(model.split('/')[-2:])}"
  175. if branch != 'main':
  176. output_folder += f'_{branch}'
  177. output_folder = Path(base_folder) / output_folder
  178. if args.check:
  179. # Validate the checksums
  180. validated = True
  181. for i in range(len(sha256)):
  182. fpath = (output_folder / sha256[i][0])
  183. if not fpath.exists():
  184. print(f"The following file is missing: {fpath}")
  185. validated = False
  186. continue
  187. with open(output_folder / sha256[i][0], "rb") as f:
  188. bytes = f.read()
  189. file_hash = hashlib.sha256(bytes).hexdigest()
  190. if file_hash != sha256[i][1]:
  191. print(f'Checksum failed: {sha256[i][0]} {sha256[i][1]}')
  192. validated = False
  193. else:
  194. print(f'Checksum validated: {sha256[i][0]} {sha256[i][1]}')
  195. if validated:
  196. print('[+] Validated checksums of all model files!')
  197. else:
  198. print('[-] Invalid checksums. Rerun download-model.py with the --clean flag.')
  199. else:
  200. # Creating the folder and writing the metadata
  201. if not output_folder.exists():
  202. output_folder.mkdir()
  203. with open(output_folder / 'huggingface-metadata.txt', 'w') as f:
  204. f.write(f'url: https://huggingface.co/{model}\n')
  205. f.write(f'branch: {branch}\n')
  206. f.write(f'download date: {str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}\n')
  207. sha256_str = ''
  208. for i in range(len(sha256)):
  209. sha256_str += f' {sha256[i][1]} {sha256[i][0]}\n'
  210. if sha256_str != '':
  211. f.write(f'sha256sum:\n{sha256_str}')
  212. # Downloading the files
  213. print(f"Downloading the model to {output_folder}")
  214. download_files(links, output_folder, args.threads)