U
    <c                     @   s  d dl mZ d dlmZ d dlmZmZ d dlm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 d dlmZmZmZmZmZmZ d dlmZ d d	lmZ d d
lmZ d dlmZ d dl m!Z! d dl"m#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,Z,d dl-m.Z. d dl/m0Z0m1Z1m2Z2m3Z3m4Z4 e	j56 Z7e7ote	j58 dkZ9e7Z:e	j56 re	j;j<se	j=> Z?e@e	j58 D ]$ZAe	j5BeAd  ZCeCdk rdZ:qdd ZDdd ZEdd ZFdd ZGG dd deHZIdZJG dd deZKG d d! d!eHZLed"d# ZMed$d% ZNedId'd(ZOd)d* ZPd+d, ZQd-d. ZRd/d0 ZSd1d2 ZTd3d4 ZUd5d6 ZVd7d8 ZWd9d: ZXd;d< ZYd=d> ZZd?d@ Z[G dAdB dBZ\dCdD Z]dEdF Z^dGdH Z_dS )J    Variable_nested_map)BroadcastingList2BroadcastingList3)OperatorExportTypesN)	FileCheck)
IS_WINDOWSfreeze_rng_state)enable_profiling_mode_for_profiling_testsProfilingModeTEST_BAILOUTSis_iterable_of_tensors)JitCommonTestCase)enable_profiling_mode)contextmanager)reduce)StringIO)defaultdict)Loader)AnyDictListTupleUnion      Fc                 C   s   t | || d S N)exec)codeglobloc r#   E/tmp/pip-unpacked-wheel-gikjz4vx/torch/testing/_internal/jit_utils.pyexecWrapper5   s    r%   c                 C   s   t dd | |S )Nc                 S   s   t | tjS r   )
isinstancetorchTensortr#   r#   r$   <lambda>9       zdo_input_map.<locals>.<lambda>r   fninputr#   r#   r$   do_input_map8   s    r0   c                   C   s,   t j  t jj t jj_t jj  d S r   )	r'   _CZ_jit_clear_class_registryjit
_recursiveZConcreteTypeStoreZconcrete_type_store_stateZ_clear_class_stater#   r#   r#   r$   clear_class_registry;   s    
r5   c                 C   s4   t | j }t|}|dkr,td||d S )Nr   zQThis test assumes this GraphExecutor should only have one execution plan, got: {}r   )listexecution_plansvalueslenRuntimeErrorformat)Zgraph_executor_stater7   Z	num_plansr#   r#   r$   get_execution_plan@   s    r<   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	&_AssertRaisesRegexWithHighlightContextz~
    A context manager that is useful for checking that error messages highlight
    the correct part of the source code.
    c                 C   s   || _ || _|| _|| _d S r   )	test_caseexception_typeregex	highlight)selfr>   	exceptionr@   rA   r#   r#   r$   __init__N   s    z/_AssertRaisesRegexWithHighlightContext.__init__c                 C   s   | S r   r#   rB   r#   r#   r$   	__enter__T   s    z0_AssertRaisesRegexWithHighlightContext.__enter__c              	   C   sH   | j | j| j |r|W 5 Q R X | jrDt | jt| dS NT)	r>   assertRaisesRegexr?   r@   rA   r	   Zcheck_source_highlightedrunstr)rB   typevalue	tracebackr#   r#   r$   __exit__W   s    z/_AssertRaisesRegexWithHighlightContext.__exit__N)__name__
__module____qualname____doc__rD   rF   rN   r#   r#   r#   r$   r=   H   s   r=   zprim::TensorExprGroupc                       s  e Zd ZdZdZG dd deZG dd deZdd Zd	d
 Z	 fddZ
 fddZd8ddZdd Zdd Zdd Zdd Zd9ddZd:ddZd;dd Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zdddd+ejfd,d-Zd.d/ Zd0dddd+ejddfd1d2Zd<d4d5Zd6d7 Z  Z S )=JitTestCaseTFc                   @   s    e Zd ZdZdd Zdd ZdS )zJitTestCase.capture_stdoutz>
        Replace sys.stdout with a temporary StringIO
        c                 C   s   t j| _t | _| jt _| S r   )sysstdout
sys_stdoutr   stringiorE   r#   r#   r$   rF   k   s    z$JitTestCase.capture_stdout.__enter__c                 G   s$   |  t| j  | `| jt_d S r   )appendrJ   rW   getvaluerV   rT   rU   rB   argsr#   r#   r$   rN   q   s    z#JitTestCase.capture_stdout.__exit__NrO   rP   rQ   rR   rF   rN   r#   r#   r#   r$   capture_stdoutg   s   r]   c                   @   s    e Zd ZdZdd Zdd ZdS )zJitTestCase.capture_stderrz>
        Replace sys.stderr with a temporary StringIO
        c                 C   s   t j| _t | _| jt _| S r   )rT   stderr
sys_stderrr   rW   rE   r#   r#   r$   rF   z   s    z$JitTestCase.capture_stderr.__enter__c                 G   s$   |  t| j  | `| jt_d S r   )rX   rJ   rW   rY   r_   rT   r^   rZ   r#   r#   r$   rN      s    z#JitTestCase.capture_stderr.__exit__Nr\   r#   r#   r#   r$   capture_stderrv   s   r`   c                 C   s   t j| j| j d S r   )r'   r1   _jit_set_emit_hooksemitModuleHookemitFunctionHookrE   r#   r#   r$   setHooks   s    zJitTestCase.setHooksc                 C   s   t jd d  d S r   )r'   r1   ra   rE   r#   r#   r$   
clearHooks   s    zJitTestCase.clearHooksc                    s.   t    tjs"tjj  dt_|   d S rG   )	supersetUprS   _restored_warningsr'   r2   ZTracerWarningZignore_lib_warningsrd   rE   	__class__r#   r$   rg      s
    
zJitTestCase.setUpc                    s   t    |   t  d S r   )rf   tearDownre   r5   rE   ri   r#   r$   rk      s    
zJitTestCase.tearDownr#   c                    s   fdddt dddddht|B  tt}|t | | t|d	kd
| t| d \}}| t|d	kd
| | t fdd|	 D d
| d S )Nc                    s   |   D ]}| |kr(||  | q| dkrH |d|| q| dkr|    dks|    dks|    dkr |  || q| D ]} ||| qqd S )Nzprim::DifferentiableGraphZSubgraphprim::Ifz	aten::allprim::TypeCheckprim::RequiresGradCheck)nodeskindrX   ginputs__next__nodeblocks)blockrp   accrt   Zinner_block)!get_nodes_and_parents_recursivelyr#   r$   rx      s    $zEJitTestCase.assertAllFused.<locals>.get_nodes_and_parents_recursivelyzprim::Constantzprim::BailoutTemplatezprim::TupleConstructrl   rm   rn   r   zgot {}r   c                 3   s   | ]}|   kV  qd S r   )rp   ).0rt   )allowed_nodesr#   r$   	<genexpr>   s     z-JitTestCase.assertAllFused.<locals>.<genexpr>)
FUSION_GROUPsetr   r6   
assertTruer9   r;   itemsallro   )rB   graphZ
except_forZfusion_groupsZfusion_nodesr#   )rz   rx   r$   assertAllFused   s"       zJitTestCase.assertAllFusedc                 C   s(   t |}d}|D ]}||kr dS qdS )N)z Could not export Python functionzclosures are not exportableTF)rJ   )rB   eseallowedar#   r#   r$   _isHookExceptionOk   s    zJitTestCase._isHookExceptionOkc                    sr   fdd}t j P zzt|jdkr:W W 5 Q R  d S t|t jjrht| dkrhW W 5 Q R  d S t	
 }t j|| | }||\}}W nD tk
r } z& |s nW Y W 5 Q R  d S W 5 d }~X Y nX t	
|}t j|}	t	
 }
t j|	|
 |
d ||
\}}t||D ]\}} || q&t|t jjrd t j||	j W 5 Q R X d S )Nc                    s   t |  tt  t   ttdd   }tdd |} fdd|D }dd |D }tdd |} fdd|D }d	d |D }||fS )
Nc                 S   s
   |  dS )Nzarchive/code/
startswithxr#   r#   r$   r+      r,   zKJitTestCase._compared_saved_loaded.<locals>.extract_files.<locals>.<lambda>c                 S   s
   |  dS )Nz.pyendswithr   r#   r#   r$   r+      r,   c                 3   s   | ]}  |V  qd S r   openry   farchiver#   r$   r{      s     zLJitTestCase._compared_saved_loaded.<locals>.extract_files.<locals>.<genexpr>c                 s   s"   | ]}d  dd |D V  qdS ) c                 S   s   g | ]}|  qS r#   )decode)ry   liner#   r#   r$   
<listcomp>   s     zWJitTestCase._compared_saved_loaded.<locals>.extract_files.<locals>.<genexpr>.<listcomp>N)join)ry   filer#   r#   r$   r{      s     c                 S   s
   |  dS )Nz
.debug_pklr   )r   r#   r#   r$   r+      r,   c                 3   s   | ]}  |V  qd S r   r   r   r   r#   r$   r{      s     c                 s   s   | ]}t |V  qd S r   )pickleloadr   r#   r#   r$   r{      s     )zipfileZipFileassertEqualr9   r}   namelistr6   filter)bufferfilesZcode_files_strZcode_files_stream
code_filesZdebug_files_strZdebug_files_streamdebug_filesrE   r   r$   extract_files   s    
 z9JitTestCase._compared_saved_loaded.<locals>.extract_filesr   )r'   Z_jit_internalZ_disable_emit_hooksr9   r    r&   r1   ZScriptModuleZ_method_namesioBytesIOr2   saverY   r:   r   r   seekzipZassertMultiLineEqualr~   Z_ivalue_tags_match_c)rB   mr   r   Zbuffer_copyr   r   r   Zbuffer2importedZsaved_module_buffer_2Zcode_files_2Zdebug_files_2r   br#   rE   r$   _compared_saved_loaded   s4    
&

z"JitTestCase._compared_saved_loadedc                 C   s&   |j dksd|j krd S | | d S )Nz<lambda>zaten::)namer   )rB   funcr#   r#   r$   rc     s    zJitTestCase.emitFunctionHookc                 C   s   |  | d S r   )r   )rB   moduler#   r#   r$   rb     s    zJitTestCase.emitModuleHookNc              	   C   s   t  }|dd  tj|| |dd  |d tjj||d}|dd  |sb|S tj	dd}z*|  ||j tjj|j|d}W 5 t
|j X |d	d  |S )
Nc                 S   s   | j dr|  S d S )N_pack)r   _has_methodr   sr#   r#   r$   r+     r,   z<JitTestCase.getExportImportCopyWithPacking.<locals>.<lambda>c                 S   s   | j dr|  S d S N_unpackr   r   r   r   r#   r#   r$   r+     r,   r   )map_locationc                 S   s   | j dr|  S d S r   r   r   r#   r#   r$   r+     r,   F)deletec                 S   s   | j dr|  S d S r   r   r   r#   r#   r$   r+   "  r,   )r   r   applyr'   r2   r   r   r   tempfileNamedTemporaryFileosunlinkr   close)rB   r   Zalso_test_filer   r   r   r   resultr#   r#   r$   getExportImportCopyWithPacking  s"    
z*JitTestCase.getExportImportCopyWithPackingc                    sd   |r8t |}| |d  }| |dk d S  fdd|}| t|dk d S )Nwith {}r   c                    sF   g }|   D ]4}|  kr&|| | D ]} || 7 }q.q|S r   ro   rp   rX   ru   rv   outrt   rp   ro   r#   r$   ro   -  s    
z.JitTestCase.assertGraphContains.<locals>.nodes)rJ   countr;   r~   r9   )rB   r   rp   consider_subgraphsstrgraphr   	out_nodesr#   r   r$   assertGraphContains%  s    	zJitTestCase.assertGraphContainsc           	         sp   dd }|rBt |}| |d  }|| ||| d S  fdd|}|| t||| d S )Nc                 S   s2   ||krd S |rdnd}t d| ||||d S )NZ	includingZ	excludingzC{}
Error: graph contains {} {} nodes ({} subgraphs) but expected {})AssertionErrorr;   )r   rp   actualexpectedr   Zsubgraphr#   r#   r$   perform_assert:  s        z>JitTestCase.assertGraphContainsExactly.<locals>.perform_assertr   c                    sF   g }|   D ]4}|  kr&|| | D ]} || 7 }q.q|S r   r   r   r   r#   r$   ro   I  s    
z5JitTestCase.assertGraphContainsExactly.<locals>.nodes)rJ   r   r;   r9   )	rB   r   rp   Znum_kind_nodesr   r   r   r   r   r#   r   r$   assertGraphContainsExactly9  s    
	z&JitTestCase.assertGraphContainsExactlyc                 O   s(   t jj|tjd}| j|f|| d S )N)Zoperator_export_type)r'   ZonnxZ_optimize_tracer   ZONNXassertExpectedGraph)rB   rq   r[   kwargsr#   r#   r$   assertExpectedONNXGraphV  s    z#JitTestCase.assertExpectedONNXGraphc                 O   sr   t |tjjr|}n| }tj| tj| tj| tj|}tj| | jt	|f|| d S r   )
r&   r'   r1   Graphr   _jit_pass_lintZ_jit_pass_dceZ_jit_pass_canonicalizeassertExpectedrJ   )rB   tracer[   r   r   r#   r#   r$   r   Z  s    zJitTestCase.assertExpectedGraphc                 C   sx   t |tjjr|}d}nd}| }tj| ttjd| |}|d k	rZt |tsZ|}tj| |rt|| |S )NFTZ
_jit_pass_)	r&   r'   r1   r   r   r   getattrbool	set_graph)rB   r   r   r   r   r   r#   r#   r$   run_passg  s    
zJitTestCase.run_passc                 C   s`   t  }|stdd}||d k r@|j}|s6td|d7 }qi }||j ||j |S )Nzfailed to inspect framer   r   zfailed to get frame)inspectcurrentframer:   f_backupdatef_locals	f_globals)rB   	frames_upframeiZdefined_varsr#   r#   r$   get_frame_varsy  s    
zJitTestCase.get_frame_varsc                 C   s   t | |||S r   )r=   )rB   rC   r@   rA   r#   r#   r$   assertRaisesRegexWithHighlight  s    z*JitTestCase.assertRaisesRegexWithHighlightr   c
              
   C   s   t   | ||L t|trR| |}
i }t||
|d |
| |
| }n|}||  W 5 Q R X | ||` t|trtjj	||d}t
||}n,tt|}tjj	||d}t
||j}||  W 5 Q R X t|ts| || tj|}||  W 5 Q R X W 5 Q R X dS )z
        Checks that a given function will throw the correct exception,
        when executed with normal python, the string frontend, and the
        AST frontend. Logic taken from `checkScript` (see comments there
        for details)
        r!   r"   Z
_frames_upN)r   rH   r&   rJ   r   r%   r   r'   r2   CompilationUnitr   textwrapdedentr   	getsourcerO   script)rB   r   rr   rC   r@   r   outputscapture_outputr   	profilingr   
the_locals	python_fncuZstring_frontendsourceger#   r#   r$   checkScriptRaisesRegex  s,    	





z"JitTestCase.checkScriptRaisesRegexc           	      C   sN   |  }t|}|j }td|D ]$}|j| || }| || q$d S Nr   )Zget_debug_stater<   r    num_bailoutsrangeZrequest_bailoutr   )	rB   modelrr   r   stateZplanr   r   Zbailout_outputsr#   r#   r$   checkBailouts  s    
zJitTestCase.checkBailoutsr   c                 C   s  t j| t  tdd |D }t|trt jj||d}| |}i }t	|||d |
| || }t||}n@tt|}| j|||j||||dd t jj|dd}|}|rtdd	 |}n|}|r^|  }|| }W 5 Q R X |  }|| }W 5 Q R X |  }|| }W 5 Q R X tsJ| j|d
 dd | j|||	|
d n@|| }|sr|rz|| }|| }tr| ||| || }| j|||	|
d | j|||	|
d |W  5 Q R  W  5 Q R  S Q R X W 5 Q R X dS )z|
        Checks that a given script generates the same output as the Python
        version using the given inputs.
        c                 s   s    | ]}t |tjo|jV  qd S r   )r&   r'   r(   requires_grad)ry   r   r#   r#   r$   r{     s     z*JitTestCase.checkScript.<locals>.<genexpr>r   r      )optimizeinputs_requires_gradr   r   r   r   c                 S   s   |    S r   )detachrequires_grad_r)   r#   r#   r$   r+     r,   z)JitTestCase.checkScript.<locals>.<lambda>r   rU   )subnameatolrtolN)r'   r2   Zoptimized_executionr   anyr&   rJ   r   r   r%   r   r   r   r   r   r   checkScriptrO   r   r0   r]   r
   r   r   r   r   )rB   r   rr   r   r  r  r   r   r   r  r  Zextra_profile_runsr   r   r   r   Zscripted_fnr   recording_inputsZscript_stdoutZscript_outputsZopt_script_stdoutZopt_script_outputsZ_python_stdoutZpython_outputsr#   r#   r$   r
    s^    






zJitTestCase.checkScripth㈵>c                    s.   fdd}|d kr|}fdd}|}|rDt dd ||}n|tjj||||
dd}|	rl| |}|rzt|j || }|| }| || | }|rtjj	||||d	}| }|rtjj	||||d	}| || |r| || | || |r| || | }||}|r>tjj	||d
|d}|rb||| }tjj	|||d	}|r~t dd ||}| }||}|rtjj	||d
|d}|r||| }tjj	|||d	}| || |r*| || t
||D ]4\}}|d kr|d krq| j||ddd q|S )Nc                    s,    d k	r| d    } t dd t| D S )Nc                 s   s0   | ](\}}|d k	rt |d |  V  qd S )Nr   )mathlogsum)ry   r   vr#   r#   r$   r{     s      z9JitTestCase.checkTrace.<locals>.allSum.<locals>.<genexpr>)r  	enumerate)vs)dropr#   r$   allSum  s    z&JitTestCase.checkTrace.<locals>.allSumc                    s     fdd t  dd g S )Nc                    sV   t tjr | n:t tr<t fdd| nt fdd| |S )Nc                    s   |  | S r   r#   )rw   key)r.   r/   input_reducer#   r$   r+   $  r,   zVJitTestCase.checkTrace.<locals>.flatten_inputs.<locals>.input_reduce.<locals>.<lambda>c                    s   | | S r   r#   )rw   val)r.   r  r#   r$   r+   &  r,   )r&   r'   r(   dictr   )r/   r.   rw   r  r-   r$   r     s    
zDJitTestCase.checkTrace.<locals>.flatten_inputs.<locals>.input_reducec                 S   s
   | | S r   )rX   )r*   rw   r#   r#   r$   r+   (  r,   z@JitTestCase.checkTrace.<locals>.flatten_inputs.<locals>.<lambda>)tuple)rr   )r  r  r$   flatten_inputs  s    z.JitTestCase.checkTrace.<locals>.flatten_inputsc                 S   s   |    S r   )cloner  r)   r#   r#   r$   r+   ,  r,   z(JitTestCase.checkTrace.<locals>.<lambda>F)check_tolerance_force_outplaceZcheck_trace)allow_unusedT)Zcreate_graphr  c                 S   s   t | ddS )NT)r   r   r)   r#   r#   r$   r+   _  r,   g-C6J?r  )r0   r'   r2   r   ZgetExportImportCopyprintr   r   autogradgradr   )rB   r   Zreference_tensorsZinput_tensorsr  r  verboseZinputs_require_gradsr  Zexport_importr  r  r  Znograd_inputsZflattened_recording_inputsr   r   Z
outputs_geZgradsZgrads_gel1l2Zgrads2Zl1_geZl2_geZ	grads2_geZg2Zg2_ger#   )r  r  r$   
checkTrace  s    
 

   zJitTestCase.checkTracec              	   C   s\   t j|}t  || }W 5 Q R X t  || }W 5 Q R X | || | || |S )zq
        Check that a nn.Module's results in Script mode match eager and that it
        can be exported
        )r'   r2   r   r   r   ZassertExportImportModule)rB   Z	nn_moduler[   smZ	eager_outZ
script_outr#   r#   r$   checkModulev  s    zJitTestCase.checkModule)r#   )TN)F)F)NNFFTr  TF)!rO   rP   rQ   Z_do_cuda_memory_leak_checkrh   r6   r]   r`   rd   re   rg   rk   r   r   r   rc   rb   r   r   r   r   r   r   r   r   r   Z	PROFILINGr   r   r
  r&  r(  __classcell__r#   r#   ri   r$   rS   c   s^   

	>


   
*
P            
hrS   c                   @   s   e Zd Zdd Zdd ZdS )NoTracerWarnContextManagerc                 C   s   t j | _t jd d S NF)r'   r1   Z_jit_get_tracer_state_warnprev_jit_set_tracer_state_warnrE   r#   r#   r$   rF     s    z$NoTracerWarnContextManager.__enter__c                 G   s   t j| j d S r   )r'   r1   r-  r,  rZ   r#   r#   r$   rN     s    z#NoTracerWarnContextManager.__exit__N)rO   rP   rQ   rF   rN   r#   r#   r#   r$   r*    s   r*  c              	   c   s4   t j }t j|  z
d V  W 5 t j| X d S r   )r'   r1   Z_jit_get_inline_everything_modeZ_jit_set_inline_everything_mode)Zshould_inlineoldr#   r#   r$   inline_everything_mode  s
    

r/  c              	   c   s4   t j }t j|  z
d V  W 5 t j| X d S r   )r'   r1    _debug_get_fusion_group_inlining _debug_set_fusion_group_inlining)Zinliningr.  r#   r#   r$   set_fusion_group_inlining  s
    

r2  Tc              	   c   s,   t j|   z
d V  W 5 t jd X d S rG   )r'   r1   Z%_debug_set_autodiff_subgraph_inlining)Zenabledr#   r#   r$   "disable_autodiff_subgraph_inlining  s    
r3  c                    s   t   fdd}|S )Nc               	      s"   t d  | | W 5 Q R X d S rG   r/  r[   r   r.   r#   r$   wrapper  s    
z#_inline_everything.<locals>.wrapper	functoolswrapsr.   r7  r#   r6  r$   _inline_everything  s    r<  c                    s   t   fdd}|S )Nc               	      s"   t d  | | W 5 Q R X d S r+  r4  r5  r6  r#   r$   r7    s    
z5_tmp_donotuse_dont_inline_everything.<locals>.wrapperr8  r;  r#   r6  r$   $_tmp_donotuse_dont_inline_everything  s    r=  c                     s    fdd}|S )Nc                    s   t jj|  fS r   )r'   r2   r   )r   r5  r#   r$   r7    s    z_trace.<locals>.wrapperr#   )r[   r   r7  r#   r5  r$   _trace  s    r>  c                    s    fdd}|S )Nc               	      s^   t jd t jd t jd z | | W 5 t jd t jd t jd X d S NTF)r'   r1   Z$_jit_override_can_fuse_on_cpu_legacy_jit_override_can_fuse_on_cpu_jit_set_te_must_use_llvm_cpur5  r6  r#   r$   r7    s    z!enable_cpu_fuser.<locals>.wrapperr#   r;  r#   r6  r$   enable_cpu_fuser  s    
rB  c                 C   s   | rt S dd }|S d S )Nc                    s    fdd}|S )Nc                     s
    | |S r   r#   r5  r6  r#   r$   r7    s    z8enable_cpu_fuser_if.<locals>.noop_fuser.<locals>.wrapperr#   r;  r#   r6  r$   
noop_fuser  s    z'enable_cpu_fuser_if.<locals>.noop_fuser)rB  )ZcondrC  r#   r#   r$   enable_cpu_fuser_if  s    rD  c                 C   s
   |  dS NZforward)_get_methodcr#   r#   r$   get_forward  s    rI  c                 C   s   |  djS rE  )rF  r   rG  r#   r#   r$   get_forward_graph  s    rJ  c                 C   s   | j ||S r   )r   r   rF  )r   r   methodr#   r#   r$   get_module_method  s    rL  c                    s    fdd| j j D S )Nc                    s   g | ]\}}|  r|qS r#   r   )ry   r   _prefixr#   r$   r     s    
z%attrs_with_prefix.<locals>.<listcomp>)Z_modulesr   r   )r   rO  r#   rN  r$   attrs_with_prefix  s    rP  c                 G   sP   d}g }t |D ]:}t|dkr>tjj| f| }|| q| jdd q|S )N   r   T)Zretain_graph)r   r9   r'   r!  r"  rX   Zbackward)r   r[   Zprofiling_countresultsr   rr#   r#   r$   warmup_backward  s    rT  c                  G   s$   | D ]}t tj|j |j| qd S r   )setattrrT   modulesrP   rO   )r[   argr#   r#   r$   make_global  s    rX  c           	   
   C   s   t  }tj|d}t|d}||  W 5 Q R X tj	||}tj
|}|j}t|tsft|| t||}|W  5 Q R  S Q R X d S )Nz	script.pyw)r   TemporaryDirectoryr   pathr   r   write	importlibutilspec_from_file_locationmodule_from_specloaderr&   r   r   exec_moduler   )	r    fn_nameZtmp_dirZscript_pathr   specr   ra  r.   r#   r#   r$   _get_py3_code  s    


re  c                   @   s   e Zd Zdd Zdd ZdS )TensorExprTestOptionsc                 C   s   t jd| _t jd| _t j | _t j | _	t j
d t jd t j | _t jd t j | _t jd t j | _t jd t jd| _d S r?  )r'   r1   _jit_set_profiling_executorold_profiling_executor_get_graph_executor_optimizeold_profiling_modeZ_jit_can_fuse_on_cpuold_cpu_fuser_stateZ_jit_can_fuse_on_gpuold_gpu_fuser_stater@  _jit_override_can_fuse_on_gpuZ_jit_texpr_fuser_enabledtexpr_fuser_state_jit_set_texpr_fuser_enabledr0  old_fusion_inliningr1  Z_jit_get_te_must_use_llvm_cpuold_te_must_use_llvm_cpurA  _jit_set_nvfuser_enabledold_nvfuserrE   r#   r#   r$   rD     s    zTensorExprTestOptions.__init__c                 C   st   t j| j t j| j t j| j t j| j	 t j
| j t j| j t j| j t j| j d S r   )r'   r1   rg  rh  ri  rj  ro  rn  rm  rl  r@  rk  r1  rp  rA  rq  rr  rs  rE   r#   r#   r$   restore  s    zTensorExprTestOptions.restoreN)rO   rP   rQ   rD   rt  r#   r#   r#   r$   rf    s   rf  c                 C   sZ   g }| D ]L}t |tjr,||   qt|rJ|dd |D  q|| q|S )Nc                 S   s   g | ]}|   qS r#   )r  r  )ry   r*   r#   r#   r$   r   *  s     z clone_inputs.<locals>.<listcomp>)r&   r'   r(   rX   r  r  r   )r[   rr   rW  r#   r#   r$   clone_inputs#  s    ru  c              	      sN  g }  | |}  }  }||d} jdk}|rJdttj ji}ddgdddgdddgdd	d
gdddgdddgdddgdg}	|r|S |D ]}
| D ]\}}|d krqt|rqt	 fdd|	}|D ]X}|d D ]J}t
|
j}t|
j|kr*t|
j| tr*t|| ||< t||
_qq|||
f qq|S )N)functionrK  )Zresize_Z
resize_as_rK  Zdiv_floor_roundingr   )r   arg_idxZdiv_no_rounding_modeZdiv_trunc_roundingZ
index_fillr   Z	full_likemulZnew_fullr   c                    s    j | d kS )Nr   )Zformatted_namer   opr#   r$   r+   s  r,   z1get_traced_sample_variant_pairs.<locals>.<lambda>rw  )Zsample_inputsZget_op
get_methodr   r   r'   r(   r   	is_lambdar   r6   r[   r9   r&   r   intr  rX   )ZdeviceZdtyperz  r   Zsamplesr   rK  variantsZhas_fake_functionZops_with_unsupported_bool_argssampleZ	func_typevariantZmatching_opsZop_dataidxr[   r#   ry  r$   get_traced_sample_variant_pairs0  sb     
 
"r  c                 C   s"   dd }t | t|o | j|jkS )Nc                   S   s   dS r   r#   r#   r#   r#   r$   r+     r,   zis_lambda.<locals>.<lambda>)r&   rK   rO   )ZlambZLAMBDAr#   r#   r$   r|    s    r|  )T)`Ztorch.autogradr   Ztorch.autograd.functionr   Ztorch.jit.annotationsr   r   Z
torch.onnxr   r'   Z
torch.cudaZ	torch.jitZtorch.jit._loggingZtorch.jit.frontendZtorch.jit.quantizedr   r9  Ztorch.testingr	   Z$torch.testing._internal.common_utilsr
   r   r   r   r   r   Z"torch.testing._internal.common_jitr   r   
contextlibr   r   r   r   collectionsr   Zimportlib.utilr]  r   r  r   r   rT   r   r   importlib.abcr   typingr   r   r   r   r   ZcudaZis_availableZRUN_CUDAZdevice_countZRUN_CUDA_MULTI_GPUZRUN_CUDA_HALFversionZhipr1   Z_cuda_getCompiledVersionZCUDA_VERSIONr   dZget_device_capabilitymajorr%   r0   r5   r<   objectr=   r|   rS   r*  r/  r2  r3  r<  r=  r>  rB  rD  rI  rJ  rL  rP  rT  rX  re  rf  ru  r  r|  r#   r#   r#   r$   <module>   s    


    )

		
P