download-model.py 7.8 KB

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