convert_model.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import argparse
  2. import os
  3. import psutil
  4. import torch.backends.quantized
  5. import torch.nn as nn
  6. import transformers
  7. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  8. from huggingface_hub import Repository
  9. from tqdm.auto import tqdm
  10. from src import BloomModel
  11. from src.bloom.from_pretrained import BLOCK_BRANCH_PREFIX, CLIENT_BRANCH
  12. from src.client import DistributedBloomConfig
  13. use_hivemind_log_handler("in_root_logger")
  14. logger = get_logger(__file__)
  15. DTYPE_MAP = dict(bfloat16=torch.bfloat16, float16=torch.float16, float32=torch.float32, auto="auto")
  16. if __name__ == "__main__":
  17. parser = argparse.ArgumentParser(description="Load bloom layers and convert to 8-bit using torch quantization.")
  18. parser.add_argument("--model", type=str, default="bigscience/bloom-6b3", help="Model name for from_pretrained")
  19. parser.add_argument("--revision", type=str, default=None, help="Optional commit id from HF hub")
  20. parser.add_argument("--torch_dtype", type=str, default="auto", help="Load initial model in this dtype")
  21. parser.add_argument("--output_path", type=str, default="./converted_model", help="Track output repo to this folder")
  22. parser.add_argument("--output_repo", type=str, default="bigscience/test-bloomd", help="Push to this HF hub repo")
  23. parser.add_argument("--client_branch", type=str, default=CLIENT_BRANCH, help="Save client version to this branch")
  24. parser.add_argument(
  25. "--block_branch_prefix", type=str, default=BLOCK_BRANCH_PREFIX, help="Save blocks to branches with this prefix"
  26. )
  27. parser.add_argument(
  28. "--commit_message", type=str, default="push-o-matic", help="Use this commit message for all parts"
  29. )
  30. parser.add_argument("--use_auth_token", type=str, default=None, help="auth token for from_pretrained")
  31. parser.add_argument("--resize_token_embeddings", type=int, default=None, help="change the vocabulary size")
  32. args = parser.parse_args()
  33. free_ram_gb = psutil.virtual_memory().available / 2**30
  34. if args.model == "bigscience/bloom" and free_ram_gb < 400:
  35. logger.warning(f"ACHTUNG! converting bloom-176b will use up 350-400GB RAM, you have {free_ram_gb:.3f} free")
  36. assert args.torch_dtype in DTYPE_MAP, f"torch_dtype must be one of {list(DTYPE_MAP.keys())}"
  37. if os.path.exists(args.output_path) and (
  38. len(os.listdir(args.output_path)) != 0 or not os.path.isdir(args.output_path)
  39. ):
  40. raise FileExistsError(f"Output path {args.output_path} already exists and is not an empty directory")
  41. logger.info(f"Loading source model {args.model} (this may take a few minutes)")
  42. config = DistributedBloomConfig.from_pretrained(
  43. args.model, use_auth_token=args.use_auth_token, revision=args.revision
  44. )
  45. config.dht_prefix = args.output_repo
  46. model = BloomModel.from_pretrained(
  47. args.model, use_auth_token=args.use_auth_token, revision=args.revision, torch_dtype=DTYPE_MAP[args.torch_dtype]
  48. )
  49. if args.resize_token_embeddings:
  50. logger.info(f"Resizing token embeddings, new size = {args.resize_token_embeddings}")
  51. model.resize_token_embeddings(args.resize_token_embeddings)
  52. config.vocab_size = args.resize_token_embeddings
  53. tokenizer = transformers.AutoTokenizer.from_pretrained(
  54. args.model, use_auth_token=args.use_auth_token, revision=args.revision
  55. )
  56. os.makedirs(args.output_path, exist_ok=True)
  57. repo = Repository(args.output_path, clone_from=args.output_repo, use_auth_token=args.use_auth_token)
  58. repo.git_pull()
  59. transformer_blocks = model.h
  60. logger.info(
  61. f"Saving transformer blocks to {args.output_repo}@{args.block_branch_prefix}0"
  62. f" - {args.output_repo}@{args.block_branch_prefix}{len(transformer_blocks)}"
  63. )
  64. for i, block in enumerate(tqdm(transformer_blocks)):
  65. repo.git_checkout(args.client_branch, create_branch_ok=True)
  66. with repo.commit(
  67. commit_message=args.commit_message, branch=args.block_branch_prefix + str(i), track_large_files=True
  68. ):
  69. torch.save(block.state_dict(), "./pytorch_model.bin")
  70. logger.info(f"Saving client-side modules to {args.output_repo}@{args.client_branch}")
  71. repo.git_checkout(args.client_branch, create_branch_ok=True)
  72. with repo.commit(commit_message=args.commit_message, branch=args.client_branch, track_large_files=True):
  73. model.h = nn.ModuleList()
  74. model.save_pretrained(".")
  75. tokenizer.save_pretrained(".")
  76. config.save_pretrained(".")
  77. logger.info(f"Converted {args.model} and pushed to {args.output_repo}")