
    Q%dY3                     8   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 ej                    v rrd dlZ ej	                    d          Z
ej                            e
dd          Zej        j        dk    r ej        e           ej        dxx         ej        ez   z  cc<   ddlT dd	lmZ ddlT dd	lmZ d
dgez   ez   ZdZda	 da	 dZddZ	 	 ddZ G d dej        j                  Z	 	 ddZ  G d dej        j                  Z! G d d
          Z"d Z#d Z$d Z%dS )    NWindowsLibrarybin   PATH   )*)__all__Monkey	is_activez
Python API for Intel(R) oneAPI Threading Building Blocks (oneTBB)
extended with standard Python's pools implementation and monkey-patching.

Command-line interface example:
$  python3 -m tbb $your_script.py
Runs your_script.py in context of tbb.Monkey
Fzlibirml.so.1c                     ddl } |j                    dk    rCt          j        t                     dt          j        dt          j        z   dz             k    sJ ddlm}  ||            t          d	           dS )
z
Some testsr   NLinux   zldd z#| grep -E 'libimf|libsvml|libintlc'r   )testdone)
platformsystemctypesCDLLlibirmlos_api__file__r   print)argr   r   s      ,lib/python3.11/site-packages/tbb/__init__.py_testr   ;   s    OOOxG##Gbit} 45Z Z[[[[[[DIII	&MMMMM     c                     ddl m}  || ||||           t          rY	 t          j        t
                    }|                                 d S #  t          dt
          t          j	                   Y d S xY wd S Nr   )workerzWarning: Can not load file
multiprocessing.poolr"   ipc_enabledr   r   r   release_resourcesr   sysstderr)inqueueoutqueueinitializerinitargsmaxtasksr"   librmls          r   tbb_process_pool_worker27r1   F   s    ++++++
F7Hk8X>>> F	F[))F$$&&&&&	F*G#*EEEEEEEF Fs   -A #A3c                        e Zd Zd Zd Zd ZdS )TBBProcessPool27c           	         ddl m} t          | j        t	          | j                  z
            D ]}|                     t          | j        | j	        | j
        | j        | j        f          }| j                            |           |j                            dd          |_        d|_        |                                  |d           dS 	zBring the number of pool processes up to the specified number,
        for use after reaping workers which have exited.
        r   )debug)targetargsProcess
PoolWorkerTzadded workerN)multiprocessing.utilr6   range
_processeslen_poolr9   r1   _inqueue	_outqueue_initializer	_initargs_maxtasksperchildappendnamereplacedaemonstartselfr6   iws       r   _repopulate_poolz!TBBProcessPool27._repopulate_poolS   s     	/.....tTZ899 
	" 
	"A$=#'=$.#'#4#'>43I#K   A
 Ja   V^^I|<<AFAHGGIIIE.!!!!
	" 
	"r   c                 j    |                                   | j        D ]}|                                 d S Ncloser?   joinrK   ps     r   __del__zTBBProcessPool27.__del__e   9    

 	 	AFFHHHH	 	r   c                 j    |                                   | j        D ]}|                                 d S rP   rQ   rK   r8   rU   s      r   __exit__zTBBProcessPool27.__exit__j   rW   r   N__name__
__module____qualname__rN   rV   rZ   r   r   r   r3   r3   R   sA        " " "$  
    r   r3   c                     ddl m}  || |||||           t          rY	 t          j        t
                    }|                                 d S #  t          dt
          t          j	                   Y d S xY wd S r!   r%   )r+   r,   r-   r.   r/   wrap_exceptionr"   r0   s           r   tbb_process_pool_worker3ra   p   s    ++++++
F7Hk8X~NNN F	F[))F$$&&&&&	F*G#*EEEEEEEF Fs   -A #A4c                        e Zd Zd Zd Zd ZdS )TBBProcessPool3c           
         ddl m} t          | j        t	          | j                  z
            D ]}|                     t          | j        | j	        | j
        | j        | j        | j        f          }| j                            |           |j                            dd          |_        d|_        |                                  |d           dS r5   )r;   r6   r<   r=   r>   r?   r9   ra   r@   rA   rB   rC   rD   _wrap_exceptionrE   rF   rG   rH   rI   rJ   s       r   rN   z TBBProcessPool3._repopulate_pool}   s     	/.....tTZ899 	" 	"A$<#'=$.#'#4#'>43I#'#7#9   A Ja   V^^I|<<AFAHGGIIIE.!!!!	" 	"r   c                 j    |                                   | j        D ]}|                                 d S rP   rQ   rT   s     r   rV   zTBBProcessPool3.__del__   rW   r   c                 j    |                                   | j        D ]}|                                 d S rP   rQ   rY   s      r   rZ   zTBBProcessPool3.__exit__   rW   r   Nr[   r   r   r   rc   rc   |   sA        " " "&  
    r   rc   c                   4    e Zd ZdZi Zi ZddZd Zd Zd Z	dS )	r   a  
    Context manager which replaces standard multiprocessing.pool
    implementations with tbb.pool using monkey-patching. It also enables oneTBB
    threading for Intel(R) oneAPI Math Kernel Library (oneMKL). For example:

        with tbb.Monkey():
            run_my_numpy_code()

    It allows multiple parallel tasks to be executed on the same thread pool
    and coordinate number of threads across multiple processes thus avoiding
    overheads from oversubscription.
    NFc                     |r,t          t           j        t          |                    | _        |r0|st	                      }ddlm}  |t          |                     dS dS )a  
        Create context manager for running under TBB scheduler.
        :param max_num_threads: if specified, limits maximal number of threads
        :param benchmark: if specified, blocks in initialization until requested number of threads are ready
        r   )_concurrency_barrierN)global_controlmax_allowed_parallelismintctldefault_num_threadsapirj   )rK   max_num_threads	benchmarkrj   s       r   __init__zMonkey.__init__   s      	d%n&LcRaNbNbccDH 	7" 7!4!6!6111111  _!5!566666		7 	7r   c                     t          |t                      t                      |g          x}| j        |<   |d k    rd S t	          ||d           }|d k    rd | j        |<   d S || j        |<   t          |||           d S rP   )
__import__globalslocals_modulesgetattr_itemssetattr)rK   
class_namemodule_nameobjmoldattrs         r   _patchzMonkey._patch   s    (2;		3988j\)K )K 	KDM*%99F!Z..d??(,DM*%F")J:s#####r   c                 4   t           dk    s
J d            da t          j        d          | _        dt          j        d<   t          j        d          | _        dt          j        d<   t          rt          j        j	        dk    r2t          j        j
        dk    r|                     d	d
t                     nFt          j        j	        dk    r1t          j        j
        dk    r|                     d	d
t                     |                     dd
t                     | S )NFz'tbb.Monkey does not support nesting yetTMKL_THREADING_LAYERTBBNUMBA_THREADING_LAYER      Poolzmultiprocessing.pool      
ThreadPool)r   r   getenvenv_mklenviron	env_numbar'   r)   version_infomajorminorr   r3   rc   r   )rK   s    r   	__enter__zMonkey.__enter__   s    E!!!#L!!!	y!677,1
()#:;;.3
*+ 	M%**s/?/E/J/JF$:<LMMMM!'1,,1A1G11L1LF$:OLLLL"8$???r   c                 ^   t           dk    s
J d            da | j        t          j        d= n| j        t          j        d<   | j        t          j        d= n| j        t          j        d<   | j                                        D ])}t          | j        |         || j        |                    *d S )NTz	modified?Fr   r   )	r   r   r   r   r   rz   keysr{   rx   )rK   exc_type	exc_value	tracebackrF   s        r   rZ   zMonkey.__exit__   s    D   +   	<
01104BJ,->!
23326.BJ./K$$&& 	B 	BDDM$'t{4/@AAAA	B 	Br   )NF)
r\   r]   r^   __doc__rz   rx   rs   r   r   rZ   r   r   r   r   r      sp          FH7 7 7 7
$ 
$ 
$  "B B B B Br   c                      	 t          j        t                    } |                                  |                                  d S # t
          $ r'}t          d|t          j                   Y d }~d S d }~ww xY w)Nz6Warning: Can not initialize name of shared semaphores:r#   )	r   r   r   set_active_sem_nameset_stop_sem_name	Exceptionr   r)   r*   )r0   es     r   init_sem_namer      s    W%%""$$$  """""   F:	 	 	 	 	 	 	 	 	 	s   AA 
A6A11A6c                      t           rS	 t          j        t                    } |                                  d S #  t          dt          j                   Y d S xY wd S )Nz*Warning: Can not release shared semaphoresr#   )r'   r   r   r   release_semaphoresr   r)   r*   )r0   s    r   
tbb_atexitr      sw     #	#[))F%%'''''	#>z# # # # # # ## #s	   -8 Ac                     dd l } dd l}|                    dd|j                  } | j                    dk    rI|                    ddd	           |                    d
ddd	           |                    ddd	           |                    ddt                      t          dd           |                    dddd	           |                    dddd	           |                    dddd           |                    dd            |                    d!|j        d"#           |	                                }|j
        rd$t          j        d%<    | j                    dk    r|j        rd&|_        |j        rt          j                            d'          sd(}d)}d$t          j        d'<   t!          d t          j                            |d*                              d+                    }||v rt%          d,|d-|d.           n3d+                    |gt)          |          z             t          j        |<   |j        r | j                    dk    sJ 	 t+          d/d0          5 }t          |                                          }d d d            n# 1 swxY w Y   |dk    rt%          d1           d$t          j        d2<   n*#  t%          d3           t/          j        d4           Y nxY wt          j        t.          j        t.          j        dd5gt.          j        d4d          R   J d7            |j        g|j        z   t.          _         | j                    dk    o|j        at>          rd$nd8t          j        d9<   t>          r'tA          j!        tD                     tG                       t          j                            d:          sd8t          j        d:<   d;|j        z   tI                      v r$ tI                      d;|j        z            |j         S dd l%}	|j&        r|	j'        n|	j(        }
tS          |j*        |j+        <          5   |
|j        d=>           d d d            d S # 1 swxY w Y   d S )?Nr   zpython3 -m tbba  
                Run your Python script in context of tbb.Monkey, which
                replaces standard Python pools and threading layer of
                Intel(R) oneAPI Math Kernel Library (oneMKL) by implementation based on
                Intel(R) oneAPI Threading Building Blocks (oneTBB). It enables multiple parallel
                tasks to be executed on the same thread pool and coordinate
                number of threads across multiple processes thus avoiding
                overheads from oversubscription.
             )progdescriptionformatter_classr   z--ipc
store_truezAEnable inter-process (IPC) coordination between oneTBB schedulers)actionhelpz-az--allocatorzOEnable oneTBB scalable allocator as a replacement for standard memory allocatorz--allocator-huge-pagesz4Enable huge pages for oneTBB allocator (implies: -a)z-pz--max-num-threadsz:Initialize oneTBB with P max number of threads per processP)defaulttyper   metavarz-bz--benchmarkzBlock oneTBB initialization until all the threads are created before continue the script. This is necessary for performance benchmarks that want to exclude lazy scheduler initialization effects from the measurementsz-vz	--verbosez'Request verbose and version informationz-mmodulezExecutes following as a module)r   destr   rF   zScript or module name)r   r8   zCommand line arguments)nargsr   1TBB_VERSIONT_TBB_MALLOC_PRELOADzlibtbbmalloc_proxy.so.2
LD_PRELOAD :zInfo:containszalready
z/proc/sys/vm/nr_hugepagesrzoneTBB: Pre-allocated huge pages are not currently reserved in the system. To reserve, run e.g.:
	sudo sh -c 'echo 2000 > /proc/sys/vm/nr_hugepages'TBB_MALLOC_USE_HUGE_PAGESzoneTBB: Failed to read number of pages from /proc/sys/vm/nr_hugepages
	Is the Linux kernel configured with the huge pages feature?r   tbbFzRe-execution failed0
IPC_ENABLEKMP_BLOCKTIME_)rq   rr   __main__)run_name),r   argparseArgumentParserArgumentDefaultsHelpFormatterr   add_argumentro   rm   	REMAINDER
parse_argsverboser   r   allocator_huge_pages	allocatorgetfiltersplitr   rS   listopenreadr)   exitexecl
executableargvrF   r8   ipcr'   atexitregisterr   r   rv   runpyr   
run_modulerun_pathr   rq   rr   )r   r   parserr8   libtbbmalloc_lib
ld_preloadpreload_listfpagesr   runfs              r   _mainr      sw   
 OOOOOO$$*: I #+"H % J JF xG##GL` 	 	b 	b 	bD-n 	 	p 	p 	p4\S 	 	U 	U 	U
1;N;P;PWZYcf  h h h
mLX  Y Y Y k,F  H H H
\=  ? ? ?
%<===
h&85  7 7 7D| ($'
=!xG##$ 	"!DN> 	0"*..1F"G"G 	08%J03BJ,-!$
z2(F(F(L(LS(Q(QRRL<//gz:7GUUUU),3C2DtLGYGY2Y)Z)Z
:&(  &x((G3333
 93?? .1 #AFFHH. . . . . . . . . . . . . . .zz U V V V>ABJ:;;  Z [ [ [HQKKKKKHS^S^T5P38ABB<PPPP/////	{TY&CH!(/##w.;48K&1:sssBJ| 
###:>>/** *&)
?#
TY'))##)wyyty)4955#';BuEND$8DNSSS 	1 	1DZ0000	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1 	1sB   K -"JK JK "J#'K %K2Q22Q69Q6rP   )Nr   N)Nr   NF)&r&   multiprocessingr   r   r)   r   r   r   sitegetsitepackagespath_to_envpathrS   path_to_libsr   r   add_dll_directoryr   pathseprp   r
   api__allpool	pool__allr   r   r'   r   r   r1   r   r3   ra   rc   r   r   r   r   r   r   r   <module>r      sp  "       



 				 !!!!KKK&$&((+K7<<Y>>L
""\***Jv"*|33     $ $ $ $ $ $     & & & & & &[
!H
,y
8 	 5 -
    MO%)	F 	F 	F 	F    +0   < LN:?	F 	F 	F 	F    o*/   >HB HB HB HB HB HB HB HBV  # # #S1 S1 S1 S1 S1r   