You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

hccl_tools.py 5.2 kB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """generate hccl config file script"""
  16. import os
  17. import sys
  18. import json
  19. import socket
  20. from argparse import ArgumentParser
  21. from typing import Dict, Any
  22. def parse_args():
  23. """
  24. parse args .
  25. Args:
  26. Returns:
  27. args.
  28. Examples:
  29. >>> parse_args()
  30. """
  31. parser = ArgumentParser(description="mindspore distributed training launch "
  32. "helper utility that will generate hccl"
  33. " config file")
  34. parser.add_argument("--device_num", type=str, default="[0,8)",
  35. help="The number of the Ascend accelerators used. please note that the Ascend accelerators"
  36. "used must be continuous, such [0,4) means to use four chips "
  37. "0,1,2,3; [0,1) means to use chip 0; The first four chips are"
  38. "a group, and the last four chips are a group. In addition to"
  39. "the [0,8) chips are allowed, other cross-group such as [3,6)"
  40. "are prohibited.")
  41. parser.add_argument("--visible_devices", type=str, default="0,1,2,3,4,5,6,7",
  42. help="will use the visible devices sequentially")
  43. parser.add_argument("--server_ip", type=str, default="",
  44. help="server ip")
  45. args = parser.parse_args()
  46. return args
  47. def get_host_ip():
  48. """
  49. get host ip
  50. """
  51. ip = None
  52. try:
  53. hostname = socket.gethostname()
  54. ip = socket.gethostbyname(hostname)
  55. except EOFError:
  56. pass
  57. return ip
  58. def main():
  59. print("start", __file__)
  60. args = parse_args()
  61. # visible_devices
  62. visible_devices = args.visible_devices.split(',')
  63. print('visible_devices:{}'.format(visible_devices))
  64. # server_id
  65. ip = get_host_ip()
  66. if args.server_ip:
  67. server_id = args.server_ip
  68. elif ip:
  69. server_id = ip
  70. else:
  71. raise ValueError("please input server ip!")
  72. print('server_id:{}'.format(server_id))
  73. # device_num
  74. first_num = int(args.device_num[1])
  75. last_num = int(args.device_num[3])
  76. if first_num < 0 or last_num > 8:
  77. raise ValueError("device num {} must be in range [0,8] !".format(args.device_num))
  78. if first_num > last_num:
  79. raise ValueError("First num {} of device num {} must less than last num {} !".format(first_num, args.device_num,
  80. last_num))
  81. if first_num < 4:
  82. if last_num > 4:
  83. if first_num == 0 and last_num == 8:
  84. pass
  85. else:
  86. raise ValueError("device num {} must be in the same group of [0,4] or [4,8] !".format(args.device_num))
  87. device_num_list = list(range(first_num, last_num))
  88. print("device_num_list:", device_num_list)
  89. assert len(visible_devices) >= len(device_num_list)
  90. # construct hccn_table
  91. device_ips: Dict[Any, Any] = {}
  92. with open('/etc/hccn.conf', 'r') as fin:
  93. for hccn_item in fin.readlines():
  94. if hccn_item.strip().startswith('address_'):
  95. device_id, device_ip = hccn_item.split('=')
  96. device_id = device_id.split('_')[1]
  97. device_ips[device_id] = device_ip.strip()
  98. hccn_table = {'version': '1.0',
  99. 'server_count': '1',
  100. 'server_list': []}
  101. device_list = []
  102. rank_id = 0
  103. for instance_id in device_num_list:
  104. device_id = visible_devices[instance_id]
  105. device_ip = device_ips[device_id]
  106. device = {'device_id': device_id,
  107. 'device_ip': device_ip,
  108. 'rank_id': str(rank_id)}
  109. print('rank_id:{}, device_id:{}, device_ip:{}'.format(rank_id, device_id, device_ip))
  110. rank_id += 1
  111. device_list.append(device)
  112. hccn_table['server_list'].append({
  113. 'server_id': server_id,
  114. 'device': device_list,
  115. 'host_nic_ip': 'reserve'
  116. })
  117. hccn_table['status'] = 'completed'
  118. # save hccn_table to file
  119. table_path = os.getcwd()
  120. table_fn = os.path.join(table_path,
  121. 'hccl_{}p_{}_{}.json'.format(len(device_num_list), "".join(map(str, device_num_list)),
  122. server_id))
  123. with open(table_fn, 'w') as table_fp:
  124. json.dump(hccn_table, table_fp, indent=4)
  125. sys.stdout.flush()
  126. print("Completed: hccl file was save in :", table_fn)
  127. if __name__ == "__main__":
  128. main()