download-model.py 7.7 KB

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