run_cpu.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. """
  2. This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable Processors with optimal configurations.
  3. Single instance inference, multi-instance inference are enabled.
  4. Note: term "instance" here doesn't refer to a cloud instance. This script is executed as a single process. It invokes
  5. multiple "instances" which are formed from multiple threads for each. "instance" is kind of group of threads in this
  6. context.
  7. Illustrated as below:
  8. ::
  9. +-----------------------------+----------------------+-------+
  10. | process | thread | core |
  11. +=============================+======================+=======+
  12. | torch.backends.xeon.run_cpu | instance 0: thread 0 | 0 |
  13. | | thread 1 | 1 |
  14. | +----------------------+-------+
  15. | | instance 1: thread 0 | 2 |
  16. | | thread 1 | 3 |
  17. | +----------------------+-------+
  18. | | ... | ... |
  19. | +----------------------+-------+
  20. | | instance N: thread 0 | M |
  21. | | thread 1 | M+1 |
  22. +-----------------------------+----------------------+-------+
  23. To get the peak performance on Intel(R) Xeon(R) Scalable Processors, the script optimizes the configuration of thread and memory
  24. management. For thread management, the script configures thread affinity and the preload of Intel OMP library.
  25. For memory management, it configures NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc).
  26. Environment variables that will be set by this script:
  27. +------------------+-------------------------------------------------------------------------------------------------+
  28. | Environ Variable | Value |
  29. +==================+=================================================================================================+
  30. | LD_PRELOAD | Depending on knobs you set, <lib>/libiomp5.so, <lib>/libjemalloc.so, <lib>/libtcmalloc.so might |
  31. | | be appended to LD_PRELOAD. |
  32. +------------------+-------------------------------------------------------------------------------------------------+
  33. | KMP_AFFINITY | If libiomp5.so is preloaded, KMP_AFFINITY could be set to "granularity=fine,compact,1,0". |
  34. +------------------+-------------------------------------------------------------------------------------------------+
  35. | KMP_BLOCKTIME | If libiomp5.so is preloaded, KMP_BLOCKTIME is set to "1". |
  36. +------------------+-------------------------------------------------------------------------------------------------+
  37. | OMP_NUM_THREADS | value of ncores_per_instance |
  38. +------------------+-------------------------------------------------------------------------------------------------+
  39. | MALLOC_CONF | If libjemalloc.so is preloaded, MALLOC_CONF will be set to |
  40. | | "oversize_threshold:1,background_thread:true,metadata_thp:auto". |
  41. +------------------+-------------------------------------------------------------------------------------------------+
  42. *Note*: This script respects environment variables set preliminarily. I.e. If you set the environment variables
  43. mentioned above before running the script, the script will not overwrite the values in the script.
  44. How to use this module:
  45. ~~~~~~~~~~~~~~~~~~~~~~~
  46. Single instance inference
  47. -------------------------
  48. 1. Run single-instance inference on a single node with all CPU nodes.
  49. ::
  50. python -m torch.backends.xeon.run_cpu --throughput-mode script.py args
  51. 2. Run single-instance inference on a single CPU node.
  52. ::
  53. python -m torch.backends.xeon.run_cpu --node-id 1 script.py args
  54. Multi-instance inference
  55. ------------------------
  56. 1. Multi-instance
  57. By default this tool runs one process per node. If you want to set the instance numbers and core per instance,
  58. --ninstances and --ncores-per-instance should be set.
  59. ::
  60. python -m torch.backends.xeon.run_cpu -- python_script args
  61. eg: on an Intel(R) Xeon(R) Scalable Processor with 14 instance, 4 cores per instance
  62. ::
  63. python -m torch.backends.xeon.run_cpu --ninstances 14 --ncores-per-instance 4 python_script args
  64. 2. Run single-instance inference among multiple instances.
  65. By default, runs all ninstances. If you want to independently run a single instance among ninstances, specify rank.
  66. eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 0-27)
  67. ::
  68. python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 0 python_script args
  69. eg: run 1st instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 28-55)
  70. ::
  71. python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 1 python_script args
  72. eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance, 2 cores per instance,
  73. first four cores (i.e., numactl -C 0-1)
  74. ::
  75. python -m torch.backends.xeon.run_cpu --core-list "0, 1, 2, 3" --ninstances 2 --ncores-per-instance 2
  76. --rank 0 python_script args
  77. 3. To look up what optional arguments this module offers:
  78. ::
  79. python -m torch.backends.xeon.run_cpu --help
  80. Memory allocator
  81. ----------------
  82. "--enable-tcmalloc" and "--enable-jemalloc" can be used to enable different memory allcator.
  83. """
  84. import sys
  85. import platform
  86. import subprocess
  87. import os
  88. from os.path import expanduser
  89. import re
  90. import glob
  91. from argparse import ArgumentParser, REMAINDER
  92. from argparse import RawTextHelpFormatter
  93. import logging
  94. from torch.distributed.elastic.multiprocessing import Std, start_processes
  95. from typing import List, Dict
  96. format_str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
  97. logging.basicConfig(level=logging.INFO, format=format_str)
  98. logger = logging.getLogger(__name__)
  99. class _CPUinfo():
  100. """
  101. Get CPU inforamation, such as cores list and NUMA information.
  102. """
  103. def __init__(self, test_input=""):
  104. self.cpuinfo = []
  105. if platform.system() in ["Windows", "Darwin"]:
  106. raise RuntimeError(f"{platform.system()} is not supported!!!")
  107. elif platform.system() == "Linux":
  108. # Sample output of: `lscpu --parse=CPU,Core,Socket,Node`
  109. #
  110. # # The following is the parsable format, which can be fed to other
  111. # # programs. Each different item in every column has an unique ID
  112. # # starting from zero.
  113. # # CPU,Core,Socket,Node
  114. # 0,0,0,0
  115. # 1,1,0,0
  116. # ...
  117. if test_input == "":
  118. lscpu_cmd = ["lscpu", "--parse=CPU,Core,Socket,Node"]
  119. lscpu_info = subprocess.check_output(lscpu_cmd, universal_newlines=True).split("\n")
  120. else:
  121. lscpu_info = test_input.split("\n")
  122. # Get information about cpu, core, socket and node
  123. for line in lscpu_info:
  124. pattern = r"^([\d]+,[\d]+,[\d]+,[\d]?)"
  125. regex_out = re.search(pattern, line)
  126. if regex_out:
  127. self.cpuinfo.append(regex_out.group(1).strip().split(","))
  128. # physical cores := core column in lscpu output
  129. # logical cores := cPU column in lscpu output
  130. self.node_nums = int(max([line[3] for line in self.cpuinfo])) + 1
  131. self.node_physical_cores: List[List[int]] = [] # node_id is index
  132. self.node_logical_cores: List[List[int]] = [] # node_id is index
  133. self.physical_core_node_map = {} # phyical core to numa node id
  134. self.logical_core_node_map = {} # logical core to numa node id
  135. for node_id in range(self.node_nums):
  136. cur_node_physical_core = []
  137. cur_node_logical_core = []
  138. for cpuinfo in self.cpuinfo:
  139. nid = cpuinfo[3] if cpuinfo[3] != "" else "0"
  140. if node_id == int(nid):
  141. if int(cpuinfo[1]) not in cur_node_physical_core:
  142. cur_node_physical_core.append(int(cpuinfo[1]))
  143. self.physical_core_node_map[int(cpuinfo[1])] = int(node_id)
  144. cur_node_logical_core.append(int(cpuinfo[0]))
  145. self.logical_core_node_map[int(cpuinfo[0])] = int(node_id)
  146. self.node_physical_cores.append(cur_node_physical_core)
  147. self.node_logical_cores.append(cur_node_logical_core)
  148. def _physical_core_nums(self):
  149. return len(self.node_physical_cores) * len(self.node_physical_cores[0])
  150. def _logical_core_nums(self):
  151. return len(self.node_logical_cores) * len(self.node_logical_cores[0])
  152. def get_node_physical_cores(self, node_id):
  153. if node_id < 0 or node_id > self.node_nums - 1:
  154. raise ValueError(f"Invalid node id: {node_id}. Valid node ids: {list(range(len(self.node_physical_cores)))}")
  155. return self.node_physical_cores[node_id]
  156. def get_node_logical_cores(self, node_id):
  157. if node_id < 0 or node_id > self.node_nums - 1:
  158. raise ValueError(f"Invalid node id: {node_id}. Valid node ids: {list(range(len(self.node_physical_cores)))}")
  159. return self.node_logical_cores[node_id]
  160. def get_all_physical_cores(self):
  161. all_cores = []
  162. for cores in self.node_physical_cores:
  163. all_cores.extend(cores)
  164. return all_cores
  165. def get_all_logical_cores(self):
  166. all_cores = []
  167. for cores in self.node_logical_cores:
  168. all_cores.extend(cores)
  169. return all_cores
  170. def numa_aware_check(self, core_list):
  171. """
  172. Check whether all cores in core_list are in the same NUMA node. cross NUMA will reduce perforamnce.
  173. We strongly advice to not use cores on different nodes.
  174. """
  175. cores_numa_map = self.logical_core_node_map
  176. numa_ids = []
  177. for core in core_list:
  178. numa_id = cores_numa_map[core]
  179. if numa_id not in numa_ids:
  180. numa_ids.append(numa_id)
  181. if len(numa_ids) > 1:
  182. logger.warning(f"Numa Aware: cores:{str(core_list)} on different NUMA nodes:{str(numa_ids)}. To avoid \
  183. this behavior, please use --ncores-per-instance knob to make sure number of cores is divisible by --ncores-per-\
  184. instance. Alternatively, please use --skip-cross-node-cores knob.")
  185. if len(numa_ids) == 0:
  186. raise RuntimeError("invalid number of NUMA nodes; please make sure numa_ids >= 1")
  187. return numa_ids
  188. class _Launcher():
  189. r"""
  190. Class for launcher
  191. """
  192. msg_lib_notfound = f"Unable to find the {{0}} library file lib{{1}}.so in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib \
  193. or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or \
  194. {expanduser('~')}/.local/lib/ so the LD_PRELOAD environment variable will not be set."
  195. def __init__(self):
  196. self.cpuinfo = _CPUinfo()
  197. def add_lib_preload(self, lib_type):
  198. """
  199. Enale TCMalloc/JeMalloc/intel OpenMP
  200. """
  201. library_paths = []
  202. if "CONDA_PREFIX" in os.environ:
  203. library_paths.append(f"{os.environ['CONDA_PREFIX']}/lib")
  204. if "VIRTUAL_ENV" in os.environ:
  205. library_paths.append(f"{os.environ['VIRTUAL_ENV']}/lib")
  206. library_paths += [f"{expanduser('~')}/.local/lib", "/usr/local/lib",
  207. "/usr/local/lib64", "/usr/lib", "/usr/lib64"]
  208. lib_find = False
  209. lib_set = False
  210. for item in os.getenv("LD_PRELOAD", "").split(":"):
  211. if item.endswith(f"lib{lib_type}.so"):
  212. lib_set = True
  213. break
  214. if not lib_set:
  215. for lib_path in library_paths:
  216. library_file = os.path.join(lib_path, f"lib{lib_type}.so")
  217. matches = glob.glob(library_file)
  218. if len(matches) > 0:
  219. ld_preloads = [f"{matches[0]}", os.getenv("LD_PRELOAD", "")]
  220. os.environ["LD_PRELOAD"] = os.pathsep.join([p.strip(os.pathsep) for p in ld_preloads if p])
  221. lib_find = True
  222. break
  223. return lib_set or lib_find
  224. def set_memory_allocator(self, enable_tcmalloc=True, enable_jemalloc=False, use_default_allocator=False):
  225. """
  226. Enable TCMalloc/JeMalloc with LD_PRELOAD and set configuration for JeMalloc.
  227. By default, PTMalloc will be used for PyTorch, but TCMalloc and JeMalloc can get better
  228. memory resue and reduce page fault to improve performance.
  229. """
  230. if enable_tcmalloc and enable_jemalloc:
  231. raise RuntimeError("Unable to enable TCMalloc and JEMalloc at the same time.")
  232. if enable_tcmalloc:
  233. find_tc = self.add_lib_preload(lib_type="tcmalloc")
  234. if not find_tc:
  235. msg = f"{self.msg_lib_notfound} you can use \"conda install -c conda-forge gperftools\" to install {{0}}"
  236. logger.warning(msg.format("TCmalloc", "tcmalloc"))
  237. else:
  238. logger.info("Use TCMalloc memory allocator")
  239. elif enable_jemalloc:
  240. find_je = self.add_lib_preload(lib_type="jemalloc")
  241. if not find_je:
  242. msg = f"{self.msg_lib_notfound} you can use \"conda install -c conda-forge jemalloc\" to install {{0}}"
  243. logger.warning(msg.format("Jemalloc", "jemalloc"))
  244. else:
  245. logger.info("Use JeMalloc memory allocator")
  246. self.set_env("MALLOC_CONF", "oversize_threshold:1,background_thread:true,metadata_thp:auto")
  247. elif use_default_allocator:
  248. pass
  249. else:
  250. find_tc = self.add_lib_preload(lib_type="tcmalloc")
  251. if find_tc:
  252. logger.info("Use TCMalloc memory allocator")
  253. return
  254. find_je = self.add_lib_preload(lib_type="jemalloc")
  255. if find_je:
  256. logger.info("Use JeMalloc memory allocator")
  257. return
  258. logger.warning(f"""Neither TCMalloc nor JeMalloc is found in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib
  259. or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or
  260. {expanduser("~")}/.local/lib/ so the LD_PRELOAD environment variable will not be set.
  261. This may drop the performance""")
  262. def log_env_var(self, env_var_name=""):
  263. if env_var_name in os.environ:
  264. logger.info(f"{env_var_name}={os.environ[env_var_name]}")
  265. def set_env(self, env_name, env_value):
  266. if not env_value:
  267. logger.warning(f"{env_name} is None")
  268. if env_name not in os.environ:
  269. os.environ[env_name] = env_value
  270. elif os.environ[env_name] != env_value:
  271. logger.warning(f"Overriding value with the one set in environment variable: {env_name}. \
  272. Value applied: {os.environ[env_name]}. Value ignored: {env_value}")
  273. self.log_env_var(env_name)
  274. # set_kmp_affinity is used to control whether to set KMP_AFFINITY or not.
  275. # In scenario that use all cores on all nodes, including logical cores, setting KMP_AFFINITY disables logical cores.
  276. # In this case, KMP_AFFINITY should not be set.
  277. def set_multi_thread_and_allocator(self, ncores_per_instance,
  278. disable_iomp=False,
  279. set_kmp_affinity=True,
  280. enable_tcmalloc=True,
  281. enable_jemalloc=False,
  282. use_default_allocator=False):
  283. """
  284. Set multi-thread configuration and enable Intel openMP and TCMalloc/JeMalloc.
  285. By default, GNU openMP and PTMalloc are used in PyTorch. but Intel openMP and TCMalloc/JeMalloc are better alternatives
  286. to get performance benifit.
  287. """
  288. self.set_memory_allocator(enable_tcmalloc, enable_jemalloc, use_default_allocator)
  289. self.set_env("OMP_NUM_THREADS", str(ncores_per_instance))
  290. if not disable_iomp:
  291. find_iomp = self.add_lib_preload(lib_type="iomp5")
  292. if not find_iomp:
  293. msg = f"{self.msg_lib_notfound} you can use \"conda install mkl\" to install {{0}}"
  294. logger.warning(msg.format("iomp", "iomp5"))
  295. else:
  296. logger.info("Using Intel OpenMP")
  297. if set_kmp_affinity:
  298. self.set_env("KMP_AFFINITY", "granularity=fine,compact,1,0")
  299. self.set_env("KMP_BLOCKTIME", "1")
  300. self.log_env_var("LD_PRELOAD")
  301. r"""
  302. Launcher for single instance and multi-instance
  303. """
  304. def launch(self, args):
  305. cores = []
  306. set_kmp_affinity = True
  307. if args.core_list: # user specify what cores will be used by params
  308. cores = [int(x) for x in args.core_list.split(",")]
  309. if args.ncores_per_instance == -1:
  310. raise RuntimeError("please specify the \"--ncores-per-instance\" if you have pass the --core-list params")
  311. elif args.ninstances > 1 and args.ncores_per_instance * args.ninstances < len(cores):
  312. logger.warning(f"only first {args.ncores_per_instance * args.ninstances} cores will be used, \
  313. but you specify {len(cores)} cores in core_list")
  314. else:
  315. args.ninstances = len(cores) // args.ncores_per_instance
  316. else:
  317. if args.use_logical_core:
  318. if args.node_id != -1:
  319. cores = self.cpuinfo.get_node_logical_cores(args.node_id)
  320. else:
  321. cores = self.cpuinfo.get_all_logical_cores()
  322. # When using all cores on all nodes, including logical cores,
  323. # setting KMP_AFFINITY disables logical cores. Thus, KMP_AFFINITY should not be set.
  324. set_kmp_affinity = False
  325. else:
  326. if args.node_id != -1:
  327. cores = self.cpuinfo.get_node_physical_cores(args.node_id)
  328. else:
  329. cores = self.cpuinfo.get_all_physical_cores()
  330. if not args.multi_instance and args.ninstances == -1 and args.ncores_per_instance == -1:
  331. args.ninstances = 1
  332. args.ncores_per_instance = len(cores)
  333. elif args.multi_instance and args.ninstances == -1 and args.ncores_per_instance == -1:
  334. args.throughput_mode = True
  335. elif args.ncores_per_instance == -1 and args.ninstances != -1:
  336. if args.ninstances > len(cores):
  337. raise RuntimeError(f"there are {len(cores)} total cores but you specify {args.ninstances} ninstances; \
  338. please make sure ninstances <= total_cores)")
  339. else:
  340. args.ncores_per_instance = len(cores) // args.ninstances
  341. elif args.ncores_per_instance != -1 and args.ninstances == -1:
  342. if not args.skip_cross_node_cores:
  343. args.ninstances = len(cores) // args.ncores_per_instance
  344. else:
  345. ncore_per_node = len(self.cpuinfo.node_physical_cores[0])
  346. num_leftover_cores = ncore_per_node % args.ncores_per_instance
  347. if args.ncores_per_instance > ncore_per_node:
  348. # too many ncores_per_instance to skip cross-node cores
  349. logger.warning("there are {} core(s) per socket, but you specify {} ncores_per_instance and \
  350. skip_cross_node_cores. Please make sure --ncores-per-instance < core(s) per \
  351. socket".format(ncore_per_node, args.ncores_per_instance))
  352. exit(-1)
  353. elif num_leftover_cores == 0:
  354. # aren't any cross-node cores
  355. logger.info('--skip-cross-node-cores is set, but there are no cross-node cores.')
  356. args.ninstances = len(cores) // args.ncores_per_instance
  357. else:
  358. # skip cross-node cores
  359. if args.ninstances != -1:
  360. logger.warning('--skip-cross-node-cores is exclusive to --ninstances. --ninstances \
  361. won\'t take effect even if it is set explicitly.')
  362. i = 1
  363. leftover_cores = set()
  364. while ncore_per_node * i <= len(cores):
  365. leftover_cores.update(cores[ncore_per_node * i - num_leftover_cores : ncore_per_node * i])
  366. i += 1
  367. cores = list(set(cores) - leftover_cores)
  368. assert len(cores) % args.ncores_per_instance == 0
  369. args.ninstances = len(cores) // args.ncores_per_instance
  370. else:
  371. if args.ninstances * args.ncores_per_instance > len(cores):
  372. raise RuntimeError("Please make sure ninstances * ncores_per_instance <= total_cores")
  373. if args.latency_mode:
  374. logger.warning("--latency-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and \
  375. --use-logical-core. They won't take effect even they are set explicitly.")
  376. args.ncores_per_instance = 4
  377. cores = self.cpuinfo.get_all_physical_cores()
  378. args.ninstances = len(cores) // args.ncores_per_instance
  379. if args.throughput_mode:
  380. logger.warning("--throughput-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and \
  381. --use-logical-core. They won't take effect even they are set explicitly.")
  382. args.ninstances = self.cpuinfo.node_nums
  383. cores = self.cpuinfo.get_all_physical_cores()
  384. args.ncores_per_instance = len(cores) // args.ninstances
  385. if args.ninstances > 1 and args.rank != -1:
  386. logger.info(f"assigning {args.ncores_per_instance} cores for instance {args.rank}")
  387. self.set_multi_thread_and_allocator(args.ncores_per_instance,
  388. args.disable_iomp,
  389. set_kmp_affinity,
  390. args.enable_tcmalloc,
  391. args.enable_jemalloc,
  392. args.use_default_allocator)
  393. entrypoint = ""
  394. launch_args = {}
  395. launch_envs: Dict[int, Dict] = {}
  396. launch_tee = {}
  397. for i in range(args.ninstances):
  398. cmd = []
  399. cur_process_cores = ""
  400. if not args.disable_numactl:
  401. cmd = ["numactl"]
  402. cores = sorted(cores)
  403. if args.rank == -1: # sequentially assign ncores_per_instance to ninstances
  404. core_list = cores[i * args.ncores_per_instance : (i + 1) * args.ncores_per_instance]
  405. else: # assign ncores_per_instance from rank
  406. core_list = cores[args.rank * args.ncores_per_instance
  407. : (args.rank + 1) * args.ncores_per_instance]
  408. core_ranges: List[Dict] = []
  409. for core in core_list:
  410. if len(core_ranges) == 0:
  411. range_elem = {"start": core, "end": core}
  412. core_ranges.append(range_elem)
  413. else:
  414. if core - core_ranges[-1]["end"] == 1:
  415. core_ranges[-1]["end"] = core
  416. else:
  417. range_elem = {"start": core, "end": core}
  418. core_ranges.append(range_elem)
  419. for r in core_ranges:
  420. cur_process_cores = f"{cur_process_cores}{r['start']}-{r['end']},"
  421. cur_process_cores = cur_process_cores[:-1]
  422. numa_params = f"-C {cur_process_cores} "
  423. numa_ids = ",".join([str(numa_id) for numa_id in self.cpuinfo.numa_aware_check(core_list)])
  424. numa_params += f"-m {numa_ids}"
  425. cmd.extend(numa_params.split())
  426. with_python = not args.no_python
  427. if with_python:
  428. cmd.append(sys.executable)
  429. cmd.append("-u")
  430. if args.module:
  431. cmd.append("-m")
  432. cmd.append(args.program)
  433. cmd.extend(args.program_args)
  434. cmd_s = " ".join(cmd)
  435. logger.info(cmd_s)
  436. if entrypoint == "":
  437. entrypoint = cmd[0]
  438. del cmd[0]
  439. launch_args[i] = tuple(cmd)
  440. launch_envs[i] = {}
  441. launch_tee[i] = Std.ALL
  442. if args.rank != -1: # launches single instance, rank, only
  443. break
  444. ctx = start_processes(name=args.log_file_prefix,
  445. entrypoint=entrypoint,
  446. args=launch_args,
  447. envs=launch_envs,
  448. log_dir=args.log_path,
  449. tee=launch_tee)
  450. ctx.wait()
  451. def _add_memory_allocator_params(parser):
  452. group = parser.add_argument_group("Memory Allocator Parameters")
  453. # allocator control
  454. group.add_argument("--enable-tcmalloc", "--enable_tcmalloc", action="store_true", default=False,
  455. help="Enable tcmalloc allocator")
  456. group.add_argument("--enable-jemalloc", "--enable_jemalloc", action="store_true", default=False,
  457. help="Enable jemalloc allocator")
  458. group.add_argument("--use-default-allocator", "--use_default_allocator", action="store_true", default=False,
  459. help="Use default memory allocator")
  460. def _add_multi_instance_params(parser):
  461. group = parser.add_argument_group("Multi-instance Parameters")
  462. # multi-instance control
  463. group.add_argument("--ncores-per-instance", "--ncores_per_instance", metavar="\b", default=-1, type=int,
  464. help="Cores per instance")
  465. group.add_argument("--ninstances", metavar="\b", default=-1, type=int,
  466. help="For multi-instance, you should give the cores number you used for per instance.")
  467. group.add_argument("--skip-cross-node-cores", "--skip_cross_node_cores", action='store_true', default=False,
  468. help="If specified --ncores-per-instance, skips cross-node cores.")
  469. group.add_argument("--rank", metavar="\b", default="-1", type=int,
  470. help="Specify instance index to assign ncores_per_instance for rank; \
  471. otherwise ncores_per_instance will be assigned sequentially to ninstances. Please refer to \
  472. https://github.com/intel/intel-extension-for-pytorch/blob/master/docs/tutorials/performance_tuning/launch_script.md")
  473. group.add_argument("--latency-mode", "--latency_mode", action="store_true", default=False,
  474. help="By detault 4 core per instance and use all physical cores")
  475. group.add_argument("--throughput-mode", "--throughput_mode", action="store_true", default=False,
  476. help="By default one instance per node and use all physical cores")
  477. group.add_argument("--node-id", "--node_id", metavar="\b", default=-1, type=int,
  478. help="node id for multi-instance, by default all nodes will be used")
  479. group.add_argument("--use-logical-core", "--use_logical_core", action="store_true", default=False,
  480. help="Whether only use physical cores")
  481. group.add_argument("--disable-numactl", "--disable_numactl", action="store_true", default=False,
  482. help="Disable numactl")
  483. group.add_argument("--core-list", "--core_list", metavar="\b", default=None, type=str,
  484. help="Specify the core list as \"core_id, core_id, ....\", otherwise, all the cores will be used.")
  485. group.add_argument("--log-path", "--log_path", metavar="\b", default="", type=str,
  486. help="The log file directory. Default path is "", which means disable logging to files.")
  487. group.add_argument("--log-file-prefix", "--log_file_prefix", metavar="\b", default="run", type=str,
  488. help="log file prefix")
  489. def _add_kmp_iomp_params(parser):
  490. group = parser.add_argument_group("IOMP Parameters")
  491. group.add_argument("--disable-iomp", "--disable_iomp", action="store_true", default=False,
  492. help="By default, we use Intel OpenMP and libiomp5.so will be add to LD_PRELOAD")
  493. def create_args(parser=None):
  494. """
  495. Helper function parsing the command line options
  496. @retval ArgumentParser
  497. """
  498. parser.add_argument("--multi-instance", "--multi_instance", action="store_true", default=False,
  499. help="Enable multi-instance, by default one instance per node")
  500. parser.add_argument("-m", "--module", default=False, action="store_true",
  501. help="Changes each process to interpret the launch script "
  502. "as a python module, executing with the same behavior as"
  503. "\"python -m\".")
  504. parser.add_argument("--no-python", "--no_python", default=False, action="store_true",
  505. help="Do not prepend the --program script with \"python\" - just exec "
  506. "it directly. Useful when the script is not a Python script.")
  507. _add_memory_allocator_params(parser)
  508. _add_kmp_iomp_params(parser)
  509. _add_multi_instance_params(parser)
  510. # positional
  511. parser.add_argument("program", type=str,
  512. help="The full path to the program/script to be launched. "
  513. "followed by all the arguments for the script")
  514. # rest from the training program
  515. parser.add_argument("program_args", nargs=REMAINDER)
  516. def main(args):
  517. env_before = set(os.environ.keys())
  518. if platform.system() in ["Windows", "Darwin"]:
  519. raise RuntimeError(f"{platform.system()} is not supported!!!")
  520. if args.log_path:
  521. os.makedirs(args.log_path, exist_ok=True)
  522. else:
  523. args.log_path = os.devnull
  524. if args.latency_mode and args.throughput_mode:
  525. raise RuntimeError("Either args.latency_mode or args.throughput_mode should be set")
  526. if not args.no_python and not args.program.endswith(".py"):
  527. raise RuntimeError("For non Python script, you should use \"--no-python\" parameter.")
  528. # Verify LD_PRELOAD
  529. if "LD_PRELOAD" in os.environ:
  530. lst_valid = []
  531. tmp_ldpreload = os.environ["LD_PRELOAD"]
  532. for item in tmp_ldpreload.split(":"):
  533. matches = glob.glob(item)
  534. if len(matches) > 0:
  535. lst_valid.append(item)
  536. else:
  537. logger.warning(f"{item} doesn't exist. Removing it from LD_PRELOAD.")
  538. if len(lst_valid) > 0:
  539. os.environ["LD_PRELOAD"] = ":".join(lst_valid)
  540. else:
  541. os.environ["LD_PRELOAD"] = ""
  542. launcher = _Launcher()
  543. launcher.launch(args)
  544. for x in sorted(set(os.environ.keys()) - env_before):
  545. logger.debug("{x}={os.environ[x]}")
  546. if __name__ == "__main__":
  547. parser = ArgumentParser(description="This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable "
  548. "Processors with optimal configurations. Single instance inference, "
  549. "multi-instance inference are enable. To get the peak performance on Intel(R) "
  550. "Xeon(R) Scalable Processors, the script optimizes the configuration "
  551. "of thread and memory management. For thread management, the script configures thread "
  552. "affinity and the preload of Intel OMP library. For memory management, it configures "
  553. "NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc) "
  554. "\n################################# Basic usage ############################# \n"
  555. "\n 1. single instance\n"
  556. "\n >>> python -m torch.backends.xeon.run_cpu python_script args \n"
  557. "\n2. multi-instance \n"
  558. "\n >>> python -m torch.backends.xeon.run_cpu --ninstances xxx "
  559. "--ncores-per-instance xx python_script args\n"
  560. "\n############################################################################# \n",
  561. formatter_class=RawTextHelpFormatter)
  562. create_args(parser)
  563. args = parser.parse_args()
  564. main(args)