o
    8ήcD                  
   @   s  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Zd dl	Z
d dlmZmZ d dlZd dlmZmZ d dlmZmZ d dlmZmZ d dlmZmZmZ d dlZeejdZdd	d
dZddddZ i dej!e j!gdej"e j"gdg dej#e j#gdej$e j$gde j%gde j&gde j'gde j(gdg de j)gde j*gdg dg dg dg dg i dej+e j+gd e j,gd!e j-gd"g d#g d$g d%g d&ej.e j.gd'g d(g d)g d*g d+ej/e j/gd,ej0e j0gd-g d.g d/g g g g ej1e j1gej2e j2gej3e j3gej4e j4gg d0Z5g d1Z6d2d3 e57 D Z5d4d5 e57 D Z8d6d5 e57 D Z9dGd8d9Z:d:d; Z;d<d= Z<eG d>d? d?eZ=e=>  d@dA Z?dBdC Z@eG dDdE dEeZAeBdFkrueC  dS dS )H    N)chaincombinations)configcpu)prangenjit)compile_isolatedFlags)TestCasetagoverride_env_configz"SVML tests need SVML to be presentnehalemhaswellskylake-avx512)          -prefer-256-bitsincospowexplogacosacoshasinasinhatan2atanatanhcbrtcdfnorm
cdfnorminvceilcosdcosherferfcerfcinverfinvexp10exp2expm1floorfmodhypotinvsqrtlog10log1plog2logb	nearbyint)rintroundsindsinhsqrttantanhtrunc)r;   r<   r2   r-   r3   r=   r   c                 C   s"   i | ]\}}t |d kr||qS )r   )len).0kv rC   </tmp/pip-target-vg8gfxp4/lib/python/numba/tests/test_svml.py
<dictcomp>U   s   " rE   c                 C   &   g | ]\}}d dd |D v r|qS )z<ufuncc                 S      g | ]}t |d d qS  r   strsplitr@   prC   rC   rD   
<listcomp>X       <listcomp>.<listcomp>rC   r@   frB   rC   rC   rD   rO   W       rO   c                 C   rF   )z	<built-inc                 S   rG   rH   rJ   rM   rC   rC   rD   rO   Z   rP   rQ   rC   rR   rC   rC   rD   rO   Y   rT           c                 C   s  |dkrd dd |D }d||| |f }	n:|dkr4d||| d |f }	|	|dr0d	| nd
7 }	n|dks>|dks>J d dd |D }djd i t }	|dkpX|dk}
|
r_| d n| }|
rg|d n|}|rmdnd}tjrvd| nd| }d|||f }|dkr|g}d|g}n|g}g }|dkr|
s|dkr|dd||d |f g7 }| dkr|dkrdg}||g}n|dkrdg}||g}|	||fS )!z
    For a given function and its usage modes,
    returns python code and assembly patterns it should and should not generate
    scalar,c                 S      g | ]}|d  qS )z[0]rC   r@   arC   rC   rD   rO   e       z!func_patterns.<locals>.<listcomp>z%s%s[0] += math.%s(%s)
numpyz%s%s += np.%s(%s)intz.astype(np.%s)

ranger   c                 S   rX   )z[i]rC   rY   rC   rC   rD   rO   l   r[   zP{pad}for i in {mode}({res}.size):
{pad}{pad}{res}[i] += math.{func}({arg_list})
float32	complex64rS   r   r   _haz$_$z__svml_%s%d%s,__svml_r   int32z%zmmr;   sqrtsvsqrtpNrC   )join
startswithformatlocalsr   IS_OSX)funcargsresdtypemodevlenfastmathpadarg_listbodyis_f32rS   rB   	prec_suffscalar_func	svml_funccontainsavoidsrC   rC   rD   func_patterns]   sD   


r}   c                 C   s   |  d| | d| S )z, Returns pretty name for given set of modes _rC   )rp   rq   rr   namerC   rC   rD   usecase_name   s   r   c              	   C   s   t | |||}djdi t }t|dkrtnt}| dr$|t}t }t }|D ]}	t	|	dgd| |||\}
}}|
| ||
7 }|
| q,|d7 }i }t|t | ||| _|| ||fS )	z? Combine multiple function calls under single umbrella usecase z\def {name}(n):
        x   = np.empty(n*8, dtype=np.{dtype})
        ret = np.empty_like(x)
r\   complexxretz        return retNrC   )r   rj   rk   setnumpy_funcsother_funcsri   
differencecomplex_funcs_excluder}   updateexecglobals__doc__)rp   rq   rr   rs   r   rv   funcsr{   r|   rS   bcrZ   ldictrC   rC   rD   combo_svml_usecase   s*   



r   c                   @   sR   e Zd ZdZdZeddgee	 Z
edd Zedd Zed	d
 ZdS )TestSVMLGenerationz; Tests all SVML-generating functions produce desired calls F|z\$[a-z_]\w+,c                 C   sL   t | |}z| \}}W n ty   t }d}Y nw |||d d S )NF)statusmsg)getattr	Exception	traceback
format_excput)clstestnameoutqueuemethodokr   rC   rC   rD   	mp_runner   s   
zTestSVMLGeneration.mp_runnerc           	         s    drdkrd S  dodk}tjft fdd}td }d| t | t| d	fd
d}t d| | d S )Nr   r\   r]   r   c            	   	      s,  t d d \} }}tdt 9 tdt " ztd d d| }W n
   td| j W d    n1 sCw   Y  W d    n1 sRw   Y  |  fdd	|D } fd
d	|D }| os| }dfdd	 	dD }d| d| d| d| j }||fS )Nrs   r   NUMBA_CPU_NAMENUMBA_CPU_FEATURESerror_modelrs   r   zraised while compiling c                    s   g | ]}| vr|qS rC   rC   r@   patternasmrC   rD   rO          zITestSVMLGeneration._inject_test.<locals>.run_template.<locals>.<listcomp>c                    s   g | ]}| v r|qS rC   rC   r   r   rC   rD   rO      r   r^   c                    s$   g | ]} j |rd |vr|qS )")
asm_filtersearch)r@   line)r   rC   rD   rO      s
    

zWhile expecting z	 and not z,
it contains:
z
when compiling )
r   r   vlen2cpuvlen2cpu_featuresr   r   r   inspect_asmrh   rL   )	fnr{   r|   	jitted_fnmissedfoundr   detailr   )r   rp   flagsrq   sigrr   r   rD   run_template   sB   

 
z5TestSVMLGeneration._inject_test.<locals>.run_templater   run_zNot implementedc           	         s   t d}| }|jt| j |gd}|  |jdd}|j}|d u r>|d u r0| 	d n|dk r>| 	d|  d | j
|dd	d
 | }|d }|d }| j||d
 d S )Nspawn)targetrn      )timeoutzProcess timed out.r   zProcess terminated with signal .zprocess ended unexpectedly)r   r   r   )mpget_contextQueueProcesstyper   startrh   exitcodefailassertEqualget
assertTrue)	selfctxqrN   term_or_timeoutr   outr   r   )r   rC   rD   test_runner   s    
z4TestSVMLGeneration._inject_test.<locals>.test_runnertest_)ri   numbaint64staticmethodr   setattrunittest
skipUnless)	r   rp   rq   rr   r   skippedr   postfixr   rC   )r   rp   r   rq   r   r   rr   rD   _inject_test   s   
zTestSVMLGeneration._inject_testc                 C   s|   ddddddddg}dD ]}t D ]}|D ]}dD ]}| |||t| qqqqd	D ]}t| |td
t| | q,d S )NFr\   usecase)rs   r   r   Tfastmath_usecase)ra   float64r`   re   )rV   r_   r   r\   )test_int32_range4_usecase	important)r   r   dictr   r   r   )r   	flag_listrp   rr   r   rq   nrC   rC   rD   autogenerate  s$   zTestSVMLGeneration.autogenerateN)__name__
__module____qualname__r   _numba_parallel_test_recompilerh   list
svml_funcsr   classmethodr   r   r   rC   rC   rC   rD   r      s    
	
@r   c                 C   s
   t | S N)mathr   )r   rC   rC   rD   math_sin_scalar  s   
r   c                 C   s6   t j| t jd}t| D ]}tt |||< q|S )Nrp   )npemptyr   r_   r   r   )r   r   r   rC   rC   rD   math_sin_loop  s   r   c                       sd   e Zd ZdZdZ fddZdd Zdd Zd	d
 Zdd Z	dd Z
dd Zdd Zdd Z  ZS )TestSVMLz  Tests SVML behaves as expected Fc                    sB   t  | _d| j_t  | _d| j_td| j_tt| j	|  d S )NT)
r	   r   nrt	fastflagsr   FastMathOptionsrs   superr   __init__)r   rn   	__class__rC   rD   r   ,  s   zTestSVML.__init__c                 O   sB   |rJ t dd |D }t||| jd}t||| jd}||fS )Nc                 S   s   g | ]}t |qS rC   )r   typeof)r@   r   rC   rC   rD   rO   8  s    z$TestSVML.compile.<locals>.<listcomp>)r   )tupler   r   r   )r   rm   rn   kwargsr   stdfastrC   rC   rD   r   6  s
   zTestSVML.compilec                 G   sx   |st  S g }|D ].}t|tjr||d q	t|tjr(||  q	t|tjr4|| q	t	dt |S )NrA   z%Unsupported argument type encountered)
r   
isinstancer   ndarrayappendcopynumbernumbersNumber
ValueError)r   rn   new_argsr   rC   rC   rD   	copy_args?  s   zTestSVML.copy_argsc              	   O   s@  | j |g|R  \}}|dd }|dd }|dd}|dd}	|| j|  }
|j| j|  }|j| j|  }tjj||
fi | tjj||
fi | td|A td|	# | j |g|R  \}}|ro| || |rw| || W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )	Nstd_patternfast_patterncpu_namer   cpu_featuresr   r   r   )	r   popr	  entry_pointr   testingassert_almost_equalr   check_svml_presence)r   pyfuncrn   r   jitstdjitfastr
  r  r  r  py_expectedjitstd_resultjitfast_resultrC   rC   rD   checkN  s(   PzTestSVML.checkc                 C   s   |j  }| || d S r   )libraryget_asm_strassertIn)r   rm   r   r   rC   rC   rD   r  p  s   
zTestSVML.check_svml_presencec                 C   s2   t jrdnd}| jtd|d | jtd|d d S )Nz$_sinz$sing      @)r
  )r  )r   rl   r  r   )r   patrC   rC   rD   test_scalar_contextt  s   zTestSVML.test_scalar_contextc                 C   s   d}d}| j td||d d S )Nz__svml_sin8_ha,z__svml_sin8,
   )r
  r  )r  r   )r   r   r   rC   rC   rD   	test_svmlz  s   zTestSVML.test_svmlc                 C   sP   d}t jtjd|gt jt jd}| \}}|jdkr&td|j| f d S )Na  if 1:
            import os
            import numpy as np
            import math

            def math_sin_loop(n):
                ret = np.empty(n, dtype=np.float64)
                for x in range(n):
                    ret[x] = math.sin(np.float64(x))
                return ret

            def check_no_svml():
                try:
                    # ban the use of SVML
                    os.environ['NUMBA_DISABLE_INTEL_SVML'] = '1'

                    # delay numba imports to account for env change as
                    # numba.__init__ picks up SVML and it is too late by
                    # then to override using `numba.config`
                    import numba
                    from numba import config
                    from numba.core import cpu
                    from numba.tests.support import override_env_config
                    from numba.core.compiler import compile_isolated, Flags

                    # compile for overridden CPU, with and without fastmath
                    with override_env_config('NUMBA_CPU_NAME', 'skylake-avx512'),                          override_env_config('NUMBA_CPU_FEATURES', ''):
                        sig = (numba.int32,)
                        f = Flags()
                        f.nrt = True
                        std = compile_isolated(math_sin_loop, sig, flags=f)
                        f.fastmath = cpu.FastMathOptions(True)
                        fast = compile_isolated(math_sin_loop, sig, flags=f)
                        fns = std, fast

                        # assert no SVML call is present in the asm
                        for fn in fns:
                            asm = fn.library.get_asm_str()
                            assert '__svml_sin' not in asm
                finally:
                    # not really needed as process is separate
                    os.environ['NUMBA_DISABLE_INTEL_SVML'] = '0'
                    config.reload_config()
            check_no_svml()
            z-c)stdoutstderrr   z/process failed with code %s: stderr follows
%s
)	
subprocessPopensys
executablePIPEcommunicate
returncodeAssertionErrordecode)r   codepopenr   errrC   rC   rD   test_svml_disabled  s   .

zTestSVML.test_svml_disabledc                 C   s<   t dhdddd }|d | d||jd v  d S )	Nr   r\   r   c                 S   sL   t j| d t jd}t |}t|jD ]}||  t|| 7  < q|S )Nr   r   )r   r   r   
empty_liker_   sizer   r&   )r   r   r   irC   rC   rD   impl  s
   
z@TestSVML.test_svml_working_in_non_isolated_context.<locals>.impl   intel_svmlccr   )r   r   inspect_llvm
signatures)r   r3  rC   rC   rD   )test_svml_working_in_non_isolated_context  s   
z2TestSVML.test_svml_working_in_non_isolated_context)r   r   r   r   r   r   r   r	  r  r  r  r   r/  r8  __classcell__rC   rC   r   rD   r   %  s    
	"8r   __main__)rU   )Dr   r\   r   r#  r  	importlibr%  r   r   multiprocessingr   	itertoolsr   r   r   
numba.corer   r   r   r   numba.core.compilerr   r	   numba.tests.supportr
   r   r   r   r   
USING_SVML
needs_svmlr   r   r   r   r   r   r   r   r   r   r   r    r&   r'   r(   r-   r2   r3   r:   r;   r<   r=   r   r   itemsr   r   r}   r   r   r   r   r   r   r   r   mainrC   rC   rC   rD   <module>   s    	
 !"#



-
4e 
 