a
    àñh7{  ã                   @   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mZmZm	Z	m
Z
 d dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZmZ e dd¡Ze d	d
¡Zg d¢Zdd„ Zdd„ Zdd„ Zee e!e"e#dƒej$ej%ej&fZ'dd„ Z(G dd„ dej)j*j+ƒZ,d?dd„Z-G dd„ de.ƒZ/e/ƒ Z0dd„ Z1d@dd„Z2dAdd „Z3d!d"„ Z4d#d$„ Z5d%d&„ Z6d'd(„ Z7d)d*„ Z8d+d,„ Z9d-d.„ Z:d/d0„ Z;d1d2„ Z<d3d4„ Z=d5d6„ Z>d7d8„ Z?d9d:„ Z@d;d<„ ZAd=d>„ ZBdS )Bé    N)ÚDictÚListÚSetÚType)Úget_default_argsÚget_jit_defÚget_class_properties)Ú_find_builtin)ÚModule)Úget_function_from_typeÚbind_methodÚScriptMethodStub)Úresolution_callbackÚdef_Úoriginal_methodZProperty)r   r   )Ú_versionÚ_parametersÚ_buffersÚ_modulesÚ_initializingZ_backward_hooksZ_forward_hooksZ_forward_pre_hooksZ_state_dict_hooksZ_load_state_dict_pre_hooksZdump_patchesc                 C   s$   t  | ¡}t| |dd�}t||| ƒS ©NÚRecursiveScriptModule©Z	self_name)Ú_jit_internalÚ#createResolutionCallbackFromClosurer   r   )ÚfuncÚnameÚrcbÚast© r   úT/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torch/jit/_recursive.pyÚ	make_stub#   s    
r!   c                 C   s"   t | |ƒ}t|tƒr|S t||ƒS ©N)ÚgetattrÚ
isinstancer   r!   )Ú	nn_moduleÚmethod_namer   r   r   r    Úmake_stub_from_method(   s    

	r'   c                 C   sD   g }t | ƒD ]2}t| |d ƒ}t |¡tjju r| t| |ƒ¡ q|S r"   )Údirr#   r   Úget_torchscript_modifierÚFunctionModifiersÚEXPORTÚappendr'   )ÚmodÚstubsr   Úitemr   r   r    Ú make_stubs_from_exported_methods7   s    ÿÿr0   c              	      sv   t |tƒr|S t |tƒs"t |tƒr:t‡ ‡fdd„|D ƒƒS d dd„ tD ƒ¡}tt d t	 
t|ƒ¡ˆˆ |¡¡ƒ‚d S )Nc                 3   s   | ]}t ˆ |ˆƒV  qd S r"   )Ú_get_valid_constant)Ú.0Úx©ÚattrÚ
owner_typer   r    Ú	<genexpr>N   ó    z&_get_valid_constant.<locals>.<genexpr>z, c                 s   s   | ]}t  |¡V  qd S r"   )ÚtorchÚtypename)r2   Útypr   r   r    r7   O   r8   zÇ
        '{}' object in attribute '{}.{}' is not a valid constant.
        Valid constants are:
        1. a nn.ModuleList
        2. a value of type {{{}}}
        3. a list or tuple of (2)
        )r$   Ú_constant_typesÚtupleÚlistÚjoinÚ	TypeErrorÚtextwrapÚdedentÚformatr9   r:   Útype)r5   Úvr6   Ú	constantsr   r4   r    r1   J   s    

úr1   c                       s   e Zd Z‡ fdd„Z‡  ZS )ÚSourceContextc                    s   t t| ƒ ||||¡ d S r"   )ÚsuperrG   Ú__init__)ÚselfÚsourceÚfilenameZfile_linenoZleading_whitespace_len©Ú	__class__r   r    rI   Z   s    zSourceContext.__init__)Ú__name__Ú
__module__Ú__qualname__rI   Ú__classcell__r   r   rM   r    rG   Y   s   rG   Tc                    sþ  t j t| ƒ¡}t| t jjƒr&| ¡  t| t jjt jj	fƒrD| 
¡  t| di ƒ‰ ‡ fdd„}tƒ }| j ¡ D ]D\}}|du sŒt|t jƒsŒJ ‚|||ƒ}| ||dd¡ | |¡ ql| j ¡ D ]D\}}|du sÜt|t jƒsÜJ ‚|||ƒ}| ||dd¡ | |¡ q¼| j ¡ D ]z\}}|||ƒ}|du �r<| ||dd¡ �q|du�rd| ¡ �sTJ ‚t jj |¡}n
t||ƒ}| ||¡ | |¡ �qt| dtƒ ƒ}	ˆ  ¡ D ]"\}}
t j |
¡�rž|	 |¡ �qž|	D ]²}||v �r(|| jv �ræd}n,|| jv �rød	}n|| jv �r
d
}ntdƒ‚t d ||¡¡ �qÆt| |ƒ�sHt d |¡¡ �qÆt| |ƒ}|  |t!||t| ƒj"ƒ¡ | |¡ �qÆt| di ƒ}| #t$t%| ƒƒ¡ | ¡ D ]\}}| &||¡ �q | j' ¡ D �]4\}}|t(v �sÂ| )d¡�ræ�qÂ||v �rô�qÂt* +|¡�rhz&t j, -|¡}| .|t j /|¡|¡ W n< t0�yb } z"d |¡}| 1||¡ W Y d}~n
d}~0 0 �qÂt2|ƒ}|�r†| 3||¡ �qÂt|t j,j4ƒ�r°| .|t j /|¡|¡ �qÂ|||ƒ}|du�rÖ| ||dd¡ n d t  5t|ƒ¡¡}| 1||¡ �qÂ|S )z²
    Build a ConcreteModuleTypeBuilder from an nn.Module. This
    ConcreteModuleType doesn't have a JIT type associated with it yet, it
    must be filled in by the caller.
    Ú__annotations__c                    sn   | ˆ v r8ˆ |  t jjjd kr8t jj ˆ |  t ¡ ¡}n2t	|t jj
ƒr^t jj |jt ¡ ¡}nt j |¡}|S )NÚforward)r9   Únnr
   rS   ÚjitÚannotationsZann_to_typer   Ú
fake_ranger$   Ú	AttributerD   Ú_CÚ_jit_try_infer_type)r   r/   Ú	attr_type©Zclass_annotationsr   r    Ú
infer_typem   s    z/infer_concrete_type_builder.<locals>.infer_typeNTFZ__constants__Ú	submoduleÚbufferZ	parameterz3added_names must be submodule, parameter, or bufferz]'{}' was found in ScriptModule constants,  but it is a non-constant {}. Consider removing it.ze'{}' was found in ScriptModule constants, but was not actually set in __init__. Consider removing it.Ú__overloads__Ú__zš(This function exists as an attribute on the Python module, but we failed to compile it to a TorchScript function. 
The error stack is reproduced here:
{}zo(This attribute exists on the Python module, but we failed to convert Python type: '{}' to a TorchScript type.))6r9   rZ   ZConcreteModuleTypeBuilderrD   r$   rU   Ú
ModuleDictZset_module_dictÚ
ModuleListÚ
SequentialZset_module_listr#   Úsetr   ÚitemsZTensorZadd_attributeÚaddr   r   Zis_interface_typeÚConcreteModuleTypeÚfrom_jit_typeÚget_module_concrete_typeZ
add_moduler   Úis_finalÚAssertionErrorÚwarningsÚwarnrC   ÚhasattrZadd_constantr1   rO   ÚupdateÚget_overload_name_mappingÚget_overload_annotationsZadd_overloadÚ__dict__Úignored_attributesÚ
startswithÚinspectÚ
isfunctionrV   ÚscriptZadd_function_attributer[   Ú	ExceptionZadd_failed_attributer	   Zadd_builtin_functionZScriptFunctionr:   )r%   Úshare_typesÚconcrete_type_builderr^   Zadded_namesr   r/   r\   Úsub_concrete_typeZconstants_setÚannÚhintÚvalueÚ	overloadsZoverloaded_namesZscripted_fnÚeZbuiltin_symbol_namer   r]   r    Úinfer_concrete_type_builder^   sÂ    






ÿþ


ýþ
ý

þrƒ   c                   @   sJ   e Zd ZU eee eejj	 f e
d< eejj	 e
d< dd„ Zdd„ ZdS )ÚConcreteTypeStoreÚ
type_storeÚmethods_compiledc                 C   s   i | _ tƒ | _d S r"   )r…   rf   r†   )rJ   r   r   r    rI   	  s    zConcreteTypeStore.__init__c                 C   sf   t |ƒ}t|ƒ}|| jvr$g | j|< | j| }|D ]}| |¡r2|  S q2| ¡ }| j|  |¡ |S )z|
        Infer a ConcreteType from this `nn.Module` instance. Underlying JIT
        types are re-used if possible.
        )rƒ   rD   r…   ÚequalsÚbuildr,   )rJ   r%   r|   Znn_module_typeZknown_typesZ
known_typeÚconcrete_typer   r   r    Úget_or_create_concrete_type  s    




z-ConcreteTypeStore.get_or_create_concrete_typeN)rO   rP   rQ   r   r   r
   r   r9   rZ   ri   rS   r   rI   rŠ   r   r   r   r    r„     s   
r„   c                 C   s\   dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}dd„ |D ƒ}|   |||||¡ d S )Nc                 S   s   g | ]
}|j ‘qS r   ©r   ©r2   Úmr   r   r    Ú
<listcomp>)  r8   z<create_methods_and_properties_from_stubs.<locals>.<listcomp>c                 S   s   g | ]
}|j ‘qS r   ©r   rŒ   r   r   r    rŽ   *  r8   c                 S   s   g | ]}t |jƒ‘qS r   )r   r   rŒ   r   r   r    rŽ   +  r8   c                 S   s   g | ]
}|j ‘qS r   r‹   ©r2   Úpr   r   r    rŽ   -  r8   c                 S   s   g | ]
}|j ‘qS r   r�   r�   r   r   r    rŽ   .  r8   )Z_create_methods_and_properties)r‰   Úmethod_stubsÚproperty_stubsZmethod_defsZmethod_rcbsZmethod_defaultsZproperty_defsZproperty_rcbsr   r   r    Ú(create_methods_and_properties_from_stubs(  s    r”   c                 C   sZ   t | tƒsJ ‚t | tjjƒr,t| dƒr,| jS |r<t | ¡}nt	| |ƒ}| 
¡  | ¡ }|S )aÜ  
    Gets a concrete type for nn_modules. If share_types is True, the concrete
    type is fetched from concrete_type_store. If it is False, a new concrete type
    is created without first searching concrete_type_store.

    Arguments:
        nn_module:  The original Python nn.Module that we are creating a ScriptModule for.
        share_types = Whether to share underlying JIT types between modules (if possible).

    Returns:
        A concrete type for nn_module.
    Ú_concrete_type)r$   r
   r9   rV   ÚScriptModulerp   r•   Úconcrete_type_storerŠ   rƒ   Zset_poisonedrˆ   )r%   r{   r‰   r|   r   r   r    rk   3  s    ÿ
rk   c                 C   s0   t | tjjƒrJ ‚t| ƒ t| |ƒ}t| ||ƒS )ah  
    Creates a new ScriptModule from an nn.Module

    Arguments:
        nn_module:  The original Python nn.Module that we are creating a ScriptModule for.
        stubs_fn:  Lambda that takes an nn.Module and generates a list of ScriptMethodStubs to compile.
        share_types:  Whether to share underlying JIT types between modules (if possible).
            NOTE: Only set to False this when we cannot guarantee type sharing will work
                correctly. This only happens today for traced modules, where the same
                module can produce different traced methods depending on the inputs.
    )r$   r9   rV   r   Úcheck_module_initializedrk   Úcreate_script_module_impl)r%   Ústubs_fnr{   r‰   r   r   r    Úcreate_script_moduleQ  s    
r›   c                    sö  t j ˆ j¡‰ˆˆƒ}tˆƒ}‡ ‡‡‡fdd„}t jj ˆ|¡}ˆ tj	vrnt
ˆ ||ƒ t j ˆ¡ tj	 ˆ ¡ tˆt jjt jjt jjfƒrªdˆ ¡ vrª| d tˆƒ¡¡ tˆt jjƒrüdˆ ¡ vrütˆ ¡ ƒròttˆ ¡ ƒƒ}| d |¡¡ n
| d¡ |D ]X}|jdu �r�q |jj}	|	|j ¡ jk�r2�q ˆ |	¡}
t |j¡|
ƒ}||j |	< �q |D ]V}|j ¡ j}ˆ |j !¡ j¡}|j "¡ }|�rœˆ |j¡nd}t#|||ƒ|j |< �q^t$ˆƒD ]2}	t%ˆ|	dƒ}t& '|¡t&j(j)u �r¾t*|ˆ|	ƒ �q¾|S )	aW  
    Convert an nn.Module to a RecursiveScriptModule.

    Arguments:
        nn_module:  The original Python nn.Module that we are creating a ScriptModule for.
        concrete_type:  The fully initialized ConcreteType of the module.
        stubs_fn:  Lambda that takes an nn.Module and generates a list of ScriptMethodStubs to compile.
    c                    s2  ˆ   ¡  ¡ D ]:\}\}}tˆ|ƒ}t|tjjƒr6|jn|}ˆ ||¡ qˆ  	¡ D ]„\}}tˆ|ƒ}t|t
ƒs~J d t|ƒ¡ƒ‚|j}t|tjjƒržt||ƒ}n t|tjjƒr²|}nt||ˆƒ}ˆ ||¡ || j|< qPtˆƒD ]H}tˆ|d ƒ}t |¡rÞt |¡rÞttˆƒ|ƒ}	|	 | ¡}
t| ||
ƒ qÞˆ | _d S )NzExpected Module but got {})Zget_attributesrg   r#   r$   r9   rV   rY   r€   ÚsetattrZget_modulesr
   rC   rD   Újit_typerZ   ZInterfaceTypeÚinterface_scriptr–   r™   r   r(   rw   Úismethodr   Úis_ignored_fnÚ__get__r•   )Úscript_moduler   r\   Zis_paramZ
orig_valuer}   Úmodule_typeZscriptedr/   Zunbound_functionZbound_method©r‰   Ú
cpp_moduler%   rš   r   r    Úinit_fno  s,    


z*create_script_module_impl.<locals>.init_fnÚ__len__z def __len__(self):
   return {}
Ú__contains__z6def __contains__(self, key: str):
   return key in {}
z2def __contains__(self, key: str):
   return False
N)+r9   rZ   Z_create_module_with_typer�   Úget_property_stubsrV   r   Ú
_constructr—   r†   r”   Z_run_emit_module_hookrh   r$   rU   rd   re   rc   Z_method_namesZdefinerC   ÚlenÚkeysÚreprr>   r   rO   r   r   Z_get_methodÚ	functoolsÚwrapsrt   Zgetter_nameÚsetter_nameÚpropertyr(   r#   r   r)   r*   ZCOPY_TO_SCRIPT_WRAPPERÚ!add_python_attr_to_scripted_model)r%   r‰   rš   r’   r“   r¦   r¢   r¬   Zmethod_stubr   Zscript_methodZwrapped_script_methodZproperty_stubZproperty_nameÚfgetr°   Úfsetr/   r   r¤   r    r™   b  sP    	'

ÿ
ÿ


r™   c                 C   s:   t | |d ƒ}|d u rdS ttjj|ƒ}|d u r2dS ||kS )NF)r#   r   r9   rV   r   )Úscript_modelr5   Zscript_attrZdefault_attrr   r   r    Úscript_model_defines_attrÚ  s    r¶   c                 C   s*   t ||ƒr&t| |ƒr&t| |t||ƒƒ d S r"   )rp   r¶   rœ   r#   )rµ   Úorigr5   r   r   r    r²   ã  s    r²   c                    sˆ   i }t t| ƒƒD ]r‰ t| ˆ d ƒ}t|ƒs*qt|dƒr|jd urt || j¡}|d u rVq‡ fdd„t	t
|ƒƒD ƒ}tt||ƒƒ||< q|S )NrP   c                    s   g | ]}ˆ d  t |ƒ ‘qS )rb   )Ústr)r2   Úi©r   r   r    rŽ   ö  r8   z,get_overload_annotations.<locals>.<listcomp>)r(   rD   r#   Úcallablerp   rP   r   Z_get_overloaded_methodsrN   Úranger«   r>   Úzip)r-   r�   r/   Zmethod_overloadsÚnamesr   rº   r    rs   ç  s    rs   c                 C   sL   i }|   ¡ D ]:\}}|j}||vr*g ||< |D ]\}}||  |¡ q.q|S r"   )rg   rO   r,   )Úoverload_infoÚoverload_name_mappingsÚorig_fnr�   Úoriginal_nameÚoverload_nameÚ_r   r   r    rr   û  s    rr   c                 C   sB   t jj | d t ¡ t | ¡¡}|d u r>t | ¡}t	d 
|¡ƒ‚d S )Nz@Must explicitly add type annotations to overloaded functions: {})r9   rV   rW   Zget_signaturer   rX   rw   rŸ   Z_qualified_nameÚRuntimeErrorrC   )r   Ú	signatureZ	qual_namer   r   r    Ú_check_no_signature  s    
rÇ   c           
      C   s€   g }|   ¡ D ]n\}}t||jdd�}|D ]P\}}t|ƒ t||jdd�}tj | ¡ ||¡}t 	|¡}	| 
t|	||ƒ¡ q(q|S r   )rg   r   rO   rÇ   r9   rZ   Z_replace_overloaded_method_declÚdeclr   r   r,   r   )
r¿   Úoverload_stubsrÁ   r�   Zorig_astrÃ   Zoverload_fnZover_astZnew_astÚ_rcbr   r   r    Úmake_stubs_for_overloads  s    
rË   c                 C   s8   t | tjjƒsJ ‚t| dƒs4td t t| ƒ¡¡ƒ‚d S )Nr   z@'{}' has not been initialized, did you forget to call 'super()'?)	r$   r9   rU   r
   rp   rÅ   rC   r:   rD   )r-   r   r   r    r˜     s
    
ÿr˜   c                    s2  t | ƒ g }t| dƒrLt | j¡sLt| jddƒ}ttjj	dƒ}||krLdg}g }t
| ƒD ],}t| |dƒ}t |¡tjju rX| |¡ qX|| }tt| di ƒƒ‰ t| ƒ}ˆ  t|ƒ¡ t|ƒ}ˆ | _‡ fdd„}	t|	|ƒ}
tƒ }g }|
D ]"}||v rôqæ| |¡ | |¡ qæg }|D ]}| t| |ƒ¡ �q|| S )zš
    Implements the default rules for which methods should act as starting
    points for compilation (TODO add a link when the rules are published).
    rT   Ú__func__Nra   c                    s   | ˆ vS r"   r   )r&   ©rÀ   r   r    Úignore_overloaded>  s    z3infer_methods_to_compile.<locals>.ignore_overloaded)r˜   rp   r   r    rT   r#   r   r9   rU   r
   r(   r)   r*   r+   r,   Údictrs   rq   rr   rË   ra   Úfilterrf   rh   r'   )r%   ÚmethodsZforward_funcZmodule_forwardZexportedr   r/   r¿   rÉ   rÎ   Zfiltered_methodsZuniquerZuniqued_methodsr.   Úmethodr   rÍ   r    Úinfer_methods_to_compile   s>    

rÓ   c                    s€   t | ƒ}t|dd�}i ‰ t|ƒD ]H}t||dƒ}t|tƒr |jsXtd|› d| j› d�ƒ‚t	 
|j¡ˆ |< q ‡ fdd„|D ƒ}|S )	zx
    Create property stubs for the properties of the module by creating method
    stubs for the getter and setter.
    r   r   Nz	Property z of z must have a getterc                    s    g | ]}t ˆ | ¡ j |ƒ‘qS r   )ÚPropertyStubr   )r2   r   ©Zrcbsr   r    rŽ   d  r8   z&get_property_stubs.<locals>.<listcomp>)rD   r   r(   r#   r$   r±   r³   rÅ   rO   r   r   )r%   Z	module_tyZproperties_astsr   r/   r.   r   rÕ   r    r©   S  s    
r©   c                    s0   t |tjjƒr|S t|ƒ ‡ fdd„}t||ƒS )a*  
    Makes a ScriptModule from an nn.Module, using the interface methods rule for
    determining which methods to compile.

    Arguments:
        mod_interface: the interface type that the module have
        nn_module:  The original Python nn.Module that we are creating a ScriptModule for.
    c                    s&   g }ˆ   ¡ D ]}| t| |ƒ¡ q|S )z‘
        Rule to infer the methods from the interface type to know which
        methods need to act as starting points for compilation.
        )ZgetMethodNamesr,   r'   )r%   r.   rÒ   ©Úmod_interfacer   r    Ú"infer_interface_methods_to_compilev  s    z<interface_script.<locals>.infer_interface_methods_to_compile)r$   r9   rV   r–   r˜   r›   )r×   r%   rØ   r   rÖ   r    rž   h  s
    	
rž   c                 C   s^   t  | ¡rd S t| tjjƒr d S t | ¡sDt | ¡sDt	d 
| | ¡ƒ‚t  | ¡}tjj| |d�S )Nzš`{}` is not a function. Recursive scripting only supports Python functions or methods currently.
Consider manually annotating `{}` with @torch.jit.script.)rÊ   )r   r    r$   r9   rU   r
   rw   rx   rŸ   rÅ   rC   r   rV   ry   )ÚfnÚlocr   r   r   r    Útry_compile_fn‚  s    
þ
rÛ   c                 C   s   dd„ }t jj | |¡S )zb
    Wrap this torch._C.ScriptModule in a Python ScriptModule, recursively for all submodules
    c                 S   sF   t j | j¡ ¡ D ]\}}t| |t|ƒƒ qt jj | j 	¡ ¡| _
d S r"   )r9   rZ   rc   Z_crg   rœ   Úwrap_cpp_moduleri   rj   Ú_typer•   )r¢   r   r¥   r   r   r    r¦   ›  s    z wrap_cpp_module.<locals>.init_fn)r9   rV   r   rª   )r¥   r¦   r   r   r    rÜ   —  s    rÜ   c                 C   sV   t  |¡rd S t||jƒ}tj  ¡ � t| |fdƒ W d   ƒ n1 sH0    Y  |S )Nr   )r   r    r!   rO   r9   Z_disable_emit_hooksr”   )r‰   rÙ   Zstubr   r   r    Úcompile_unbound_method¡  s    
,rÞ   c                    s.   ‡ ‡fdd„}ˆ|_ ˆj|_tj ˆ|¡ |S )zé
    Returns a function that lazily binds `unbound_method` to a provided
    Module IValue, then invokes the method. We do this so that any Python
    shenanigans that will poison type sharing are impossible at compile
    time.
    c                    s4   ‡ fdd„}t jj | |¡}tˆ|t jjƒ}||Ž S )Nc                    s\   ˆ j }t|ƒD ]&}t||d ƒ}t |¡rt| ||ƒ qˆ  ¡  ¡ D ]\}}t| ||ƒ qBd S r"   )Zpy_classr(   r#   r   r    rœ   Zget_constantsrg   )r¢   Z
orig_classr   r/   r€   )r‰   r   r    r¦   ³  s    
z7lazy_bind.<locals>.lazy_binding_method.<locals>.init_fn)r9   rV   r   rª   r   )r¥   Úargsr¦   r¢   rÒ   ©r‰   Úunbound_methodr   r    Úlazy_binding_method²  s    z&lazy_bind.<locals>.lazy_binding_method)Zoriginal_fnrO   r9   r   Zcopy_torchscript_modifier)r‰   rá   râ   r   rà   r    Ú	lazy_bind«  s
    rã   )T)T)T)Crw   r9   ÚcollectionsrA   r®   rn   Útypingr   r   r   r   Ztorch._jit_internalr   Ztorch.jit.frontendr   r   r   Ztorch.jit._builtinsr	   Ztorch.nnr
   Z
torch._sixr   r   Ú
namedtupler   rÔ   ru   r!   r'   r0   ÚboolÚfloatÚintr¸   rD   ZdeviceZlayoutZdtyper<   r1   rZ   Z_jit_tree_viewsZSourceRangeFactoryrG   rƒ   Úobjectr„   r—   r”   rk   r›   r™   r¶   r²   rs   rr   rÇ   rË   r˜   rÓ   r©   rž   rÛ   rÜ   rÞ   rã   r   r   r   r    Ú<module>   sT   
 ( 

x	3

