download-model.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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_tokenizer = re.match("tokenizer.*\.model", fname)
  94. is_text = re.match(".*\.(txt|json)", fname)
  95. if any((is_pytorch, is_safetensors, is_text, is_tokenizer)):
  96. if is_text:
  97. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  98. classifications.append('text')
  99. continue
  100. if not args.text_only:
  101. links.append(f"https://huggingface.co/{model}/resolve/{branch}/{fname}")
  102. if is_safetensors:
  103. has_safetensors = True
  104. classifications.append('safetensors')
  105. elif is_pytorch:
  106. has_pytorch = True
  107. classifications.append('pytorch')
  108. #page = dict['nextUrl']
  109. page = None
  110. # If both pytorch and safetensors are available, download safetensors only
  111. if has_pytorch and has_safetensors:
  112. for i in range(len(classifications)-1, -1, -1):
  113. if classifications[i] == 'pytorch':
  114. links.pop(i)
  115. return links
  116. if __name__ == '__main__':
  117. model = args.MODEL
  118. branch = args.branch
  119. if model is None:
  120. model, branch = select_model_from_default_options()
  121. else:
  122. if model[-1] == '/':
  123. model = model[:-1]
  124. branch = args.branch
  125. if branch is None:
  126. branch = "main"
  127. else:
  128. try:
  129. branch = sanitize_branch_name(branch)
  130. except ValueError as err_branch:
  131. print(f"Error: {err_branch}")
  132. sys.exit()
  133. if branch != 'main':
  134. output_folder = Path("models") / (model.split('/')[-1] + f'_{branch}')
  135. else:
  136. output_folder = Path("models") / model.split('/')[-1]
  137. if not output_folder.exists():
  138. output_folder.mkdir()
  139. links = get_download_links_from_huggingface(model, branch)
  140. # Downloading the files
  141. print(f"Downloading the model to {output_folder}")
  142. pool = multiprocessing.Pool(processes=args.threads)
  143. results = pool.map(get_file, [[links[i], output_folder, i+1, len(links)] for i in range(len(links))])
  144. pool.close()
  145. pool.join()