a
    HSic                     @   s<  U 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Zddl	m
Z
mZmZmZmZ ddlmZmZ ddlmZmZ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 ej j!Z"ej j#Z$d=ddZ%d>ddZ&G dd dej'jZ(dd Z)ej*+ddZ,ej*+ddZ-ej*+ddZ.ej/d?ddZ0ej1dfddZ2dd Z3dd Z4G d d! d!e5Z6e7 d"d# Z8G d$d% d%e9Z:e:;  ej <  d&d' Z=d(d) Z>d*d+ Z?dddd,dddefd-d.Z@dZAeee
e
f  eBd/< dddd,dddefd0d1ZCd2d3 ZDG d4d5 d5eZEG d6d7 d7eEZFd8d9 ZGd@d;d<ZHdS )AzTracing

This module contains functionality to support the JIT's tracing frontend, notably:
    * torch.jit.trace
    * torch.jit.trace_module

This is not intended to be imported directly; please use the exposed
functionalities in `torch.jit`.
    N)AnyDictListOptionalSet)
_python_cu_enabled)ScriptModule_CachedForwardscript)_qualified_nameis_scriptingget_callable_argument_names)function)Module)default_tolerances   c                    s    fdd}|S )Nc                    s   t  }|stdd}| d k r@|j}|s6td|d7 }q|j}|j}| D ]0\}}t|tj	rT| |u rT|dkr||nd  S qTdS )Nzfailed to inspect framer   r   zfailed to get frameself )
inspectcurrentframeRuntimeErrorf_backf_locals	f_globalsitems
isinstancetorchTensor)varframeir   r   kv	frames_up L/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/jit/_trace.py_get_interpreter_name_for_var"   s    
zI_create_interpreter_name_lookup_fn.<locals>._get_interpreter_name_for_varr&   )r%   r(   r&   r$   r'   "_create_interpreter_name_lookup_fn!   s    r)   Fc                 C   sh   | j dd}t| }t }| D ]>\}}t||v r:q$|t| |rV|||< q$| ||< q$|S )NT	keep_vars)
state_dicttypesetr   idadddetach)moduler+   r,   Zfiltered_dictZseen_idsr"   r#   r&   r&   r'   _unique_state_dict9   s    

r3   c                       s.   e Zd Zd fdd	ZejdddZ  ZS )	ONNXTracedModuleTFc                    s0   t t|   || _|| _|| _|| _|| _d S N)superr4   __init__innerstrict_force_outplace_return_inputs_return_inputs_states)r   r8   r9   force_outplacereturn_inputsZreturn_inputs_states	__class__r&   r'   r7   L   s    zONNXTracedModule.__init__argsc                    s   t |\ ttdd }g g g  fdd}tj|| t jj	\}}j
r||d d fS jr|d d fS |d fS d S )NTr*   c                     s   g }t tD ]*}t| | tjs,td|| |  qt| }tdd | D  j	rtt|  j
|  j	rd |fd< t\}}t|dkr|d S t|S d S )NzExpected Tensor argumentc                 s   s   | ]}|j tjd V  qdS )memory_formatN)cloner   preserve_format).0xr&   r&   r'   	<genexpr>r       z<ONNXTracedModule.forward.<locals>.wrapper.<locals>.<genexpr>r   r   )rangelenr   r   r   r   append
_unflattentupler<   r8   _flatten)rB   in_argsr!   Ztrace_inputsout_vars_Zin_descin_varsZinputs_statesoutsZ
ret_inputsr   r&   r'   wrapperh   s$    
z)ONNXTracedModule.forward.<locals>.wrapperr   )rP   listr3   valuesr   _C_create_graph_by_tracingr)   r9   r:   r;   r<   )r   rB   Zmodule_staterW   graphoutr&   rT   r'   forward^   s$    zONNXTracedModule.forward)TFFF)__name__
__module____qualname__r7   r   r   r^   __classcell__r&   r&   r?   r'   r4   K   s       r4   c                    s$    fdd t jdd  dd| S )Nc                    sh   | d u rd S t | tjrV|  j| jr*d ntjd| j}| j	d urR |j	|_	|S | jtjdS d S )NrC   )
r   r   r   r1   rE   	is_mkldnnrF   requires_grad_requires_gradgrad)ar#   clone_inputr&   r'   ri      s    
z"_clone_inputs.<locals>.clone_inputc                 S   s   t | tjS r5   r   r   r   rH   r&   r&   r'   <lambda>   rJ   z_clone_inputs.<locals>.<lambda>tensors)condition_msg)r   _nested_maprA   r&   rh   r'   _clone_inputs   s    
rp   ZPYTORCH_JIT_TIMEZPYTORCH_JIT_DISABLEZPYTORCH_JIT_STATSTc                 c   s   t s|rtj sd V  d S tj }tjjdd}tjjdd}|| z4d V  W || |  td	| ||
| n,|| |  td	| ||
| 0 d S )NT)enable_timingz{} {} time: {} ms)	_JIT_TIMEr   cudais_availablecurrent_streamEventrecord_eventsynchronizeprintformatelapsed_time)
trace_namenametimestreamstartendr&   r&   r'   _time   s    



r   c                    s   t tjjstdt t t |ts0|f}t|} rJt	
 }d fdd	}tjj|dd. ||dd\}}j| sJ W d	   n1 s0    Y   r| ||dd
\}	}
t||	 t||
 d	S )aB  
    Verify that a JIT compiled model has the same behavior as its uncompiled
    version along with its backwards pass.  If your model returns multiple
    outputs, you must also specify a `loss_fn` to produce a loss for which
    the backwards will be computed.

    This function has side-effects (e.g., it executes your model / saves and loads
    parameters), so don't expect the model to come out exactly the same as what
    you passed in.

    Args:
        model (compiled torch.nn.Module or function): the module/function to be
            verified.  The module/function definition MUST have been decorated with
            `@torch.jit.compile`.
        args (tuple or Tensor): the positional arguments to pass to the
            compiled function/module to be verified.  A non-tuple is assumed to
            be a single positional argument to be passed to the model.
        loss_fn (function, optional): the loss function to be applied to
            the output of the model, before backwards is invoked.  By default,
            we assume that a model returns a single result, and we :func:`torch.sum`
            before calling backwards; if this is inappropriate, you can pass your
            own loss function.  Note that if a model returns a tuple of results,
            these are passed as separate positional arguments to `loss_fn`.
        devices (iterable of device IDs, optional): the GPU devices which the
            compiled module will be run on.  This determines the RNG state we
            must save when running both compiled and uncompiled versions of the model.
    zICannot verify an uncompiled module.  Add @torch.jit.compile to compile itFc                    s    rt  ng }t| |f\}}}|r4|  |r>|j}|  }|r\|j|kr\tdt|tsl|f}tj	krt
|dkrtdt
|t|\}	}dd |	D }
| }tj|g|}dd |D }|
|fS )Nz#failed to use the compiled functionr   z_Model returns {} outputs, but default loss function (torch.sum) can only handle a single outputc                 S   s   g | ]}|  jtjd qS rC   r1   rE   r   rF   rG   r#   r&   r&   r'   
<listcomp>  s   z/verify.<locals>.run_fwd_bwd.<locals>.<listcomp>c                 S   s   g | ]}|  jtjd qS r   r   r   r&   r&   r'   r     s   )rX   
parametersrP   clear_cachehitsr   r   rO   r   sumrL   
ValueErrorrz   autogradrf   )rB   force_traceassert_compiledparamsrU   rS   compiled_fnr   r]   rR   Z
saved_outslossgradsZsaved_gradsZ	is_moduleloss_fnmodelr&   r'   run_fwd_bwd   s:    
zverify.<locals>.run_fwd_bwdztorch.jit.verify)_callerT)r   N)r   )FF)r   r   rZ   ZCompiledFunction	TypeErrorr   rO   rp   copydeepcopyr,   randomfork_rngZhas_trace_forload_state_dict_verify_equal)r   rB   r   devicesZ
saved_argssaved_stater   Zuncompiled_outsZuncompiled_gradsZcompiled_outsZcompiled_gradsr&   r   r'   verify   s&    "

!,

r   c                 C   s6   t | |D ]&\}}||  dkr
tdq
d S )Ngư>z!JIT and real computation mismatch)zipsubabsmaxr   )xsysrH   yr&   r&   r'   r     s    r   c                 C   s   d dd |  D S )N
c                 S   s   g | ]}d | qS )	r&   )rG   liner&   r&   r'   r     rJ   zindent.<locals>.<listcomp>)join
splitlines)sr&   r&   r'   indent  s    r   c                       s   e Zd Zd fdd	Z  ZS )TracingCheckErrorNc                    s   d| _ |d ur |  j |d 7  _ |d urL|  j d7  _ |  j t|d 7  _ |d urx|  j d7  _ |  j t|d 7  _ tt| | j  d S )NzTracing failed sanity checks!
r   z+ERROR: Graphs differed across invocations!
zERROR: Tensor-valued Constant nodes differed in value across invocations. This often indicates that the tracer has encountered untraceable code.
)messager   r6   r   r7   )r   Zgraph_diff_errorZtensor_compare_error	extra_msgr?   r&   r'   r7   #  s    zTracingCheckError.__init__)N)r_   r`   ra   r7   rb   r&   r&   r?   r'   r   "  s   r   c              
      sl  | D ]`}t |tjr|f}|ri }	| D ]\}
}t||	|
< q,tjjt|drX|jn||	d|||tj	
 d}|jj |j }t |tjtfr|f}n tjj|t|d|||d}|  fdddd fd	d
}dgfddfdd}||d}|||d}|||drF| |d}|||d  }tdd |D rt| qd S )N__self__F)check_tracer9   r:   _module_class_compilation_unit)r   r9   r:   r   c                     s  t jj} t j|  t j|  t| }tdd|}t j j}t j| t j| t|}tdd|}d }||krxdd l	}|
|d|d}dtd| d }t|  | D ]\}}t|t|kr|d7 }|
t|dt|d}	dtd|	 d }
| }|rF|
d	t| d 7 }
| }|rh|
d
t| d 7 }
||
7 } qxqd }t|  | D ]:\}}| | kr q| dkr| s| s|dsq|ddks|ddkrq|d}|d}zt jj||dd W n ttfy } zx|d u rTd}|dtt| d 7 }| }|r|dt| d 7 }|dtt| 7 }W Y d }~ qW Y d }~n
d }~0 0 q||fS )Nz___torch_mangle_[0-9]+\.r   r   TzGraph diff:
r   zFirst diverging operator:
zNode diff:
zTrace source location:
zCheck source location:
zprim::Constantvaluet)	equal_nanzNode:
zSource Location:
zComparison exception: )r   rZ   _jit_pass_canonicalizer\   _jit_pass_inline!_jit_pass_erase_shape_informationstrrer   difflibndiffr   r   r   r   nodessourceRangekind
mustBeNonehasAttributekindOfr   testingassert_closer   AssertionError)Zmod_canonicalizedmod_strZcheck_canonicalizedZ	check_strgraph_diff_errorsr   Z
graph_diffZn_modZn_checkZ	node_diffZsource_printoutZ	mod_stackZcheck_stacktensor_compare_errorsZmod_tensor_valZcheck_tensor_valeZcompare_stack)check_mod_functraced_funcr&   r'   graph_diagnostic_infob  s    
 


*z+_check_trace.<locals>.graph_diagnostic_infoc                 S   s   t | tr| S | fS r5   )r   rO   rk   r&   r&   r'   wrap_retval  s    z!_check_trace.<locals>.wrap_retvalc              
      s   z$| t | }dd |D }|W S  tyz } z>  \}}d| dtt| }t|||d|W Y d }~n
d }~0 0 d S )Nc                 S   s   g | ]}t |tjr|qS r&   rj   )rG   r]   r&   r&   r'   r     rJ   zK_check_trace.<locals>.run_mod_and_filter_tensor_outputs.<locals>.<listcomp>z+encountered an exception while running the z with test inputs.
Exception:
)r   )rp   	Exceptionr   r   r   )modinputsZrunning_whatrV   r   r   r   msg)r   r   r&   r'   !run_mod_and_filter_tensor_outputs  s    
z7_check_trace.<locals>.run_mod_and_filter_tensor_outputsc                     s|    d rd S d d< dd j  D } t| dkrxd}|d7 }|ddd | D d d	 7 }|d
7 }tj|tdd d S )Nr   Tc                 S   s   g | ]}|  r|qS r&   )isNondeterministicrG   opr&   r&   r'   r     s   zE_check_trace.<locals>.maybe_warn_nondeterministic.<locals>.<listcomp>z"Trace had nondeterministic nodes. z2Did you forget call .eval() on your model? Nodes:
r   c                 S   s   g | ]}t t|qS r&   )r   r   r   r&   r&   r'   r     rJ      zp
This may cause errors in trace checking. To disable trace checking, pass check_trace=False to torch.jit.trace()   category
stacklevel)r\   r   rL   r   warningswarnTracerWarning)Znondeterm_opsZnondeterministic_ops_warning)
has_warnedr   r&   r'   maybe_warn_nondeterministic  s(    z1_check_trace.<locals>.maybe_warn_nondeterministicc                    s.  d}t t| |D ]\}\}}z|jr0| }|jr>| }|jrL| }|jrZ| }| sj| rtjj	|
tj|
tj t||d dd n(tjj	| |  t||d dd W q ty& } zF  tjdt|d  d | d t| tdd d	}W Y d }~qd }~0 0 q|S )
NTr   )rtolatolr   z
Output nr zH. of the traced function does not match the corresponding output of the z. Detailed error:
   r   F)	enumerater   is_quantized
dequantizerc   to_dense
is_complexr   r   r   tocdoubler   doubler   r   r   r   r   )original	referenceZ
match_whatall_okr!   origrefr   )check_tolerancer   r&   r'   compare_outputs  sZ    



z%_check_trace.<locals>.compare_outputstracezPython functionzrepeated tracec                 s   s   | ]}|d uV  qd S r5   r&   )rG   infor&   r&   r'   rI     rJ   z_check_trace.<locals>.<genexpr>)r   r   r   r   rp   jittrace_modulehasattrr   rZ   CompilationUnit_c_get_methodr}   dictr   anyr   )check_inputsfuncr   r   r9   r=   Zis_trace_moduler   r   Zcopied_dictr}   dataZ	check_modr   r   Ztraced_outsZfn_outsZ
check_outsZ	diag_infor&   )r   r   r   r   r   r   r   r'   _check_trace5  sZ    
	
T-r  c                   @   s   e Zd Zedd ZdS )r   c                   C   s   t jdtdd d S )Nignoreztorch.(?!jit))r   r2   )r   filterwarningsr   r&   r&   r&   r'   ignore_lib_warnings  s    z!TracerWarning.ignore_lib_warningsN)r_   r`   ra   staticmethodr  r&   r&   r&   r'   r     s   r   c                 C   s,   t | tjtfr| fS t | ts(t| S | S r5   )r   r   r   r   rO   )example_inputsr&   r&   r'   
make_tuple)  s
    
r	  c                 C   sV   t | tr| S tj| r:tjjj}tjjj| |dddS |d u rFt	}|| |dS d S )NFTshare_types
is_tracingr   )
r   r	   r   _jit_internalmodule_has_exportsr   
_recursive make_stubs_from_exported_methodscreate_script_moduleTopLevelTracedModule)r   r   r   Zinfer_methods_stubs_fnr&   r&   r'   make_module2  s    

r  c                 C   s   | d u rd S dd | D S )Nc                 S   s   g | ]}d |iqS )r^   r&   )rG   cr&   r&   r'   r   H  rJ   z%wrap_check_inputs.<locals>.<listcomp>r&   )r   r&   r&   r'   wrap_check_inputsD  s    r  gh㈵>c
              
   C   sf  t s| S |durtd t| tjjr6td | S t| tjjrdt	| d|id|t
|||||	S t| drt| jtjjr| jdkrt	| jd|id|t
|||||	S t|tjtfr|f}nt|tst|}td}
t| drt| jtjjrtdt| }tj|| ||
||t| }|rb|durJt|| ||||d| nt|g| ||||d| |S )	a+  
    Trace a function and return an executable  or :class:`ScriptFunction`
    that will be optimized using just-in-time compilation. Tracing is ideal for
    code that operates only on ``Tensor``\s and lists, dictionaries, and
    tuples of ``Tensor``\s.

    Using `torch.jit.trace` and `torch.jit.trace_module`, you can turn an
    existing module or Python function into a TorchScript
    :class:`ScriptFunction` or :class:`ScriptModule`. You must provide example
    inputs, and we run the function, recording the operations performed on all
    the tensors.

    * The resulting recording of a standalone function produces `ScriptFunction`.
    * The resulting recording of `nn.Module.forward` or `nn.Module` produces
      `ScriptModule`.

    This module also contains any parameters that the original
    module had as well.

    Warning:
        Tracing only correctly records functions and modules which are not data
        dependent (e.g., do not have conditionals on data in tensors) and do not have
        any untracked external dependencies (e.g., perform input/output or
        access global variables). Tracing only records operations done when the given
        function is run on the given tensors. Therefore, the returned
        `ScriptModule` will always run the same traced graph on any input. This
        has some important implications when your module is expected to run
        different sets of operations, depending on the input and/or the module
        state. For example,

        * Tracing will not record any control-flow like if-statements or loops.
          When this control-flow is constant across your module, this is fine
          and it often inlines the control-flow decisions. But sometimes the
          control-flow is actually part of the model itself. For instance, a
          recurrent network is a loop over the (possibly dynamic) length of an
          input sequence.
        * In the returned :class:`ScriptModule`, operations that have different
          behaviors in ``training`` and ``eval`` modes will always behave as if
          it is in the mode it was in during tracing, no matter which mode the
          `ScriptModule` is in.

        In cases like these, tracing would not be appropriate and
        :func:`scripting <torch.jit.script>` is a better choice. If you trace
        such models, you may silently get incorrect results on subsequent
        invocations of the model. The tracer will try to emit warnings when
        doing something that may cause an incorrect trace to be produced.

    Args:
        func (callable or torch.nn.Module):  A Python function or `torch.nn.Module`
            that will be run with `example_inputs`. `func` arguments and return
            values  must be tensors or (possibly nested) tuples that contain
            tensors. When a module is passed `torch.jit.trace`, only the
            ``forward`` method is run and traced (see :func:`torch.jit.trace
            <torch.jit.trace_module>` for details).
        example_inputs (tuple or torch.Tensor):  A tuple of example inputs that
            will be passed to the function while tracing. The resulting trace
            can be run with inputs of different types and shapes assuming the
            traced operations support those types and shapes. `example_inputs`
            may also be a single Tensor in which case it is automatically
            wrapped in a tuple.

    Keyword arguments:
        check_trace (``bool``, optional): Check if the same inputs run through
            traced code produce the same outputs. Default: ``True``. You might want
            to disable this if, for example, your network contains non-
            deterministic ops or if you are sure that the network is correct despite
            a checker failure.

        check_inputs (list of tuples, optional): A list of tuples of input
            arguments that should be used to check the trace against what is
            expected. Each tuple is equivalent to a set of input arguments that
            would be specified in ``example_inputs``. For best results, pass in
            a set of checking inputs representative of the space of shapes and
            types of inputs you expect the network to see.  If not specified,
            the original ``example_inputs`` are used for checking
        check_tolerance (float, optional): Floating-point comparison tolerance
            to use in the checker procedure.  This can be used to relax the
            checker strictness in the event that results diverge numerically
            for a known reason, such as operator fusion.
        strict (``bool``, optional): run the tracer in a strict mode or not
            (default: ``True``). Only turn this off when you want the tracer to
            record your mutable container types (currently ``list``/``dict``)
            and you are sure that the container you are using in your
            problem is a ``constant`` structure and does not get used as
            control flow (if, for) conditions.

    Returns:
        If `func` is `nn.Module` or ``forward`` of `nn.Module`, `trace` returns
        a :class:`ScriptModule` object with a single ``forward`` method
        containing the traced code.  The returned `ScriptModule` will
        have the same set of sub-modules and parameters as the original
        ``nn.Module``.  If ``func`` is a standalone function, ``trace``
        returns `ScriptFunction`.

    Example (tracing a function):

    .. testcode::

        import torch

        def foo(x, y):
            return 2 * x + y

        # Run `foo` with the provided inputs and record the tensor operations
        traced_foo = torch.jit.trace(foo, (torch.rand(3), torch.rand(3)))

        # `traced_foo` can now be run with the TorchScript interpreter or saved
        # and loaded in a Python-free environment

    Example (tracing an existing module)::

        import torch
        import torch.nn as nn

        class Net(nn.Module):
            def __init__(self):
                super(Net, self).__init__()
                self.conv = nn.Conv2d(1, 1, 3)

            def forward(self, x):
                return self.conv(x)

        n = Net()
        example_weight = torch.rand(1, 1, 3, 3)
        example_forward_input = torch.rand(1, 1, 3, 3)

        # Trace a specific method and construct `ScriptModule` with
        # a single `forward` method
        module = torch.jit.trace(n.forward, example_forward_input)

        # Trace a module (implicitly traces `forward`) and construct a
        # `ScriptModule` with a single `forward` method
        module = torch.jit.trace(n, example_forward_input)

    N]`optimize` is deprecated and has no effect. Use `with torch.jit.optimized_execution() insteadz`The input to trace is already a ScriptModule, tracing it is a no-op. Returning the object as is.r^   r   r   zVtrace doesn't support compiling individual module's functions.
Please use trace_moduleF)r   r   r   r   r   r   r	   nnr   r   r  r   r   r_   r   r   rO   r)   AttributeErrorr   rZ   _create_function_from_tracer   r  )r  r  optimizer   r   r   r9   r:   r   r   var_lookup_fnr}   Ztracedr&   r&   r'   r   K  s     

r   _trace_module_mapc
              
      s\  t s| S |durtd td}
t| tjjs8tdt|t	sJtdtj
jj}zi  fdd | d< tj
j_ | d t| ||	}| D ]\}}|d	kr| }t| |}t|}nt| |}t|}t|}|j||||
||| |j|}|r|dur$t||||||d
| qt|g|||||d
| qW |tj
j_n|tj
j_0 |S )a$  
    Trace a module and return an executable :class:`ScriptModule` that will be optimized
    using just-in-time compilation. When a module is passed to :func:`torch.jit.trace <torch.jit.trace>`, only
    the ``forward`` method is run and traced. With ``trace_module``, you can specify a dictionary of
    method names to example inputs to trace (see the ``inputs``) argument below.

    See :func:`torch.jit.trace <torch.jit.trace>` for more information on tracing.

    Args:
        mod (torch.nn.Module):  A ``torch.nn.Module`` containing methods whose names are
                                specified in ``inputs``. The given methods will be compiled
                                as a part of a single `ScriptModule`.
        inputs (dict):  A dict containing sample inputs indexed by method names in ``mod``.
                                The inputs will be passed to methods whose names correspond to inputs'
                                keys while tracing.
                                ``{ 'forward' : example_forward_input, 'method2': example_method2_input}``
    Keyword arguments:
        check_trace (``bool``, optional): Check if the same inputs run through
                                      traced code produce the same outputs. Default: ``True``. You might want
                                      to disable this if, for example, your network contains non-
                                      deterministic ops or if you are sure that the network is correct despite
                                      a checker failure.

        check_inputs (list of dicts, optional): A list of dicts of input arguments that should be used
                                                 to check the trace against what is expected. Each tuple
                                                 is equivalent to a set of input arguments that would
                                                 be specified in ``inputs``. For best results, pass in a
                                                 set of checking inputs representative of the space of
                                                 shapes and types of inputs you expect the network to see.
                                                 If not specified, the original ``inputs`` are used for checking
        check_tolerance (float, optional): Floating-point comparison tolerance to use in the checker procedure.
                                           This can be used to relax the checker strictness in the event that
                                           results diverge numerically for a known reason, such as operator fusion.

    Returns:
        A :class:`ScriptModule` object with a single ``forward`` method containing the traced code.
        When ``func`` is a ``torch.nn.Module``, the returned :class:`ScriptModule` will have the same set of
        sub-modules and parameters as ``func``.

    Example (tracing a module with multiple methods)::

        import torch
        import torch.nn as nn

        class Net(nn.Module):
            def __init__(self):
                super(Net, self).__init__()
                self.conv = nn.Conv2d(1, 1, 3)

            def forward(self, x):
                return self.conv(x)

            def weighted_kernel_sum(self, weight):
                return weight * self.conv.weight


        n = Net()
        example_weight = torch.rand(1, 1, 3, 3)
        example_forward_input = torch.rand(1, 1, 3, 3)

        # Trace a specific method and construct `ScriptModule` with
        # a single `forward` method
        module = torch.jit.trace(n.forward, example_forward_input)

        # Trace a module (implicitly traces `forward`) and construct a
        # `ScriptModule` with a single `forward` method
        module = torch.jit.trace(n, example_forward_input)

        # Trace specific methods on a module (specified in `inputs`), constructs
        # a `ScriptModule` with `forward` and `weighted_kernel_sum` methods
        inputs = {'forward' : example_forward_input, 'weighted_kernel_sum' : example_weight}
        module = torch.jit.trace_module(n, inputs)

    Nr  r   z.expected torch.nn.Module as the first argumentz3expected a dictionary of (method_name, input) pairsc                    s4   |   D ]&\}}|d | }||<  || qd S )N.)named_children)r   prefixr}   childZsubmod_qualnameregister_submodsZtrace_module_mapr&   r'   r#    s    z&trace_module.<locals>.register_submodsZ__moduler^   T)r   r   r   r)   r   r   r  r   r  r   r   _tracer  r  r   getattrr   r	  r   _create_method_from_tracer   r  )r   r   r  r   r   r   r9   r:   r   r   r  Zold_module_mapr2   method_namer  r  Zforward_methodargument_namesZcheck_trace_methodr&   r"  r'   r   D  sz    V






	
r   c                   C   s   t  r
dS tj S )z
    Returns ``True`` in tracing (if a function is called during the tracing of
    code with ``torch.jit.trace``) and ``False`` otherwise.
    F)r   r   rZ   _is_tracingr&   r&   r&   r'   r    s    r  c                       sR   e Zd ZdZd fdd	Zdd Z fddZ fd	d
Zdd Zdd Z	  Z
S )TracedModuleTNc                    s  t t|   t|tjjs J t  G dd dtjj}tj	t
||_| } fdd}|j|_|j D ]"\}}|d urp||j|< || qp|j D ]"\}}	|	d ur|	|j|< ||	 q|j D ]4\}}
tj|
r||jvr||jvrt|||
 q|jrtdt| |j D ],\}}|d u r:q$t|td d|j|< q$tjjj|dd d	d
d}t
|j| jd< || jd< dD ]}t| | qd S )Nc                   @   s   e Zd ZdS )z.TracedModule.__init__.<locals>.QualnameWrapperN)r_   r`   ra   r&   r&   r&   r'   QualnameWrapper
  s   r+  c                    s   |  v rt d |  d S )Nz=TracedModules don't support parameter sharing between modules)r   r0   )paramid_setr&   r'   check_unique  s
    z+TracedModule.__init__.<locals>.check_uniquez=Modules that have backward hooks assigned can't be compiled: r  c                 S   s   dS )Nr&   r&   )r2   r&   r&   r'   rl   9  rJ   z'TracedModule.__init__.<locals>.<lambda>FTr
  _name_actual_script_module)_parameters_buffers_modulestraining)r6   r*  r7   r   r   r  r   r.   r  r   r-   _jit_override_qualnamer5  r2  r   r3  __dict__rZ   _jit_is_script_objectsetattr_backward_hooksr   r   r4  r  r   r  r  r_   delattr)r   r   r.  r   r+  Z
tmp_moduler/  r}   r,  bufval	submodulescript_moduler?   r-  r'   r7     sZ    






zTracedModule.__init__c                 O   s   t dd S )Nz"Trace submodules cannot be called.)r   )r   rB   kwargsr&   r&   r'   r^   A  s    zTracedModule.forwardc                    s&   d| j vrtt| |S t| j|S Nr1  )r7  r6   r*  __getattr__r%  r1  )r   attrr?   r&   r'   rB  D  s    
zTracedModule.__getattr__c                    s.   d| j vrtt| ||S t| j|| d S rA  )r7  r6   r*  __setattr__r9  r1  )r   rC  r   r?   r&   r'   rD  I  s    
zTracedModule.__setattr__c                 C   s   | j S r5   )r0  r   r&   r&   r'   	_get_nameN  s    zTracedModule._get_namec                 C   s   d | jS )Nzoriginal_name={})rz   r0  rE  r&   r&   r'   
extra_reprQ  s    zTracedModule.extra_repr)NN)r_   r`   ra   _disable_script_metar7   r^   rB  rD  rF  rG  rb   r&   r&   r?   r'   r*    s   Dr*  c                   @   s   e Zd Ze Zdd ZdS )r  c                 C   s   | j d | dS )z
        Re-construct an instance of TopLevelTracedModule using an instance of a C++ module.

        Args:
            cpp_module: The C++ module that this TopLevelTracedModule will be rebuilt around.
        r1  N)r7  _reconstruct)r   
cpp_moduler&   r&   r'   rI  X  s    z!TopLevelTracedModule._reconstructN)r_   r`   ra   r
   r^   rI  r&   r&   r&   r'   r  U  s   r  c                    s(   t   fdd _d_S )Nc                     s,   t  s | i |S tj}|| i |S r5   )r  r   __original_fn)rB   r@  r   fnrW   r&   r'   rW   c  s    
z#_script_if_tracing.<locals>.wrapperT)	functoolswrapsrK  __script_if_tracing_wrapper)rM  r&   rL  r'   _script_if_tracingb  s
    rQ  r&   c                 C   s:   |du ri }t |ts|f}t| |||||i |}|S )a  
    .. warning::
        This function is internal-only and should only be used by the ONNX
        exporter. If you are trying to get a graph through tracing, please go
        through the public API instead::

            trace = torch.jit.trace(nn.LSTMCell(), (input, hidden))
            trace_graph = trace.graph

    Trace a function or model, returning a tuple consisting of the both the
    *trace* of an execution, as well as the original return value. If return_inputs,
    also returns the trace inputs as part of the tuple

    Tracing is guaranteed not to change the semantics of the function/module
    that is traced.

    Args:
        f (torch.nn.Module or function): the function or module
            to be traced.
        args (tuple or Tensor): the positional arguments to pass to the
            function/module to be traced.  A non-tuple is assumed to
            be a single positional argument to be passed to the model.
        kwargs (dict): the keyword arguments to pass to the function/module
            to be traced.

    Example (trace a cell):

    .. testcode::

        trace = torch.jit.trace(nn.LSTMCell(), (input, hidden))
    N)r   rO   r4   )frB   r@  r9   r:   r>   r<   rV   r&   r&   r'   _get_trace_graphr  s    !
rS  )r   )F)T)r&   NTFFF)I__doc__r   r   os
contextlibrN  r   r   r   typingr   r   r   r   r   Ztorch.jit._stater   r   torch.jit._scriptr	   r
   r   torch._jit_internalr   r   r   torch.autogradr   torch.nnr   Ztorch.testing._comparisonr   rZ   _jit_flattenrP   _jit_unflattenrN   r)   r3   r  r4   rp   environgetrr   Z_JIT_DISABLEZ
_JIT_STATScontextmanagerr   r   r   r   r   r   r   no_gradr  Warningr   r  _tracer_warn_use_pythonr	  r  r  r   r  __annotations__r   r  r*  r  rQ  rS  r&   r&   r&   r'   <module>   s   	

D\
 e
	

 w
 -
[  