convert_model.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import argparse
  2. import os
  3. import psutil
  4. import torch.backends.quantized
  5. import transformers
  6. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  7. from huggingface_hub import Repository
  8. import torch.nn as nn
  9. from tqdm.auto import tqdm
  10. use_hivemind_log_handler("in_root_logger")
  11. logger = get_logger(__file__)
  12. DTYPE_MAP = dict(bfloat16=torch.bfloat16, float16=torch.float16, float32=torch.float32, auto="auto")
  13. if __name__ == "__main__":
  14. parser = argparse.ArgumentParser(description="Load bloom layers and convert to 8-bit using torch quantization.")
  15. parser.add_argument("--model", type=str, default="bigscience/bloom-6b3", help="Model name for from_pretrained")
  16. parser.add_argument("--revision", type=str, default=None, help="Optional commit id from HF hub")
  17. parser.add_argument("--torch_dtype", type=str, default="auto", help="Load initial model in this dtype")
  18. parser.add_argument("--output_path", type=str, default='./converted_model', help="Track output repo to this folder")
  19. parser.add_argument("--output_repo", type=str, default='bigscience/test-bloomd', help="Push to this HF hub repo")
  20. parser.add_argument("--base_branch", type=str, default='main', help="Use this branch as reference point")
  21. parser.add_argument("--client_branch", type=str, default='client', help="Save client version to this branch")
  22. parser.add_argument("--block_branch_prefix", type=str, default='block_', help="Save blocks to branches with this prefix")
  23. parser.add_argument("--commit_message", type=str, default='push-o-matic', help="Use this commit message for all parts")
  24. parser.add_argument("--use_auth_token", type=str, default=None, help="auth token for from_pretrained")
  25. args = parser.parse_args()
  26. free_ram_gb = psutil.virtual_memory().available / 2 ** 30
  27. if free_ram_gb < 400:
  28. logger.warning(f"ACHTUNG! converting bloom-176b will use up 350-400GB RAM, you have {free_ram_gb:.3f} free")
  29. assert args.torch_dtype in DTYPE_MAP, f"torch_dtype must be one of {list(DTYPE_MAP.keys())}"
  30. if os.path.exists(args.output_path) and (
  31. len(os.listdir(args.output_path)) != 0 or not os.path.isdir(args.output_path)
  32. ):
  33. raise FileExistsError(f"Output path {args.output_path} already exists and is not an empty directory")
  34. model = transformers.AutoModelForCausalLM.from_pretrained(
  35. args.model, use_auth_token=args.use_auth_token, revision=args.revision, torch_dtype=DTYPE_MAP[args.torch_dtype]
  36. )
  37. tokenizer = transformers.AutoTokenizer.from_pretrained(
  38. args.model, use_auth_token=args.use_auth_token, revision=args.revision
  39. )
  40. os.makedirs(args.output_path, exist_ok=True)
  41. repo = Repository(args.output_path, clone_from=args.output_repo, use_auth_token=args.use_auth_token)
  42. repo.git_pull()
  43. transformer_blocks = model.transformer.h
  44. for i, block in enumerate(tqdm(transformer_blocks)):
  45. repo.git_checkout(args.base_branch, create_branch_ok=True)
  46. with repo.commit(
  47. commit_message=args.commit_message, branch=args.block_branch_prefix + str(i), track_large_files=True
  48. ):
  49. torch.save(block.state_dict(), "./pytorch_model.bin")
  50. repo.git_checkout(args.base_branch, create_branch_ok=True)
  51. with repo.commit(commit_message=args.commit_message, branch=args.client_branch, track_large_files=True):
  52. model.transformer.h = nn.ModuleList()
  53. model.save_pretrained(".")
  54. logger.info(f"Converted {args.model} and saved to {args.output_repo}")