
    קg                        d Z ddlZddlZddlZddlZddlZddlZddlZddlm	Z	m
Z
mZ ddlmZ ddlmZmZ ddlmZmZmZ dZ ej        ej        e            ej        e          Z G d	 d
          Z G d d          Zd Zd Zd Z ddZ!d Z"edk    r9 e	de
          Z# e!e#           e#$                                Z% e"e%           dS dS )a  
This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable Processors with optimal configurations.

Single instance inference, multi-instance inference are enabled.

Note: term "instance" here doesn't refer to a cloud instance. This script is executed as a single process. It invokes
multiple "instances" which are formed from multiple threads for each. "instance" is kind of group of threads in this
context.

Illustrated as below:

::

    +-----------------------------+----------------------+-------+
    |            process          |        thread        | core  |
    +=============================+======================+=======+
    | torch.backends.xeon.run_cpu | instance 0: thread 0 |   0   |
    |                             |             thread 1 |   1   |
    |                             +----------------------+-------+
    |                             | instance 1: thread 0 |   2   |
    |                             |             thread 1 |   3   |
    |                             +----------------------+-------+
    |                             | ...                  |  ...  |
    |                             +----------------------+-------+
    |                             | instance N: thread 0 |   M   |
    |                             |             thread 1 |  M+1  |
    +-----------------------------+----------------------+-------+

To get the peak performance on Intel(R) Xeon(R) Scalable Processors, the script optimizes the configuration of thread and memory
management. For thread management, the script configures thread affinity and the preload of Intel OMP library.
For memory management, it configures NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc).

Environment variables that will be set by this script:

+------------------+-------------------------------------------------------------------------------------------------+
| Environ Variable |                                             Value                                               |
+==================+=================================================================================================+
|    LD_PRELOAD    | Depending on knobs you set, <lib>/libiomp5.so, <lib>/libjemalloc.so, <lib>/libtcmalloc.so might |
|                  | be appended to LD_PRELOAD.                                                                      |
+------------------+-------------------------------------------------------------------------------------------------+
|   KMP_AFFINITY   | If libiomp5.so is preloaded, KMP_AFFINITY could be set to "granularity=fine,compact,1,0".       |
+------------------+-------------------------------------------------------------------------------------------------+
|   KMP_BLOCKTIME  | If libiomp5.so is preloaded, KMP_BLOCKTIME is set to "1".                                       |
+------------------+-------------------------------------------------------------------------------------------------+
|  OMP_NUM_THREADS | value of ncores_per_instance                                                                    |
+------------------+-------------------------------------------------------------------------------------------------+
|    MALLOC_CONF   | If libjemalloc.so is preloaded, MALLOC_CONF will be set to                                      |
|                  | "oversize_threshold:1,background_thread:true,metadata_thp:auto".                                |
+------------------+-------------------------------------------------------------------------------------------------+

*Note*: This script respects environment variables set preliminarily. I.e. If you set the environment variables
mentioned above before running the script, the script will not overwrite the values in the script.

How to use this module:
~~~~~~~~~~~~~~~~~~~~~~~

Single instance inference
-------------------------

1. Run single-instance inference on a single node with all CPU nodes.

::

   python -m torch.backends.xeon.run_cpu --throughput-mode script.py args

2. Run single-instance inference on a single CPU node.

::

   python -m torch.backends.xeon.run_cpu --node-id 1 script.py args

Multi-instance inference
------------------------

1. Multi-instance
   By default this tool runs one process per node. If you want to set the instance numbers and core per instance,
   --ninstances and  --ncores-per-instance should be set.

::

   python -m torch.backends.xeon.run_cpu -- python_script args

   eg: on an Intel(R) Xeon(R) Scalable Processor with 14 instance, 4 cores per instance

::

   python -m torch.backends.xeon.run_cpu --ninstances 14 --ncores-per-instance 4 python_script args

2. Run single-instance inference among multiple instances.
   By default, runs all ninstances. If you want to independently run a single instance among ninstances, specify rank.

   eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 0-27)

::

   python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 0 python_script args

   eg: run 1st instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance (i.e., numactl -C 28-55)

::

   python -m torch.backends.xeon.run_cpu --ninstances 2 --rank 1 python_script args

   eg: run 0th instance on an Intel(R) Xeon(R) Scalable Processor with 2 instance, 2 cores per instance,
   first four cores (i.e., numactl -C 0-1)

::

   python -m torch.backends.xeon.run_cpu --core-list "0, 1, 2, 3" --ninstances 2 --ncores-per-instance 2
   --rank 0 python_script args

3. To look up what optional arguments this module offers:

::

    python -m torch.backends.xeon.run_cpu --help

Memory allocator
----------------

"--enable-tcmalloc" and "--enable-jemalloc" can be used to enable different memory allcator.

    N)ArgumentParserRawTextHelpFormatter	REMAINDER)
expanduser)DictList)DefaultLogsSpecsstart_processesStdz4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatc                   D    e Zd ZdZddZd Zd Zd Zd Zd Z	d	 Z
d
 ZdS )_CPUinfoz=Get CPU information, such as cores list and NUMA information. c                 F   g | _         t          j                    dv r#t          t          j                     d          t          j                    dk    rG|dk    r.ddg}t	          j        |d                              d	          }n|                    d	          }|D ]m}d
}t          j        ||          }|rR| j         	                    |
                    d                                                              d                     nt          t          d | j         D                                 dz   | _        g | _        g | _        i | _        i | _        t'          | j                  D ]+}g }g }	| j         D ]}
|
d         dk    r|
d         nd}|t          |          k    rt          |
d                   |vrR|	                    t          |
d                              t          |          | j        t          |
d                   <   |		                    t          |
d                              t          |          | j        t          |
d                   <   | j        	                    |           | j        	                    |	           +d S d S )NWindowsDarwin is not supported!!!Linuxr   lscpuz--parse=CPU,Core,Socket,NodeT)universal_newlines
z^([\d]+,[\d]+,[\d]+,[\d]?)   ,c              3   &   K   | ]}|d          V  dS )   N ).0lines     W/var/www/html/ai-engine/env/lib/python3.11/site-packages/torch/backends/xeon/run_cpu.py	<genexpr>z$_CPUinfo.__init__.<locals>.<genexpr>   s&      $F$FT!W$F$F$F$F$F$F    r   0r   )cpuinfoplatformsystemRuntimeError
subprocesscheck_outputsplitresearchappendgroupstripintmax	node_numsnode_physical_coresnode_logical_coresphysical_core_node_maplogical_core_node_maprange)self
test_input	lscpu_cmd
lscpu_infor    pattern	regex_outnode_idcur_node_physical_corecur_node_logical_corer%   nids               r!   __init__z_CPUinfo.__init__   s   ? 555(/"3"3IIIJJJ_')) R$&DE	'4$  %++ 
 (--d33
 # O O7Igt44	 OL''	(:(:(@(@(B(B(H(H(M(MNNN !$F$F$F$F$F!F!FGG!KDN8:D$79D#*,D')+D& 00 F F)+&(*%#| S SG(/
b(8(8'!**cC#c((**wqz??2HHH299#gaj//JJJKNw<<D7GAJH-44S__EEEFI'll23wqz??C(//0FGGG'../DEEEE[ *)BF Fr#   c                 `    t          | j                  t          | j        d                   z  S Nr   )lenr4   r9   s    r!   _physical_core_numsz_CPUinfo._physical_core_nums   s(    4+,,s43KA3N/O/OOOr#   c                 `    t          | j                  t          | j        d                   z  S rE   )rF   r5   rG   s    r!   _logical_core_numsz_CPUinfo._logical_core_nums   s(    4*++c$2I!2L.M.MMMr#   c                     |dk     s|| j         dz
  k    rAt          d| dt          t          t	          | j                                                 | j        |         S Nr   r   zInvalid node id: z. Valid node ids: )r3   
ValueErrorlistr8   rF   r4   r9   r?   s     r!   get_node_physical_coresz _CPUinfo.get_node_physical_cores   sl    Q;;'DNQ$666kGkktE#dNfJgJgDhDh?i?ikk   '00r#   c                     |dk     s|| j         dz
  k    rAt          d| dt          t          t	          | j                                                 | j        |         S rL   )r3   rM   rN   r8   rF   r4   r5   rO   s     r!   get_node_logical_coresz_CPUinfo.get_node_logical_cores   sl    Q;;'DNQ$666kGkktE#dNfJgJgDhDh?i?ikk   &w//r#   c                 H    g }| j         D ]}|                    |           |S N)r4   extendr9   	all_corescoress      r!   get_all_physical_coresz_CPUinfo.get_all_physical_cores   s6    	- 	$ 	$EU####r#   c                 H    g }| j         D ]}|                    |           |S rT   )r5   rU   rV   s      r!   get_all_logical_coresz_CPUinfo.get_all_logical_cores   s6    	, 	$ 	$EU####r#   c                 :   | j         }g }|D ]#}||         }||vr|                    |           $t          |          dk    r6t                              dt          |          t          |                     t          |          dk    rt          d          |S )z
        Check whether all cores in core_list are in the same NUMA node.

        Cross NUMA will reduce performance.
        We strongly advice to not use cores on different nodes.
        r   zNuma Aware: cores:%s on different NUMA nodes:%s. To avoid this behavior, please use --ncores-per-instance knob to make sure number of cores is divisible by --ncores-per-instance. Alternatively, please use --skip-cross-node-cores knob.r   z<invalid number of NUMA nodes; please make sure numa_ids >= 1)r7   r.   rF   loggerwarningstrr(   )r9   	core_listcores_numa_mapnuma_idscorenuma_ids         r!   numa_aware_checkz_CPUinfo.numa_aware_check   s     3 	) 	)D$T*Gh&&(((x==1NNC IH   x==AN   r#   Nr   )__name__
__module____qualname____doc__rC   rH   rJ   rP   rR   rY   r[   re   r   r#   r!   r   r      s        GG1F 1F 1F 1FfP P PN N N1 1 10 0 0        r#   r   c                   v    e Zd ZdZd ed           dZddZd Zd	 Z	 ddZ	ddZ
d Z	 	 	 	 	 ddZ	 d ZdS )	_LauncherzClass for launcher.zUnable to find the {0} library file lib{1}.so in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or ~zD/.local/lib/ so the LD_PRELOAD environment variable will not be set.returnNc                 ,    t                      | _        d S rT   )r   r%   rG   s    r!   rC   z_Launcher.__init__  s    zzr#   c                    g }dt           j        v r(|                    t           j        d          d           dt           j        v r(|                    t           j        d          d           |t          d           ddddd	gz  }d
}d
}t          j        dd                              d          D ]}|                    d| d          rd} n |s|D ]}t           j                            |d| d          }t          j	        |          }t          |          dk    rX|d          t          j        dd          g}	t           j                            d |	D                       t           j        d<   d} n|p|S )z&Enable TCMalloc/JeMalloc/intel OpenMP.CONDA_PREFIXz/libVIRTUAL_ENVrm   z/.local/libz/usr/local/libz/usr/local/lib64z/usr/libz
/usr/lib64F
LD_PRELOADr   :libz.soTr   c                 P    g | ]#}||                     t          j                  $S r   )r0   ospathsep)r   ps     r!   
<listcomp>z-_Launcher.add_lib_preload.<locals>.<listcomp>.  s+    GGGQG,,GGGr#   )rw   environr.   r   getenvr+   endswithpathjoinglobrF   rx   )
r9   lib_typelibrary_pathslib_findlib_setitemlib_pathlibrary_filematchesld_preloadss
             r!   add_lib_preloadz_Launcher.add_lib_preload  s   RZ''  BJ~$>!D!D!DEEEBJ&&  BJ}$=!C!C!CDDD#+++
 	
 IlB//55c:: 	 	D}}0800011   
	) 	 	!w||H6IH6I6I6IJJ)L11w<<!##&-aj?BIlB4O4O"PK/1zGGkGGG0 0BJ|,  $HE $ "("r#   c                     d}	 g d}t          j        |t          j        t           j        t           j        d          }|j        dk    rd}n# t          $ r Y nw xY w|S )NF)numactlz-Cr$   -mr$   hostname)envstdoutstderrcheckr   T)r)   runrw   r{   DEVNULL
returncode	Exception)r9   numactl_availablecmdrs       r!   is_numactl_availablez_Launcher.is_numactl_available4  s    !	???CJ!)!)  A |q  $(! 	 	 	D	  s   AA 
AATFc                 @   |r|rt          d          |rn|                     d          }|s:| j         d}t                              |                    dd                     dS t                              d           dS |r|                     d          }|s:| j         d}t                              |                    d	d                     dS t                              d
           |                     dd           dS |rdS |                     d          }|rt                              d           dS |                     d          }|rt                              d
           dS t                              dt          d                     dS )a  
        Enable TCMalloc/JeMalloc with LD_PRELOAD and set configuration for JeMalloc.

        By default, PTMalloc will be used for PyTorch, but TCMalloc and JeMalloc can get better
        memory reuse and reduce page fault to improve performance.
        z8Unable to enable TCMalloc and JEMalloc at the same time.tcmallocr   zE you can use "conda install -c conda-forge gperftools" to install {0}TCmalloczUse TCMalloc memory allocatorjemalloczC you can use "conda install -c conda-forge jemalloc" to install {0}JemalloczUse JeMalloc memory allocatorMALLOC_CONFz=oversize_threshold:1,background_thread:true,metadata_thp:autoNa[  Neither TCMalloc nor JeMalloc is found in $CONDA_PREFIX/lib or $VIRTUAL_ENV/lib
                            or /.local/lib/ or /usr/local/lib/ or /usr/local/lib64/ or /usr/lib or /usr/lib64 or
                           %s/.local/lib/ so the LD_PRELOAD environment variable will not be set.
                           This may drop the performancerm   )	r(   r   msg_lib_notfoundr]   r^   r   infoset_envr   )r9   enable_tcmallocenable_jemallocuse_default_allocatorfind_tcmsgfind_jes          r!   set_memory_allocatorz_Launcher.set_memory_allocatorE  s     	 	J    &	**J*??G =.wwwszz*jAABBBBB;<<<<< 	**J*??G .uuuszz*jAABBBBB;<<<!S    
 # 	D **J*??G ;<<<**J*??G ;<<<NN< 3    r#   r   c                 ~    |t           j        v r.t                              d|t           j        |                    d S d S )N%s=%s)rw   r{   r]   r   )r9   env_var_names     r!   log_env_varz_Launcher.log_env_var{  s:    2:%%KKrz,/GHHHHH &%r#   c                 ,   |st                               d|           |t          j        vr|t          j        |<   nCt          j        |         |k    r-t                               d|t          j        |         |           |                     |           d S )Nz
%s is NonezcOverriding value with the one set in environment variable: %s. Value applied: %s. Value ignored: %s)r]   r^   rw   r{   r   )r9   env_name	env_values      r!   r   z_Launcher.set_env  s     	3NN<2222:%%#,BJx  Z!Y..NN&
8$   	"""""r#   c                    |                      |||           |                     dt          |                     |s|                     d          }|s9| j         d}t
                              |                    dd                     nHt
                              d           |r|                     dd           |                     d	d
           | 	                    d           dS )a  
        Set multi-thread configuration and enable Intel openMP and TCMalloc/JeMalloc.

        By default, GNU openMP and PTMalloc are used in PyTorch. but Intel openMP and TCMalloc/JeMalloc are better alternatives
        to get performance benefit.
        OMP_NUM_THREADSiomp5r   z/ you can use "conda install mkl" to install {0}iompzUsing Intel OpenMPKMP_AFFINITYzgranularity=fine,compact,1,0KMP_BLOCKTIME1rs   N)
r   r   r_   r   r   r]   r^   r   r   r   )	r9   ncores_per_instancedisable_iompset_kmp_affinityr   r   r   	find_iompr   s	            r!   set_multi_thread_and_allocatorz(_Launcher.set_multi_thread_and_allocator  s     	!!_.C	
 	
 	
 	&,?(@(@AAA 		3,,g,>>I 3.aaaszz&'::;;;;0111# QLL1OPPP_c222&&&&&r#   c           
          g }d}d}|j         rd |j                             d          D             }|j        dk    rt          d          |j        dk    rX|j        |j        z  t          |          k     r8t                              d|j        |j        z  t          |                     nBt          |          |j        z  |_        n$|j        rG|j	        dk    r | j
                            |j	                  }n`| j
                                        }d}nD|j	        dk    r | j
                            |j	                  }n| j
                                        }|j        s3|j        dk    r(|j        dk    rd|_        t          |          |_        n|j        r|j        dk    r|j        dk    r	d|_        nn|j        dk    ri|j        dk    r^|j        t          |          k    r(t          d	t          |           d
|j         d          t          |          |j        z  |_        n|j        dk    r|j        dk    r|j        st          |          |j        z  |_        nt          | j
        j        d                   }||j        z  }|j        |k    r7t                              d||j                   t'          j        d           nR|dk    r8t                              d           t          |          |j        z  |_        n|j        dk    rt                              d           d}t-                      }||z  t          |          k    rA|                    |||z  |z
  ||z                      |dz  }||z  t          |          k    At1          t-          |          |z
            }t          |          |j        z  dk    sJ t          |          |j        z  |_        n/|j        |j        z  t          |          k    rt          d          |j        rVt                              d           d|_        | j
                                        }t          |          |j        z  |_        |j        r`t                              d           | j
        j        |_        | j
                                        }t          |          |j        z  |_        |j        dk    r1|j        dk    r&t                              d|j        |j                   |j        so|                                 }	|	sY|j        s$t                              d           d|_        d}n.t                              d           t'          j        d           |j        sd}|                     |j        |j         ||j!        |j"        |j#                   d}
i }i }i }tI          tJ          j&        '                    dd                    }tI          tJ          j&        '                    dd                    }tQ          |j                  D ]}g }d}|j        r|r|j        sdg}n|rdg}tS          |          }|j        dk    r|||j        z  |dz   |j        z           }n'||j        |j        z  |j        dz   |j        z           }g }|dk    r7t          |          }||z  }|dk    s
J d            |||z  ||dz   z           }|D ]k}t          |          dk    r||d}|*                    |           0||d         d         z
  dk    r||d         d<   Q||d}|*                    |           l|D ]}| |d          d |d          d}|d d         }|j        smd!| d"}d+                    d# | j
        ,                    |          D                       }|d$| z  }|-                    |                                           n/|r-d%| d"}|-                    |                                           |j.         }|r4|*                    t&          j/                   |*                    d&           |j0        r|*                    d'           |*                    |j1                   |-                    |j2                   d"+                    |          }t                              |           |
dk    r|d         }
|d= tg          |          ||<   i ||<   th          j5        ||<   |j        dk    r ntm          |j7        |
||tq          |j9        |(          )          }|:                                 d S )*NTFc                 ,    g | ]}t          |          S r   )r1   )r   xs     r!   rz   z$_Launcher.launch.<locals>.<listcomp>  s    ???SVV???r#   r   zRplease specify the "--ncores-per-instance" if you have pass the --core-list paramsr   zGonly first %s cores will be used, but you specify %s cores in core_listz
there are z total cores but you specify z8 ninstances; please make sure ninstances <= total_cores)r   zthere are %s core(s) per socket, but you specify %s ncores_per_instance and skip_cross_node_cores. Please make sure --ncores-per-instance < core(s) per socketzB--skip-cross-node-cores is set, but there are no cross-node cores.zr--skip-cross-node-cores is exclusive to --ninstances. --ninstances won't take effect even if it is set explicitly.z@Please make sure ninstances * ncores_per_instance <= total_coresz--latency-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and --use-logical-core. They won't take effect even they are set explicitly.   z--throughput-mode is exclusive to --ninstances, --ncores-per-instance, --node-id and --use-logical-core. They won't take effect even they are set explicitly.z"assigning %s cores for instance %szCore binding with numactl is not available. Disabling numactl and using taskset instead.                     This may affect performance in multi-socket system; please use numactl if memory binding is needed.zCore binding with numactl is not available, and --disable_taskset is set.                     Please unset --disable_taskset to use taskset instead of numactl.r   LOCAL_WORLD_SIZE
LOCAL_RANKr   tasksetz3At least one core needs to be assigned to each rank)startendr   r   -z-C  c                 ,    g | ]}t          |          S r   )r_   )r   rd   s     r!   rz   z$_Launcher.launch.<locals>.<listcomp>  s.        '  LL  r#   z-m z-c z-ur   )log_dirtee)name
entrypointargsenvs
logs_specs);r`   r+   r   r(   
ninstancesrF   r]   r^   use_logical_corer?   r%   rR   r[   rP   rY   multi_instancethroughput_modeskip_cross_node_coresr4   sysexitr   setupdaterN   latency_moder3   rankdisable_numactlr   disable_tasksetr   r   r   r   r   r1   rw   r{   getr8   sortedr.   r   re   rU   	no_python
executablemoduleprogramprogram_argstupler   ALLr
   log_file_prefix_DefaultLogsSpecslog_pathwait)r9   r   rX   r   enable_tasksetncore_per_nodenum_leftover_coresileftover_coresr   r   launch_argslaunch_envs
launch_tee
local_size
local_rankr   cur_process_coresr`   core_rangestotal_num_corescores_per_rankrc   
range_elemr   numa_paramsrb   taskset_paramswith_pythoncmd_sctxs                                  r!   launchz_Launcher.launch  s
   > v	I??T^%9%9#%>%>???E'2--"h   !##,t>UKK',t>JJ	    #&e**0H"H $ B<2%% L??MMEE L>>@@E (-$$<2%% L@@NNEE L??AAE'DOr)),22"#+.u::((#=Or)),22'+$$)R//DOr4I4I?SZZ//&-SZZ - -do - - -  
 035zzT_/LD,,)R//DOr4I4I1 )Q&)%jjD4L&LDOO%()I!)L%M%MN)7$:R)R&/.@@ + 4   +q00`   +.e**8P*P  ?b00"NN!1  
 ),,q0CJJ>>*11 %$2Q$6&8%9;IA;M%N!"   FA -q0CJJ>> !%SZZ.%@ A A"5zzD,DDIIII*-e**8P*P?T%==E

JJ&Z     IJ   ,-(;;=="%e**0H"H# IJ   #',"8;;==+.u::+H(?Q49??KK4(	   # 	! $ 9 9 ; ;$ !+ !NNy   ,0D(%)NNNNW   HRLLL# 	"!N++$  &	
 	
 	
 
')
(:A>>??
a8899
t'' N	 N	AC "' 87> 87+ &$+CC# &$+CuIOO %2367!e2633!II !&	236:i!m2633!I +->>&))nnO%4
%BN&!+++L ,++ )&3n
UV6WW!I & 	; 	;D;''1,,/3D%A%A
#**:6666+b/%"88A==59KOE2237)E)EJ'..z::::$ W WA+<(Vaj(V(V1U8(V(V(V%%$5crc$:!+ 7"<(9"<"<"<K"xx +/<+H+H+S+S     H  #3#3#33KJJ{00223333# 7%?+<%?%?%?NJJ~3355666"n,K !

3>***

4   { !

4   JJt|$$$JJt()))HHSMMEKKR V
A"3ZZKNKNGJqMyB  %!(JOOO
 
 
 	




r#   )rn   N)TFFrf   )FTTFF)rg   rh   ri   rj   r   r   rC   r   r   r   r   r   r   r  r   r#   r!   rl   rl     s        WCW W W" " " "!# !# !#F! ! !$ RW4 4 4 4lI I I I# # #* #' ' ' '>	} } } } }r#   rl   c                     |                      d          }|                    ddddd           |                    dd	ddd
           |                    ddddd           d S )NzMemory Allocator Parametersz--enable-tcmallocz--enable_tcmalloc
store_trueFzEnable tcmalloc allocatoractiondefaulthelpz--enable-jemallocz--enable_jemalloczEnable jemalloc allocatorz--use-default-allocatorz--use_default_allocatorzUse default memory allocatoradd_argument_groupadd_argumentparserr/   s     r!   _add_memory_allocator_paramsr    s    %%&CDDE	(     
(     
!!+      r#   c                 $   |                      d          }|                    ddddt          d           |                    dddt          d	           |                    d
dddd           |                    dddt          d           |                    ddddd           |                    ddddd           |                    ddddt          d           |                    ddddd           |                    dd ddd!           |                    d"d#ddd$           |                    d%d&dd t          d'           |                    d(d)dd*t          d+           |                    d,d-dd.t          d/           d S )0NzMulti-instance Parametersz--ncores-per-instancez--ncores_per_instancer   zCores per instance)metavarr  typer  z--ninstanceszOFor multi-instance, you should give the cores number you used for per instance.z--skip-cross-node-coresz--skip_cross_node_coresr  Fz;If specified --ncores-per-instance, skips cross-node cores.r  z--rankz-1a  Specify instance index to assign ncores_per_instance for rank; otherwise ncores_per_instance will be assigned sequentially to ninstances. Please refer to https://github.com/intel/intel-extension-for-pytorch/blob/master/docs/tutorials/performance_tuning/launch_script.mdz--latency-modez--latency_modez9By default 4 core per instance and use all physical coresz--throughput-modez--throughput_modez;By default one instance per node and use all physical coresz	--node-idz	--node_idz=node id for multi-instance, by default all nodes will be usedz--use-logical-corez--use_logical_corezWhether only use physical coresz--disable-numactlz--disable_numactlzDisable numactlz--disable-tasksetz--disable_tasksetzDisable tasksetz--core-listz--core_listzYSpecify the core list as "core_id, core_id, ....", otherwise, all the cores will be used.z
--log-pathz
--log_pathr   zOThe log file directory. Default path is , which means disable logging to files.z--log-file-prefixz--log_file_prefixr   zlog file prefix)r	  r
  r1   r_   r  s     r!   _add_multi_instance_paramsr    s   %%&ABBE	!     
^     
!!J     
u     
H     
J     
L     
.     
     
     
h     
2     
      r#   c                 d    |                      d          }|                    ddddd           d S )NzIOMP Parametersz--disable-iompz--disable_iompr  FzIBy default, we use Intel OpenMP and libiomp5.so will be add to LD_PRELOADr  r  r  s     r!   _add_kmp_iomp_paramsr  6  sL    %%&788E	X      r#   c                 n   |                      ddddd           |                      ddddd	
           |                      ddddd
           t          |            t          |            t          |            |                      dt          d           |                      dt
                     dS )zE
    Parse the command line options.

    @retval ArgumentParser
    z--multi-instancez--multi_instancer  Fz7Enable multi-instance, by default one instance per noder  r   z--modulezwChanges each process to interpret the launch script as a python module, executing with the same behavior as"python -m".)r  r  r  z--no-pythonz--no_pythonzyDo not prepend the --program script with "python" - just exec it directly. Useful when the script is not a Python script.r   z`The full path to the program/script to be launched. followed by all the arguments for the script)r  r  r   )nargsN)r
  r  r  r  r_   r   )r  s    r!   create_argsr  A  s    F          F     !(((   v&&&
7     i88888r#   c                    t          t          j                                                  }t	          j                    dv r#t          t	          j                     d          | j        rt          j        | j        d           nt          j	        | _        | j
        r| j        rt          d          | j        s)| j                            d          st          d          dt          j        v rg }t          j        d         }|                    d	          D ]Z}t!          j        |          }t#          |          d
k    r|                    |           ?t&                              d|           [t#          |          d
k    r#d	                    |          t          j        d<   ndt          j        d<   t-                      }|                    |            t1          t          t          j                                                  |z
            D ].}t&                              d|t          j        |                    /d S )Nr   r   T)exist_okz>Either args.latency_mode or args.throughput_mode should be setz.pyz>For non Python script, you should use "--no-python" parameter.rs   rt   r   z.%s doesn't exist. Removing it from LD_PRELOAD.r   r   )r   rw   r{   keysr&   r'   r(   r   makedirsdevnullr   r   r   r   r}   r+   r   rF   r.   r]   r^   r   rl   r  r   debug)r   
env_before	lst_validtmp_ldpreloadr   r   launcherr   s           r!   mainr"  r  s   RZ__&&''J111ho//EEEFFF} #
DMD11111
 
T1 
L
 
 	
 > 
$,"7"7">"> 
L
 
 	

 rz!!	
<0!'',, 	W 	WDiooG7||a  &&&&OQUVVVVy>>A'*xx	':':BJ|$$')BJ|${{HOODC
))**Z788 0 0WaA////0 0r#   __main__a  This is a script for launching PyTorch inference on Intel(R) Xeon(R) Scalable Processors with optimal configurations. Single instance inference, multi-instance inference are enable. To get the peak performance on Intel(R) Xeon(R) Scalable Processors, the script optimizes the configuration of thread and memory management. For thread management, the script configures thread affinity and the preload of Intel OMP library. For memory management, it configures NUMA binding and preload optimized memory allocation library (e.g. tcmalloc, jemalloc) 
################################# Basic usage ############################# 

 1. single instance

   >>> python -m torch.backends.xeon.run_cpu python_script args 

2. multi-instance 

   >>> python -m torch.backends.xeon.run_cpu --ninstances xxx --ncores-per-instance xx python_script args

############################################################################# 
)descriptionformatter_classrT   )&rj   r   loggingrw   r&   r,   r)   r   argparser   r   r   os.pathr   typingr   r   )torch.distributed.elastic.multiprocessingr	   r   r
   r   
format_strbasicConfigINFO	getLoggerrg   r]   r   rl   r  r  r  r  r"  r  
parse_argsr   r   r#   r!   <module>r0     s&  z zx   				  				     



 D D D D D D D D D D                        D
  ',z : : : :		8	$	$o o o o o o o odj j j j j j j jZ  4e e eP  .9 .9 .9 .9b&0 &0 &0R z^] -  F" KDDJJJJJ) r#   