download-model.py 6.8 KB

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