run_server.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  1. import configargparse
  2. from hivemind.proto.runtime_pb2 import CompressionType
  3. from hivemind.utils.limits import increase_file_limit
  4. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  5. from src.server.server import Server
  6. use_hivemind_log_handler("in_root_logger")
  7. logger = get_logger(__file__)
  8. import re
  9. def parse_size_as_bytes(size: str) -> int:
  10. """parse human-readable data size e.g. 1.5GB, based on https://stackoverflow.com/a/42865957/2002471"""
  11. units = {"B": 1, "KB": 2**10, "MB": 2**20, "GB": 2**30, "TB": 2**40, "PB": 2**50}
  12. size = size.strip().upper().replace("IB", "B")
  13. if not size.endswith("B"):
  14. size += "B"
  15. if not re.match(r" ", size):
  16. size = re.sub(r"([KMGT]?B)", r" \1", size)
  17. number, unit = [string.strip() for string in size.split()]
  18. return int(float(number) * units[unit])
  19. def main():
  20. # fmt:off
  21. parser = configargparse.ArgParser(default_config_files=["config.yml"])
  22. parser.add('-c', '--config', required=False, is_config_file=True, help='config file path')
  23. parser.add_argument('--converted_model_name_or_path', type=str, default='bigscience/test-bloomd-6b3',
  24. help="path or name of a pretrained model, converted with cli/convert_model.py (see README.md)")
  25. parser.add_argument('--num_blocks', type=int, default=None, help="The number of blocks to serve")
  26. parser.add_argument('--block_indices', type=str, default=None, help="Specific block indices to serve")
  27. parser.add_argument('--prefix', type=str, default=None, help="Announce all blocks with this prefix. By default,"
  28. "use the same name as in the converted model.")
  29. parser.add_argument('--host_maddrs', nargs='+', default=['/ip4/0.0.0.0/tcp/0'], required=False,
  30. help='Multiaddrs to listen for external connections from other p2p instances; default: all IPv4 and TCP: /ip4/0.0.0.0/tcp/0')
  31. parser.add_argument('--announce_maddrs', nargs='+', default=None, required=False,
  32. help='Visible multiaddrs the host announces for external connections from other p2p instances')
  33. parser.add_argument('--compression', type=str, default='NONE', required=False, help='Tensor compression communication')
  34. parser.add_argument('--num_handlers', type=int, default=8, required=False,
  35. help='server will use this many processes to handle incoming requests')
  36. parser.add_argument('--min_batch_size', type=int, default=1,
  37. help='Minimum required batch size for all expert operations')
  38. parser.add_argument('--max_batch_size', type=int, default=16384,
  39. help='The total number of tokens in the same batch will not exceed this value')
  40. parser.add_argument('--inference_max_length', type=int, default=None,
  41. help='Maximum total sequence length permitted per inference, defaults to max_batch_size tokens')
  42. parser.add_argument('--cache_dir', type=str, default=None,
  43. help='Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.')
  44. parser.add_argument('--device', type=str, default=None, required=False,
  45. help='all experts will use this device in torch notation; default: cuda if available else cpu')
  46. parser.add_argument("--torch_dtype", type=str, default="auto",
  47. help="Use this dtype to store block weights and do computations. "
  48. "By default, respect the dtypes in the pre-trained state dict.")
  49. parser.add_argument('--attn_cache_size', type=str, default=None,
  50. help='The size of GPU memory allocated for storing past attention keys/values between inference'
  51. ' steps; examples: 500MB or 1.2GB or 1073741824 (bytes); assumes 1KB = 1kB = 1024 bytes')
  52. parser.add_argument('--revision', type=str, default='main',
  53. help="The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a git-based system for storing models"
  54. "and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.")
  55. parser.add_argument('--throughput',
  56. type=lambda value: value if value in ['auto', 'eval'] else float(value),
  57. default='auto',
  58. help='Expected server throughput (a float measured in RPS). '
  59. 'If set to "auto" (default), the script evaluates network and compute throughput '
  60. 'on the first run and uses these estimates for future runs. '
  61. 'If set to "eval", the script re-evaluates the throughput and overrides the cache.')
  62. parser.add_argument('--update_period', type=float, required=False, default=30,
  63. help='Server will report experts to DHT once in this many seconds')
  64. parser.add_argument('--expiration', type=float, required=False, default=None,
  65. help='DHT entries will expire after this many seconds')
  66. parser.add_argument('--initial_peers', type=str, nargs='*', required=False, default=[],
  67. help='multiaddrs of one or more active DHT peers (if you want to join an existing DHT)')
  68. parser.add_argument('--increase_file_limit', action='store_true',
  69. help='On *nix, this will increase the max number of processes '
  70. 'a server can spawn before hitting "Too many open files"; Use at your own risk.')
  71. parser.add_argument('--stats_report_interval', type=int, required=False,
  72. help='Interval between two reports of batch processing performance statistics')
  73. parser.add_argument('--custom_module_path', type=str, required=False,
  74. help='Path of a file with custom nn.modules, wrapped into special decorator')
  75. parser.add_argument('--identity_path', type=str, required=False, help='Path to identity file to be used in P2P')
  76. parser.add_argument("--use_auth_token", type=str, default=None, help="auth token for from_pretrained")
  77. parser.add_argument('--load_in_8bit', action='store_true', help='Convert the loaded model into mixed-8bit quantized model.')
  78. # fmt:on
  79. args = vars(parser.parse_args())
  80. args.pop("config", None)
  81. if args.pop("increase_file_limit"):
  82. increase_file_limit()
  83. compression_type = args.pop("compression")
  84. compression = getattr(CompressionType, compression_type)
  85. attn_cache_size = args.pop("attn_cache_size")
  86. if attn_cache_size is not None:
  87. attn_cache_size = parse_size_as_bytes(attn_cache_size)
  88. assert isinstance(
  89. attn_cache_size, (int, type(None))
  90. ), "unrecognized value for attention_cache_bytes, examples: 1.5GB or 1500MB or 1572864000 (bytes)"
  91. use_auth_token = args.pop("use_auth_token")
  92. args["use_auth_token"] = True if use_auth_token in ("True", "true", "") else use_auth_token
  93. server = Server.create(**args, start=True, compression=compression, attn_cache_size=attn_cache_size)
  94. try:
  95. server.join()
  96. except KeyboardInterrupt:
  97. logger.info("Caught KeyboardInterrupt, shutting down")
  98. finally:
  99. server.shutdown()
  100. if __name__ == "__main__":
  101. main()