download-model.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 json
  10. import re
  11. import sys
  12. from pathlib import Path
  13. import requests
  14. import tqdm
  15. from tqdm.contrib.concurrent import thread_map
  16. import hashlib
  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.head(url)
  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_safetensors = False
  103. is_lora = False
  104. while True:
  105. content = requests.get(f"{base}{page}{cursor.decode()}").content
  106. dict = json.loads(content)
  107. if len(dict) == 0:
  108. break
  109. for i in range(len(dict)):
  110. fname = dict[i]['path']
  111. if not is_lora and fname.endswith(('adapter_config.json', 'adapter_model.bin')):
  112. is_lora = True
  113. is_pytorch = re.match("(pytorch|adapter)_model.*\.bin", fname)
  114. is_safetensors = re.match(".*\.safetensors", fname)
  115. is_pt = re.match(".*\.pt", fname)
  116. is_tokenizer = re.match("tokenizer.*\.model", fname)
  117. is_text = re.match(".*\.(txt|json|py|md)", fname) or is_tokenizer
  118. if any((is_pytorch, is_safetensors, is_pt, is_tokenizer, is_text)):
  119. if 'lfs' in dict[i]:
  120. sha256.append([fname, dict[i]['lfs']['oid']])
  121. if is_text:
  122. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  123. classifications.append('text')
  124. continue
  125. if not args.text_only:
  126. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  127. if is_safetensors:
  128. has_safetensors = True
  129. classifications.append('safetensors')
  130. elif is_pytorch:
  131. has_pytorch = True
  132. classifications.append('pytorch')
  133. elif is_pt:
  134. has_pt = True
  135. classifications.append('pt')
  136. cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50'
  137. cursor = base64.b64encode(cursor)
  138. cursor = cursor.replace(b'=', b'%3D')
  139. # If both pytorch and safetensors are available, download safetensors only
  140. if (has_pytorch or has_pt) and has_safetensors:
  141. for i in range(len(classifications)-1, -1, -1):
  142. if classifications[i] in ['pytorch', 'pt']:
  143. links.pop(i)
  144. return links, sha256, is_lora
  145. def download_files(file_list, output_folder, num_threads=8):
  146. thread_map(lambda url: get_file(url, output_folder), file_list, max_workers=num_threads, disable=True)
  147. if __name__ == '__main__':
  148. model = args.MODEL
  149. branch = args.branch
  150. if model is None:
  151. model, branch = select_model_from_default_options()
  152. else:
  153. if model[-1] == '/':
  154. model = model[:-1]
  155. branch = args.branch
  156. if branch is None:
  157. branch = "main"
  158. else:
  159. try:
  160. branch = sanitize_branch_name(branch)
  161. except ValueError as err_branch:
  162. print(f"Error: {err_branch}")
  163. sys.exit()
  164. links, sha256, is_lora = get_download_links_from_huggingface(model, branch)
  165. if args.output is not None:
  166. base_folder = args.output
  167. else:
  168. base_folder = 'models' if not is_lora else 'loras'
  169. output_folder = f"{'_'.join(model.split('/')[-2:])}"
  170. if branch != 'main':
  171. output_folder += f'_{branch}'
  172. # Creating the folder and writing the metadata
  173. output_folder = Path(base_folder) / output_folder
  174. if not output_folder.exists():
  175. output_folder.mkdir()
  176. with open(output_folder / 'huggingface-metadata.txt', 'w') as f:
  177. f.write(f'url: https://huggingface.co/{model}\n')
  178. f.write(f'branch: {branch}\n')
  179. f.write(f'download date: {str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))}\n')
  180. sha256_str = ''
  181. for i in range(len(sha256)):
  182. sha256_str += f' {sha256[i][1]} {sha256[i][0]}\n'
  183. if sha256_str != '':
  184. f.write(f'sha256sum:\n{sha256_str}')
  185. # Downloading the files
  186. print(f"Downloading the model to {output_folder}")
  187. download_files(links, output_folder, args.threads)
  188. if args.check:
  189. # Validate the checksums
  190. validated = True
  191. for i in range(len(sha256)):
  192. with open(output_folder / sha256[i][0], "rb") as f:
  193. bytes = f.read()
  194. file_hash = hashlib.sha256(bytes).hexdigest()
  195. if file_hash != sha256[i][1]:
  196. print(f'[!] Checksum for {sha256[i][0]} failed!')
  197. validated = False
  198. if validated:
  199. print('[+] Validated checksums of all model files!')
  200. else:
  201. print('[-] Rerun the download-model.py with --clean flag')