run_server.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import argparse
  2. import configargparse
  3. from hivemind.proto.runtime_pb2 import CompressionType
  4. from hivemind.utils.limits import increase_file_limit
  5. from hivemind.utils.logging import get_logger, use_hivemind_log_handler
  6. from humanfriendly import parse_size
  7. from src.server.server import Server
  8. use_hivemind_log_handler("in_root_logger")
  9. logger = get_logger(__file__)
  10. def main():
  11. # fmt:off
  12. parser = configargparse.ArgParser(default_config_files=["config.yml"],
  13. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  14. parser.add('-c', '--config', required=False, is_config_file=True, help='config file path')
  15. group = parser.add_mutually_exclusive_group(required=True)
  16. group.add_argument('--converted_model_name_or_path', type=str, default=None,
  17. help="path or name of a pretrained model, converted with cli/convert_model.py")
  18. group.add_argument('model', nargs='?', type=str, help="same as --converted_model_name_or_path")
  19. parser.add_argument('--num_blocks', type=int, default=None, help="The number of blocks to serve")
  20. parser.add_argument('--block_indices', type=str, default=None, help="Specific block indices to serve")
  21. parser.add_argument('--prefix', type=str, default=None, help="Announce all blocks with this prefix. By default,"
  22. "use the same name as in the converted model.")
  23. parser.add_argument('--host_maddrs', nargs='+', default=['/ip4/0.0.0.0/tcp/0'], required=False,
  24. help='Multiaddrs to listen for external connections from other p2p instances; default: all IPv4 and TCP: /ip4/0.0.0.0/tcp/0')
  25. parser.add_argument('--announce_maddrs', nargs='+', default=None, required=False,
  26. help='Visible multiaddrs the host announces for external connections from other p2p instances')
  27. parser.add_argument('--compression', type=str, default='NONE', required=False, help='Tensor compression communication')
  28. parser.add_argument('--num_handlers', type=int, default=8, required=False,
  29. help='server will use this many processes to handle incoming requests')
  30. parser.add_argument('--min_batch_size', type=int, default=1,
  31. help='Minimum required batch size for all operations (in total tokens)')
  32. parser.add_argument('--max_batch_size', type=int, default=16384,
  33. help='The total number of tokens in the same batch will not exceed this value')
  34. parser.add_argument('--prefetch_batches', type=int, default=1, required=False,
  35. help='Pre-form this many subsequent batches while GPU is processing the current one')
  36. parser.add_argument('--sender_threads', type=int, default=1, required=False,
  37. help='Use this many threads to pass results/exceptions from Runtime to Pools')
  38. parser.add_argument('--inference_max_length', type=int, default=16384,
  39. help='Maximum total sequence length permitted per inference, defaults to 16384 tokens')
  40. parser.add_argument('--cache_dir', type=str, default=None,
  41. help='Path to a directory in which a downloaded pretrained model configuration should be cached if the standard cache should not be used.')
  42. parser.add_argument('--device', type=str, default=None, required=False,
  43. help='all blocks will use this device in torch notation; default: cuda if available else cpu')
  44. parser.add_argument("--torch_dtype", type=str, default="auto",
  45. help="Use this dtype to store block weights and do computations. "
  46. "By default, respect the dtypes in the pre-trained state dict.")
  47. parser.add_argument('--attn_cache_size', type=str, default=None,
  48. help='The size of GPU memory allocated for storing past attention keys/values between inference'
  49. ' steps; examples: 500MB or 1.2GB or 1073741824 (bytes); be warned: 1KB != 1KiB')
  50. parser.add_argument('--revision', type=str, default='main',
  51. 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"
  52. "and other artifacts on huggingface.co, so `revision` can be any identifier allowed by git.")
  53. parser.add_argument('--throughput',
  54. type=lambda value: value if value in ['auto', 'eval'] else float(value),
  55. default='auto',
  56. help='Expected server throughput (a float measured in RPS). '
  57. 'If set to "auto" (default), the script evaluates network and compute throughput '
  58. 'on the first run and uses these estimates for future runs. '
  59. 'If set to "eval", the script re-evaluates the throughput and overrides the cache.')
  60. parser.add_argument('--update_period', type=float, required=False, default=30,
  61. help='Server will report blocks to DHT once in this many seconds')
  62. parser.add_argument('--expiration', type=float, required=False, default=None,
  63. help='DHT entries will expire after this many seconds')
  64. parser.add_argument('--initial_peers', type=str, nargs='*', required=False, default=[],
  65. help='multiaddrs of one or more active DHT peers (if you want to join an existing DHT)')
  66. parser.add_argument('--increase_file_limit', action='store_true',
  67. help='On *nix, this will increase the max number of processes '
  68. 'a server can spawn before hitting "Too many open files"; Use at your own risk.')
  69. parser.add_argument('--stats_report_interval', type=int, required=False,
  70. help='Interval between two reports of batch processing performance statistics')
  71. parser.add_argument('--custom_module_path', type=str, required=False,
  72. help='Path of a file with custom nn.modules, wrapped into special decorator')
  73. parser.add_argument('--identity_path', type=str, required=False, help='Path to identity file to be used in P2P')
  74. parser.add_argument("--balance_quality", type=float, default=0.75,
  75. help="Rebalance the swarm if its throughput is worse than this share of the optimal "
  76. "throughput. Use 0.0 to disable rebalancing, values > 1.0 to force rebalancing "
  77. "on each check for debugging purposes.")
  78. parser.add_argument("--mean_balance_check_period", type=float, default=60,
  79. help="Check the swarm's balance every N seconds (and rebalance it if necessary)")
  80. parser.add_argument("--use_auth_token", type=str, default=None, help="auth token for from_pretrained")
  81. parser.add_argument('--load_in_8bit', action='store_true', help='Convert the loaded model into mixed-8bit quantized model.')
  82. # fmt:on
  83. args = vars(parser.parse_args())
  84. args.pop("config", None)
  85. args["converted_model_name_or_path"] = args.pop("model") or args["converted_model_name_or_path"]
  86. if args.pop("increase_file_limit"):
  87. increase_file_limit()
  88. compression_type = args.pop("compression").upper()
  89. compression = getattr(CompressionType, compression_type)
  90. attn_cache_size = args.pop("attn_cache_size")
  91. if attn_cache_size is not None:
  92. attn_cache_size = parse_size(attn_cache_size)
  93. assert isinstance(
  94. attn_cache_size, (int, type(None))
  95. ), "unrecognized value for attention_cache_bytes, examples: 1.5GB or 1500MB or 1572864000 (bytes)"
  96. use_auth_token = args.pop("use_auth_token")
  97. args["use_auth_token"] = True if use_auth_token in ("True", "true", "") else use_auth_token
  98. server = Server(**args, compression=compression, attn_cache_size=attn_cache_size, start=True)
  99. try:
  100. server.join()
  101. except KeyboardInterrupt:
  102. logger.info("Caught KeyboardInterrupt, shutting down")
  103. finally:
  104. server.shutdown()
  105. if __name__ == "__main__":
  106. main()