download-model.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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 multiprocessing
  8. import re
  9. import sys
  10. from pathlib import Path
  11. import requests
  12. import tqdm
  13. from bs4 import BeautifulSoup
  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. if __name__ == '__main__':
  80. model = args.MODEL
  81. branch = args.branch
  82. if model is None:
  83. model, branch = select_model_from_default_options()
  84. else:
  85. if model[-1] == '/':
  86. model = model[:-1]
  87. branch = args.branch
  88. if branch is None:
  89. branch = "main"
  90. else:
  91. try:
  92. branch = sanitize_branch_name(branch)
  93. except ValueError as err_branch:
  94. print(f"Error: {err_branch}")
  95. sys.exit()
  96. url = f'https://huggingface.co/{model}/tree/{branch}'
  97. if branch != 'main':
  98. output_folder = Path("models") / (model.split('/')[-1] + f'_{branch}')
  99. else:
  100. output_folder = Path("models") / model.split('/')[-1]
  101. if not output_folder.exists():
  102. output_folder.mkdir()
  103. # Finding the relevant files to download
  104. page = requests.get(url)
  105. soup = BeautifulSoup(page.content, 'html.parser')
  106. links = soup.find_all('a')
  107. downloads = []
  108. classifications = []
  109. has_pytorch = False
  110. has_safetensors = False
  111. for link in links:
  112. href = link.get('href')[1:]
  113. if href.startswith(f'{model}/resolve/{branch}'):
  114. fname = Path(href).name
  115. is_pytorch = re.match("pytorch_model.*\.bin", fname)
  116. is_safetensors = re.match("model.*\.safetensors", fname)
  117. is_text = re.match(".*\.(txt|json)", fname)
  118. if is_text or is_safetensors or is_pytorch:
  119. if is_text:
  120. downloads.append(f'https://huggingface.co/{href}')
  121. classifications.append('text')
  122. continue
  123. if not args.text_only:
  124. downloads.append(f'https://huggingface.co/{href}')
  125. if is_safetensors:
  126. has_safetensors = True
  127. classifications.append('safetensors')
  128. elif is_pytorch:
  129. has_pytorch = True
  130. classifications.append('pytorch')
  131. # If both pytorch and safetensors are available, download safetensors only
  132. if has_pytorch and has_safetensors:
  133. for i in range(len(classifications)-1, -1, -1):
  134. if classifications[i] == 'pytorch':
  135. downloads.pop(i)
  136. # Downloading the files
  137. print(f"Downloading the model to {output_folder}")
  138. pool = multiprocessing.Pool(processes=args.threads)
  139. results = pool.map(get_file, [[downloads[i], output_folder, i+1, len(downloads)] for i in range(len(downloads))])
  140. pool.close()
  141. pool.join()