download-model.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 json
  9. import multiprocessing
  10. import re
  11. import sys
  12. from pathlib import Path
  13. import requests
  14. import tqdm
  15. parser = argparse.ArgumentParser()
  16. parser.add_argument('MODEL', type=str, default=None, nargs='?')
  17. parser.add_argument('--branch', type=str, default='main', help='Name of the Git branch to download from.')
  18. parser.add_argument('--threads', type=int, default=1, help='Number of files to download simultaneously.')
  19. parser.add_argument('--text-only', action='store_true', help='Only download text files (txt/json).')
  20. args = parser.parse_args()
  21. def get_file(args):
  22. url = args[0]
  23. output_folder = args[1]
  24. idx = args[2]
  25. tot = args[3]
  26. print(f"Downloading file {idx} of {tot}...")
  27. r = requests.get(url, stream=True)
  28. with open(output_folder / Path(url.split('/')[-1]), 'wb') as f:
  29. total_size = int(r.headers.get('content-length', 0))
  30. block_size = 1024
  31. t = tqdm.tqdm(total=total_size, unit='iB', unit_scale=True)
  32. for data in r.iter_content(block_size):
  33. t.update(len(data))
  34. f.write(data)
  35. t.close()
  36. def sanitize_branch_name(branch_name):
  37. pattern = re.compile(r"^[a-zA-Z0-9._-]+$")
  38. if pattern.match(branch_name):
  39. return branch_name
  40. else:
  41. raise ValueError("Invalid branch name. Only alphanumeric characters, period, underscore and dash are allowed.")
  42. def select_model_from_default_options():
  43. models = {
  44. "Pygmalion 6B original": ("PygmalionAI", "pygmalion-6b", "b8344bb4eb76a437797ad3b19420a13922aaabe1"),
  45. "Pygmalion 6B main": ("PygmalionAI", "pygmalion-6b", "main"),
  46. "Pygmalion 6B dev": ("PygmalionAI", "pygmalion-6b", "dev"),
  47. "Pygmalion 2.7B": ("PygmalionAI", "pygmalion-2.7b", "main"),
  48. "Pygmalion 1.3B": ("PygmalionAI", "pygmalion-1.3b", "main"),
  49. "Pygmalion 350m": ("PygmalionAI", "pygmalion-350m", "main"),
  50. "OPT 6.7b": ("facebook", "opt-6.7b", "main"),
  51. "OPT 2.7b": ("facebook", "opt-2.7b", "main"),
  52. "OPT 1.3b": ("facebook", "opt-1.3b", "main"),
  53. "OPT 350m": ("facebook", "opt-350m", "main"),
  54. }
  55. choices = {}
  56. print("Select the model that you want to download:\n")
  57. for i,name in enumerate(models):
  58. char = chr(ord('A')+i)
  59. choices[char] = name
  60. print(f"{char}) {name}")
  61. char = chr(ord('A')+len(models))
  62. print(f"{char}) None of the above")
  63. print()
  64. print("Input> ", end='')
  65. choice = input()[0].strip().upper()
  66. if choice == char:
  67. print("""\nThen type the name of your desired Hugging Face model in the format organization/name.
  68. Examples:
  69. PygmalionAI/pygmalion-6b
  70. facebook/opt-1.3b
  71. """)
  72. print("Input> ", end='')
  73. model = input()
  74. branch = "main"
  75. else:
  76. arr = models[choices[choice]]
  77. model = f"{arr[0]}/{arr[1]}"
  78. branch = arr[2]
  79. return model, branch
  80. def get_download_links_from_huggingface(model, branch):
  81. base = "https://huggingface.co"
  82. page = f"/api/models/{model}/tree/{branch}?cursor="
  83. cursor = b""
  84. links = []
  85. classifications = []
  86. has_pytorch = False
  87. has_safetensors = False
  88. while True:
  89. content = requests.get(f"{base}{page}{cursor.decode()}").content
  90. dict = json.loads(content)
  91. if len(dict) == 0:
  92. break
  93. for i in range(len(dict)):
  94. fname = dict[i]['path']
  95. is_pytorch = re.match("pytorch_model.*\.bin", fname)
  96. is_safetensors = re.match("model.*\.safetensors", fname)
  97. is_tokenizer = re.match("tokenizer.*\.model", fname)
  98. is_text = re.match(".*\.(txt|json)", fname) or is_tokenizer
  99. if any((is_pytorch, is_safetensors, is_text, is_tokenizer)):
  100. if is_text:
  101. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  102. classifications.append('text')
  103. continue
  104. if not args.text_only:
  105. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  106. if is_safetensors:
  107. has_safetensors = True
  108. classifications.append('safetensors')
  109. elif is_pytorch:
  110. has_pytorch = True
  111. classifications.append('pytorch')
  112. cursor = base64.b64encode(f'{{"file_name":"{dict[-1]["path"]}"}}'.encode()) + b':50'
  113. cursor = base64.b64encode(cursor)
  114. cursor = cursor.replace(b'=', b'%3D')
  115. # If both pytorch and safetensors are available, download safetensors only
  116. if has_pytorch and has_safetensors:
  117. for i in range(len(classifications)-1, -1, -1):
  118. if classifications[i] == 'pytorch':
  119. links.pop(i)
  120. return links
  121. if __name__ == '__main__':
  122. model = args.MODEL
  123. branch = args.branch
  124. if model is None:
  125. model, branch = select_model_from_default_options()
  126. else:
  127. if model[-1] == '/':
  128. model = model[:-1]
  129. branch = args.branch
  130. if branch is None:
  131. branch = "main"
  132. else:
  133. try:
  134. branch = sanitize_branch_name(branch)
  135. except ValueError as err_branch:
  136. print(f"Error: {err_branch}")
  137. sys.exit()
  138. if branch != 'main':
  139. output_folder = Path("models") / (model.split('/')[-1] + f'_{branch}')
  140. else:
  141. output_folder = Path("models") / model.split('/')[-1]
  142. if not output_folder.exists():
  143. output_folder.mkdir()
  144. links = get_download_links_from_huggingface(model, branch)
  145. # Downloading the files
  146. print(f"Downloading the model to {output_folder}")
  147. pool = multiprocessing.Pool(processes=args.threads)
  148. results = pool.map(get_file, [[links[i], output_folder, i+1, len(links)] for i in range(len(links))])
  149. pool.close()
  150. pool.join()