download-model.py 5.6 KB

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