U
    dH                    @   s  U d dl mZm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
  mZ d dlmZmZmZ d dlmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZ eeed	f ef Zed
ddZG dd dedddgZ dd Z!e Z"ee#ef e$d< da%ee& e$d< e Z'ee#ef e$d< e Z(ee#ef e$d< dZ)ed edddZ*ed edddZ+edeegedef f eddd Z,edeegedef f edd!d"Z-edd#d$d%Z.G d&d dZ/dS )'    )OrderedDict
namedtupleN   )	Parameter)Tensordevicedtype)UnionTupleAnyCallableIteratorSetOptionaloverloadTypeVarMappingDictList   )RemovableHandle.TModuleboundc                       s    e Zd Z fddZeZ  ZS )_IncompatibleKeysc                    s   | j s| jsdS tt|  S )Nz<All keys matched successfully>)missing_keysunexpected_keyssuperr   __repr__self	__class__ ;/tmp/pip-unpacked-wheel-ua33x9lu/torch/nn/modules/module.pyr      s    z_IncompatibleKeys.__repr__)__name__
__module____qualname__r   __str____classcell__r$   r$   r"   r%   r      s   r   ZIncompatibleKeysr   r   c                    sP   |  d}t|dkr| S |d} fdd|D }d|}|d | }|S )N
   r   c                    s   g | ]} d  | qS ) r$   ).0line	numSpacesr$   r%   
<listcomp>#   s     z_addindent.<locals>.<listcomp>)splitlenpopjoin)Zs_r1   sfirstr$   r0   r%   
_addindent   s    


r9   _global_backward_hooks_global_is_full_backward_hook_global_forward_pre_hooks_global_forward_hooksZ_extra_state.Nhookreturnc                 C   s   t t}| t|j< |S )a  Registers a forward pre-hook common to all modules.

    .. warning ::

        This adds global state to the `nn.module` module
        and it is only intended for debugging/profiling purposes.

    The hook will be called every time before :func:`forward` is invoked.
    It should have the following signature::

        hook(module, input) -> None or modified input

    The input contains only the positional arguments given to the module.
    Keyword arguments won't be passed to the hooks and only to the ``forward``.
    The hook can modify the input. User can either return a tuple or a
    single modified value in the hook. We will wrap the value into a tuple
    if a single value is returned(unless that value is already a tuple).

    This hook has precedence over the specific module hooks registered with
    ``register_forward_pre_hook``.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )hooksr   r<   idr@   handler$   r$   r%    register_module_forward_pre_hook4   s    

rF   c                 C   s   t t}| t|j< |S )a  Registers a global forward hook for all the modules

    .. warning ::

        This adds global state to the `nn.module` module
        and it is only intended for debugging/profiling purposes.

    The hook will be called every time after :func:`forward` has computed an output.
    It should have the following signature::

        hook(module, input, output) -> None or modified output

    The input contains only the positional arguments given to the module.
    Keyword arguments won't be passed to the hooks and only to the ``forward``.
    The hook can modify the output. It can modify the input inplace but
    it will not have effect on forward since this is called after
    :func:`forward` is called.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``

    This hook will be executed before specific module hooks registered with
    ``register_forward_hook``.
    )rB   r   r=   rC   rD   r$   r$   r%   register_module_forward_hookT   s    

rG   c                 C   s,   t dkrtdda tt}| t|j< |S )a  Registers a backward hook common to all the modules.

    This function is deprecated in favor of
    :func:`torch.nn.modules.module.register_module_full_backward_hook`
    and the behavior of this function will change in future versions.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``

    TtCannot use both regular backward hooks and full backward hooks as a global Module hook. Please use only one of them.Fr;   RuntimeErrorrB   r   r:   rC   rD   r$   r$   r%   register_module_backward_hooks   s    

rK   c                 C   s,   t dkrtdda tt}| t|j< |S )a  Registers a backward hook common to all the modules.

    .. warning ::
        This adds global state to the `nn.module` module
        and it is only intended for debugging/profiling purposes.

    The hook will be called every time the gradients with respect to module
    inputs are computed. The hook should have the following signature::

        hook(module, grad_input, grad_output) -> Tensor or None

    The :attr:`grad_input` and :attr:`grad_output` are tuples. The hook should
    not modify its arguments, but it can optionally return a new gradient with
    respect to the input that will be used in place of :attr:`grad_input` in
    subsequent computations. :attr:`grad_input` will only correspond to the inputs given
    as positional arguments and all kwarg arguments will not appear in the hook. Entries
    in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor
    arguments.

    For technical reasons, when this hook is applied to a Module, its forward function will
    receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
    of each Tensor returned by the Module's forward function.

    Global hooks are called before hooks registered with `register_backward_hook`

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``

    FrH   TrI   rD   r$   r$   r%   "register_module_full_backward_hook   s    #

rL   )inputrA   c                 G   s   t dt| j ddS )a  Defines the computation performed at every call.

    Should be overridden by all subclasses.

    .. note::
        Although the recipe for forward pass needs to be defined within
        this function, one should call the :class:`Module` instance afterwards
        instead of this since the former takes care of running the
        registered hooks while the latter silently ignores them.
    zModule [z,] is missing the required "forward" functionN)NotImplementedErrortyper&   )r!   rM   r$   r$   r%   _forward_unimplemented   s    rP   c                   @   sz  e Zd ZU dZdZeed< dZeed< eed< e	e ed< dd	d
dZ
eZedef ed< dee	e eddddZee	e ddddZee	d  ddddZee	d  ddddZed dddZeddddZed dd!d"Zed	d#d$Zed%d&d'Zd(d) Zeed gdf ed*d+d,Zdee	eeef  ed-d.d/Z dee	eeef  ed-d0d1Z!dee	eeef  ed-d2d3Z"eed4d5d6Z#eee$ef ed7d8d9Z%eed4d:d;Z&eed4d<d=Z'eed4d>d?Z(eed4d@dAZ)eeeef ed-dBdCZ*e+dee	eeef  e	ee$ef  eedDdEdFZ,e+deee$ef eedGdHdFZ,e+deeeedIdJdFZ,dKdF Z,ed e-e-gedef f e.dLdMdNZ/ed e-e-gedef f e.dLdOdPZ0dQdR Z1dSdT Z2edU e.dLdVdWZ3edU e.dLdXdYZ4dZd[ Z5d\d] Z6e6Z7edef ed^< d_d` Z8eeed f dadbdcZ9eeed f ddddedfZ:dgdh Z;didj Z<dkdl Z=e>dme?eef dnZ@e+dddoe@eee@dpdqdrZAe+dddoeee?eef dsdtdrZAdduddvdwdrZAddxdyZBdzd{ ZCd|d} ZDdeEeef ed~ddZFdddZGdeeHe dddZIdeeeHeJeef  dddZKdeeHe dddZLdeeeHeJeef  dddZMeHd  d	ddZNeHeJed f  d	ddZOeHd  d	ddZPde	eQd   eedddZRdeeedddZSeed4ddZTdeeedddZUdeddddZVeed4ddZWdd ZXed	ddZYdd ZZdd Z[dd Z\dS )r   a$  Base class for all neural network modules.

    Your models should also subclass this class.

    Modules can also contain other Modules, allowing to nest them in
    a tree structure. You can assign the submodules as regular attributes::

        import torch.nn as nn
        import torch.nn.functional as F

        class Model(nn.Module):
            def __init__(self):
                super().__init__()
                self.conv1 = nn.Conv2d(1, 20, 5)
                self.conv2 = nn.Conv2d(20, 20, 5)

            def forward(self, x):
                x = F.relu(self.conv1(x))
                return F.relu(self.conv2(x))

    Submodules assigned in this way will be registered, and will have their
    parameters converted too when you call :meth:`to`, etc.

    .. note::
        As per the example above, an ``__init__()`` call to the parent class
        must be made before assignment on the child.

    :ivar training: Boolean represents whether this module is in training or
                    evaluation mode.
    :vartype training: bool
    Fdump_patchesr,   _versiontraining_is_full_backward_hookN)rA   c                 C   sl   t jd d| _t | _t | _t | _t | _	d| _
t | _t | _t | _t | _t | _t | _dS )z_
        Initializes internal Module state, shared by both nn.Module and ScriptModule.
        zpython.nn_moduleTN)torch_CZ_log_api_usage_oncerS   r   _parameters_buffersset_non_persistent_buffers_set_backward_hooksrT   _forward_hooks_forward_pre_hooks_state_dict_hooks_load_state_dict_pre_hooks_load_state_dict_post_hooks_modulesr    r$   r$   r%   __init__   s    zModule.__init__.forwardT)nametensor
persistentrA   c                 C   s   |dkrt | tjjrtdd| jkr2tdnt |tjjsVt	d
t|nd|krhtdn|dkrztd	nxt| |r|| jkrtd

|nT|dk	rt |tjst	d
t||n(|| j|< |r| j| n| j| dS )a  Adds a buffer to the module.

        This is typically used to register a buffer that should not to be
        considered a model parameter. For example, BatchNorm's ``running_mean``
        is not a parameter, but is part of the module's state. Buffers, by
        default, are persistent and will be saved alongside parameters. This
        behavior can be changed by setting :attr:`persistent` to ``False``. The
        only difference between a persistent buffer and a non-persistent buffer
        is that the latter will not be a part of this module's
        :attr:`state_dict`.

        Buffers can be accessed as attributes using given names.

        Args:
            name (string): name of the buffer. The buffer can be accessed
                from this module using the given name
            tensor (Tensor or None): buffer to be registered. If ``None``, then operations
                that run on buffers, such as :attr:`cuda`, are ignored. If ``None``,
                the buffer is **not** included in the module's :attr:`state_dict`.
            persistent (bool): whether the buffer is part of this module's
                :attr:`state_dict`.

        Example::

            >>> self.register_buffer('running_mean', torch.zeros(num_features))

        Fz4ScriptModule does not support non-persistent buffersrX   z2cannot assign buffer before Module.__init__() callz&buffer name should be a string. Got {}.zbuffer name can't contain "." z$buffer name can't be empty string ""attribute '{}' already existsNzHcannot assign '{}' object to buffer '{}' (torch Tensor or None required))
isinstancerU   jitZScriptModulerJ   __dict__AttributeError_sixstring_classes	TypeErrorformattypenameKeyErrorhasattrrX   r   rZ   discardadd)r!   rd   re   rf   r$   r$   r%   register_buffer  s2    


 
zModule.register_buffer)rd   paramrA   c                 C   s   d| j krtdnjt|tjjs8tdt|nFd|krJt	dn4|dkr\t	dn"t
| |r~|| jkr~t	d||d	krd	| j|< nBt|tstd
t||n |jrtd|n
|| j|< d	S )a-  Adds a parameter to the module.

        The parameter can be accessed as an attribute using given name.

        Args:
            name (string): name of the parameter. The parameter can be accessed
                from this module using the given name
            param (Parameter or None): parameter to be added to the module. If
                ``None``, then operations that run on parameters, such as :attr:`cuda`,
                are ignored. If ``None``, the parameter is **not** included in the
                module's :attr:`state_dict`.
        rW   z5cannot assign parameter before Module.__init__() callz)parameter name should be a string. Got {}rg   z parameter name can't contain "."rh   z'parameter name can't be empty string ""ri   NzQcannot assign '{}' object to parameter '{}' (torch.nn.Parameter or None required)zCannot assign non-leaf Tensor to parameter '{0}'. Model parameters must be created explicitly. To express '{0}' as a function of another Tensor, compute the value in the forward() method.)rl   rm   rj   rU   rn   ro   rp   rq   rr   rs   rt   rW   r   grad_fn
ValueError)r!   rd   rx   r$   r$   r%   register_parameterI  s8    



 zModule.register_parameter)rd   modulerA   c                 C   s   t |ts(|dk	r(tdt|npt |tjjsLtdt|nLt| |rp|| j	krpt
d|n(d|krt
d|n|dkrt
d|| j	|< dS )	a]  Adds a child module to the current module.

        The module can be accessed as an attribute using the given name.

        Args:
            name (string): name of the child module. The child module can be
                accessed from this module using the given name
            module (Module): child module to be added to the module.
        Nz{} is not a Module subclassz&module name should be a string. Got {}ri   rg   z&module name can't contain ".", got: {}rh   z$module name can't be empty string "")rj   r   rp   rq   rU   rr   rn   ro   rt   ra   rs   r!   rd   r|   r$   r$   r%   
add_modules  s    
zModule.add_modulec                 C   s   |  || dS )zAlias for :func:`add_module`.N)r~   r}   r$   r$   r%   register_module  s    zModule.register_module)targetrA   c                 C   sr   |dkr| S | d}| }|D ]N}t||sDt| d | d t||}t|tjjstd| d q|S )a  
        Returns the submodule given by ``target`` if it exists,
        otherwise throws an error.

        For example, let's say you have an ``nn.Module`` ``A`` that
        looks like this:

        .. code-block:: text

            A(
                (net_b): Module(
                    (net_c): Module(
                        (conv): Conv2d(16, 33, kernel_size=(3, 3), stride=(2, 2))
                    )
                    (linear): Linear(in_features=100, out_features=200, bias=True)
                )
            )

        (The diagram shows an ``nn.Module`` ``A``. ``A`` has a nested
        submodule ``net_b``, which itself has two submodules ``net_c``
        and ``linear``. ``net_c`` then has a submodule ``conv``.)

        To check whether or not we have the ``linear`` submodule, we
        would call ``get_submodule("net_b.linear")``. To check whether
        we have the ``conv`` submodule, we would call
        ``get_submodule("net_b.net_c.conv")``.

        The runtime of ``get_submodule`` is bounded by the degree
        of module nesting in ``target``. A query against
        ``named_modules`` achieves the same result, but it is O(N) in
        the number of transitive modules. So, for a simple check to see
        if some submodule exists, ``get_submodule`` should always be
        used.

        Args:
            target: The fully-qualified string name of the submodule
                to look for. (See above example for how to specify a
                fully-qualified string.)

        Returns:
            torch.nn.Module: The submodule referenced by ``target``

        Raises:
            AttributeError: If the target string references an invalid
                path or resolves to something that is not an
                ``nn.Module``
        rh   rg    has no attribute ``z` is not an nn.Module)	r3   rt   rm   	_get_namegetattrrj   rU   nnr   )r!   r   Zatomsmoditemr$   r$   r%   get_submodule  s    0


zModule.get_submoduler   c                 C   sh   | d\}}}| |}t||s<t| d | d t||}t|tjj	sdtd| d |S )a  
        Returns the parameter given by ``target`` if it exists,
        otherwise throws an error.

        See the docstring for ``get_submodule`` for a more detailed
        explanation of this method's functionality as well as how to
        correctly specify ``target``.

        Args:
            target: The fully-qualified string name of the Parameter
                to look for. (See ``get_submodule`` for how to specify a
                fully-qualified string.)

        Returns:
            torch.nn.Parameter: The Parameter referenced by ``target``

        Raises:
            AttributeError: If the target string references an invalid
                path or resolves to something that is not an
                ``nn.Parameter``
        rg   r   r   z` is not an nn.Parameter)

rpartitionr   rt   rm   r   r   rj   rU   r   r   )r!   r   module_path_
param_namer   rx   r$   r$   r%   get_parameter  s    


zModule.get_parameterr   c                 C   sd   | d\}}}| |}t||s<t| d | d t||}||jkr`td| d |S )a  
        Returns the buffer given by ``target`` if it exists,
        otherwise throws an error.

        See the docstring for ``get_submodule`` for a more detailed
        explanation of this method's functionality as well as how to
        correctly specify ``target``.

        Args:
            target: The fully-qualified string name of the buffer
                to look for. (See ``get_submodule`` for how to specify a
                fully-qualified string.)

        Returns:
            torch.Tensor: The buffer referenced by ``target``

        Raises:
            AttributeError: If the target string references an invalid
                path or resolves to something that is not a
                buffer
        rg   r   r   z` is not a buffer)r   r   rt   rm   r   r   rX   )r!   r   r   r   Zbuffer_namer   bufferr$   r$   r%   
get_buffer  s    



zModule.get_bufferc                 C   s   t ddS )a  
        Returns any extra state to include in the module's state_dict.
        Implement this and a corresponding :func:`set_extra_state` for your module
        if you need to store extra state. This function is called when building the
        module's `state_dict()`.

        Note that extra state should be pickleable to ensure working serialization
        of the state_dict. We only provide provide backwards compatibility guarantees
        for serializing Tensors; other objects may break backwards compatibility if
        their serialized pickled form changes.

        Returns:
            object: Any extra state to store in the module's state_dict
        zReached a code path in Module.get_extra_state() that should never be called. Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to report this bug.NrJ   r    r$   r$   r%   get_extra_state  s    zModule.get_extra_state)statec                 C   s   t ddS )ap  
        This function is called from :func:`load_state_dict` to handle any extra state
        found within the `state_dict`. Implement this function and a corresponding
        :func:`get_extra_state` for your module if you need to store extra state within its
        `state_dict`.

        Args:
            state (dict): Extra state from the `state_dict`
        zReached a code path in Module.set_extra_state() that should never be called. Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml to report this bug.Nr   r!   r   r$   r$   r%   set_extra_state2  s    
zModule.set_extra_statec              
   C   s2  |   D ]}|| qdd }| j D ]\}}|d kr<q*t  ||}W 5 Q R X |||}|rr||_|}n.t|tst	|j
st	t||j}|| j|< |jd k	r*t  ||j}	W 5 Q R X ||j|	}|r|	|j_q*|jj
st	|	|jj|_q*| j D ]"\}}
|
d k	r
||
| j|< q
| S )Nc                 S   s    t | |rt j  S dS d S NF)rU   Z!_has_compatible_shallow_copy_type
__future__Z)get_overwrite_module_params_on_conversion)re   Ztensor_appliedr$   r$   r%   compute_should_use_set_dataE  s    	z2Module._apply.<locals>.compute_should_use_set_data)children_applyrW   itemsrU   no_graddatarj   r   AssertionErrorZis_leafrequires_gradgradrequires_grad_rX   )r!   fnr|   r   keyrx   Zparam_appliedZshould_use_set_dataZ	out_paramZgrad_appliedbufr$   r$   r%   r   A  s8    







zModule._apply)r!   r   rA   c                 C   s$   |   D ]}|| q||  | S )ab  Applies ``fn`` recursively to every submodule (as returned by ``.children()``)
        as well as self. Typical use includes initializing the parameters of a model
        (see also :ref:`nn-init-doc`).

        Args:
            fn (:class:`Module` -> None): function to be applied to each submodule

        Returns:
            Module: self

        Example::

            >>> @torch.no_grad()
            >>> def init_weights(m):
            >>>     print(m)
            >>>     if type(m) == nn.Linear:
            >>>         m.weight.fill_(1.0)
            >>>         print(m.weight)
            >>> net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
            >>> net.apply(init_weights)
            Linear(in_features=2, out_features=2, bias=True)
            Parameter containing:
            tensor([[ 1.,  1.],
                    [ 1.,  1.]])
            Linear(in_features=2, out_features=2, bias=True)
            Parameter containing:
            tensor([[ 1.,  1.],
                    [ 1.,  1.]])
            Sequential(
              (0): Linear(in_features=2, out_features=2, bias=True)
              (1): Linear(in_features=2, out_features=2, bias=True)
            )
            Sequential(
              (0): Linear(in_features=2, out_features=2, bias=True)
              (1): Linear(in_features=2, out_features=2, bias=True)
            )
        )r   apply)r!   r   r|   r$   r$   r%   r   u  s    &zModule.apply)r!   r   rA   c                    s   |   fddS )a  Moves all model parameters and buffers to the GPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing optimizer if the module will
        live on GPU while being optimized.

        .. note::
            This method modifies the module in-place.

        Args:
            device (int, optional): if specified, all parameters will be
                copied to that device

        Returns:
            Module: self
        c                    s
   |   S N)cudatr   r$   r%   <lambda>      zModule.cuda.<locals>.<lambda>r   r!   r   r$   r   r%   r     s    zModule.cudac                    s   |   fddS )a  Moves all model parameters and buffers to the IPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing optimizer if the module will
        live on IPU while being optimized.

        .. note::
            This method modifies the module in-place.

        Arguments:
            device (int, optional): if specified, all parameters will be
                copied to that device

        Returns:
            Module: self
        c                    s
   |   S r   )ipur   r   r$   r%   r     r   zModule.ipu.<locals>.<lambda>r   r   r$   r   r%   r     s    z
Module.ipuc                    s   |   fddS )a  Moves all model parameters and buffers to the XPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing optimizer if the module will
        live on XPU while being optimized.

        .. note::
            This method modifies the module in-place.

        Arguments:
            device (int, optional): if specified, all parameters will be
                copied to that device

        Returns:
            Module: self
        c                    s
   |   S r   )xpur   r   r$   r%   r     r   zModule.xpu.<locals>.<lambda>r   r   r$   r   r%   r     s    z
Module.xpu)r!   rA   c                 C   s   |  dd S )zMoves all model parameters and buffers to the CPU.

        .. note::
            This method modifies the module in-place.

        Returns:
            Module: self
        c                 S   s   |   S r   )cpur   r$   r$   r%   r     r   zModule.cpu.<locals>.<lambda>r   r    r$   r$   r%   r     s    	z
Module.cpu)r!   dst_typerA   c                    s   |   fddS )zCasts all parameters and buffers to :attr:`dst_type`.

        .. note::
            This method modifies the module in-place.

        Args:
            dst_type (type or string): the desired type

        Returns:
            Module: self
        c                    s
   |   S r   )rO   r   r   r$   r%   r     r   zModule.type.<locals>.<lambda>r   )r!   r   r$   r   r%   rO     s    zModule.typec                 C   s   |  dd S )zCasts all floating point parameters and buffers to ``float`` datatype.

        .. note::
            This method modifies the module in-place.

        Returns:
            Module: self
        c                 S   s   |   r|  S | S r   )is_floating_pointfloatr   r$   r$   r%   r     r   zModule.float.<locals>.<lambda>r   r    r$   r$   r%   r     s    	zModule.floatc                 C   s   |  dd S )zCasts all floating point parameters and buffers to ``double`` datatype.

        .. note::
            This method modifies the module in-place.

        Returns:
            Module: self
        c                 S   s   |   r|  S | S r   )r   doubler   r$   r$   r%   r     r   zModule.double.<locals>.<lambda>r   r    r$   r$   r%   r     s    	zModule.doublec                 C   s   |  dd S )zCasts all floating point parameters and buffers to ``half`` datatype.

        .. note::
            This method modifies the module in-place.

        Returns:
            Module: self
        c                 S   s   |   r|  S | S r   )r   halfr   r$   r$   r%   r     r   zModule.half.<locals>.<lambda>r   r    r$   r$   r%   r     s    	zModule.halfc                 C   s   |  dd S )zCasts all floating point parameters and buffers to ``bfloat16`` datatype.

        .. note::
            This method modifies the module in-place.

        Returns:
            Module: self
        c                 S   s   |   r|  S | S r   )r   bfloat16r   r$   r$   r%   r     r   z!Module.bfloat16.<locals>.<lambda>r   r    r$   r$   r%   r     s    	zModule.bfloat16c                   s   |   fddS )a  Moves the parameters and buffers to the specified device without copying storage.

        Args:
            device (:class:`torch.device`): The desired device of the parameters
                and buffers in this module.

        Returns:
            Module: self
        c                    s   t j|  dS )Nr   )rU   Z
empty_liker   r   r$   r%   r   (  r   z!Module.to_empty.<locals>.<lambda>r   r   r$   r   r%   to_empty  s    
zModule.to_empty)r!   r   r   non_blockingrA   c                 C   s   d S r   r$   )r!   r   r   r   r$   r$   r%   to*  s    z	Module.to)r!   r   r   rA   c                 C   s   d S r   r$   )r!   r   r   r$   r$   r%   r   /  s    )r!   re   r   rA   c                 C   s   d S r   r$   )r!   re   r   r$   r$   r%   r   3  s    c                    sf   t jjj||\ dk	rJjs:js:tdjrJt	d  fdd}| 
|S )a=  Moves and/or casts the parameters and buffers.

        This can be called as

        .. function:: to(device=None, dtype=None, non_blocking=False)
           :noindex:

        .. function:: to(dtype, non_blocking=False)
           :noindex:

        .. function:: to(tensor, non_blocking=False)
           :noindex:

        .. function:: to(memory_format=torch.channels_last)
           :noindex:

        Its signature is similar to :meth:`torch.Tensor.to`, but only accepts
        floating point or complex :attr:`dtype`\ s. In addition, this method will
        only cast the floating point or complex parameters and buffers to :attr:`dtype`
        (if given). The integral parameters and buffers will be moved
        :attr:`device`, if that is given, but with dtypes unchanged. When
        :attr:`non_blocking` is set, it tries to convert/move asynchronously
        with respect to the host if possible, e.g., moving CPU Tensors with
        pinned memory to CUDA devices.

        See below for examples.

        .. note::
            This method modifies the module in-place.

        Args:
            device (:class:`torch.device`): the desired device of the parameters
                and buffers in this module
            dtype (:class:`torch.dtype`): the desired floating point or complex dtype of
                the parameters and buffers in this module
            tensor (torch.Tensor): Tensor whose dtype and device are the desired
                dtype and device for all parameters and buffers in this module
            memory_format (:class:`torch.memory_format`): the desired memory
                format for 4D parameters and buffers in this module (keyword
                only argument)

        Returns:
            Module: self

        Examples::

            >>> linear = nn.Linear(2, 2)
            >>> linear.weight
            Parameter containing:
            tensor([[ 0.1913, -0.3420],
                    [-0.5113, -0.2325]])
            >>> linear.to(torch.double)
            Linear(in_features=2, out_features=2, bias=True)
            >>> linear.weight
            Parameter containing:
            tensor([[ 0.1913, -0.3420],
                    [-0.5113, -0.2325]], dtype=torch.float64)
            >>> gpu1 = torch.device("cuda:1")
            >>> linear.to(gpu1, dtype=torch.half, non_blocking=True)
            Linear(in_features=2, out_features=2, bias=True)
            >>> linear.weight
            Parameter containing:
            tensor([[ 0.1914, -0.3420],
                    [-0.5112, -0.2324]], dtype=torch.float16, device='cuda:1')
            >>> cpu = torch.device("cpu")
            >>> linear.to(cpu)
            Linear(in_features=2, out_features=2, bias=True)
            >>> linear.weight
            Parameter containing:
            tensor([[ 0.1914, -0.3420],
                    [-0.5112, -0.2324]], dtype=torch.float16)

            >>> linear = nn.Linear(2, 2, bias=None).to(torch.cdouble)
            >>> linear.weight
            Parameter containing:
            tensor([[ 0.3741+0.j,  0.2382+0.j],
                    [ 0.5593+0.j, -0.4443+0.j]], dtype=torch.complex128)
            >>> linear(torch.ones(3, 2, dtype=torch.cdouble))
            tensor([[0.6122+0.j, 0.1150+0.j],
                    [0.6122+0.j, 0.1150+0.j],
                    [0.6122+0.j, 0.1150+0.j]], dtype=torch.complex128)

        NzTnn.Module.to only accepts floating point or complex dtypes, but got desired dtype={}aA  Complex modules are a new feature under active development whose design may change, and some modules might not work as expected when using complex tensors as parameters or buffers. Please file an issue at https://github.com/pytorch/pytorch/issues/new?template=bug-report.yml if a complex module does not work as expected.c                    s\    d k	r:|   dkr:| j|  s*|  r.nd  dS | |  sP|  rTnd S )N)      )Zmemory_format)Zdimr   r   
is_complexr   Zconvert_to_formatr   r   r   r$   r%   convert  s     zModule.to.<locals>.convert)rU   rV   Z_nnZ	_parse_tor   r   rp   rq   warningswarnr   )r!   argskwargsr   r$   r   r%   r   7  s    Ur?   c                 C   s4   | j dkrtdd| _ t| j}|| j|j< |S )a  Registers a backward hook on the module.

        This function is deprecated in favor of :meth:`~torch.nn.Module.register_full_backward_hook` and
        the behavior of this function will change in future versions.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``

        ToCannot use both regular backward hooks and full backward hooks on a single Module. Please use only one of them.FrT   rJ   rB   r   r[   rC   r!   r@   rE   r$   r$   r%   register_backward_hook  s    
zModule.register_backward_hookc                 C   s4   | j dkrtdd| _ t| j}|| j|j< |S )a  Registers a backward hook on the module.

        The hook will be called every time the gradients with respect to module
        inputs are computed. The hook should have the following signature::

            hook(module, grad_input, grad_output) -> tuple(Tensor) or None

        The :attr:`grad_input` and :attr:`grad_output` are tuples that contain the gradients
        with respect to the inputs and outputs respectively. The hook should
        not modify its arguments, but it can optionally return a new gradient with
        respect to the input that will be used in place of :attr:`grad_input` in
        subsequent computations. :attr:`grad_input` will only correspond to the inputs given
        as positional arguments and all kwarg arguments are ignored. Entries
        in :attr:`grad_input` and :attr:`grad_output` will be ``None`` for all non-Tensor
        arguments.

        For technical reasons, when this hook is applied to a Module, its forward function will
        receive a view of each Tensor passed to the Module. Similarly the caller will receive a view
        of each Tensor returned by the Module's forward function.

        .. warning ::
            Modifying inputs or outputs inplace is not allowed when using backward hooks and
            will raise an error.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``

        Fr   Tr   r   r$   r$   r%   register_full_backward_hook  s    !
z"Module.register_full_backward_hookc                 C   sh   g }t dkr|t 7 }| jdkr0|| j 7 }g }t dkrH|t 7 }| jdkr`|| j 7 }||fS )zReturns the backward hooks for use in the call function.
        It returns two lists, one with the full backward hooks and one with the non-full
        backward hooks.
        TF)r;   r:   valuesrT   r[   )r!   full_backward_hooksnon_full_backward_hooksr$   r$   r%   _get_backward_hooks  s    

zModule._get_backward_hooksc                 C   s  t |tjs8t |tr(tdd |D s>td d S n|f}t |tjsvt |trftdd |D s|td d S n|f}dd |D }t|dkst|d	kr||krtd
 nHt|d	krtd n0dd |D }dd |jD }||krtd d S )Nc                 S   s   g | ]}t |tjqS r$   rj   rU   r   r.   rr$   r$   r%   r2     s     z=Module._maybe_warn_non_full_backward_hook.<locals>.<listcomp>a  Using non-full backward hooks on a Module that does not return a single Tensor or a tuple of Tensors is deprecated and will be removed in future versions. This hook will be missing some of the grad_output. Please use register_full_backward_hook to get the documented behavior.c                 S   s   g | ]}t |tjqS r$   r   r.   ir$   r$   r%   r2     s     a  Using non-full backward hooks on a Module that does not take as input a single Tensor or a tuple of Tensors is deprecated and will be removed in future versions. This hook will be missing some of the grad_input. Please use register_full_backward_hook to get the documented behavior.c                 S   s   h | ]}|j d k	r|j qS r   ry   r   r$   r$   r%   	<setcomp>  s     
 z<Module._maybe_warn_non_full_backward_hook.<locals>.<setcomp>r   r,   zUsing a non-full backward hook when outputs are nested in python data structure is deprecated and will be removed in future versions. This hook will be missing some grad_output.zUsing a non-full backward hook when outputs are generated by different autograd Nodes is deprecated and will be removed in future versions. This hook will be missing some grad_output. Please use register_full_backward_hook to get the documented behavior.c                 S   s   h | ]}|j d k	r|j qS r   r   r   r$   r$   r%   r     s     
 c                 S   s   h | ]}|d  qS r   r$   )r.   nr$   r$   r%   r     s     zUsing a non-full backward hook when the forward contains multiple autograd Nodes is deprecated and will be removed in future versions. This hook will be missing some grad_input. Please use register_full_backward_hook to get the documented behavior.)	rj   rU   r   tupleallr   r   r4   next_functions)r!   inputsresultry   Zout_grad_fnZinputs_grad_fnr   r$   r$   r%   "_maybe_warn_non_full_backward_hook  s&    

 z)Module._maybe_warn_non_full_backward_hookr>   c                 C   s   t | j}|| j|j< |S )a5  Registers a forward pre-hook on the module.

        The hook will be called every time before :func:`forward` is invoked.
        It should have the following signature::

            hook(module, input) -> None or modified input

        The input contains only the positional arguments given to the module.
        Keyword arguments won't be passed to the hooks and only to the ``forward``.
        The hook can modify the input. User can either return a tuple or a
        single modified value in the hook. We will wrap the value into a tuple
        if a single value is returned(unless that value is already a tuple).

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        )rB   r   r]   rC   r   r$   r$   r%   register_forward_pre_hook"  s    z Module.register_forward_pre_hookc                 C   s   t | j}|| j|j< |S )a  Registers a forward hook on the module.

        The hook will be called every time after :func:`forward` has computed an output.
        It should have the following signature::

            hook(module, input, output) -> None or modified output

        The input contains only the positional arguments given to the module.
        Keyword arguments won't be passed to the hooks and only to the ``forward``.
        The hook can modify the output. It can modify the input inplace but
        it will not have effect on forward since this is called after
        :func:`forward` is called.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        )rB   r   r\   rC   r   r$   r$   r%   register_forward_hook9  s    zModule.register_forward_hookc                 O   s   t j }|rt| jt jjr*| j||S t jjjd k	}|rp| t jjjkrXt jjj|  nd }|rl|	| nd}z| j||}W 5 |r|
  X |S r   )rU   rV   _get_tracing_staterj   rc   ZScriptMethodrk   Z_traceZ_trace_module_mapZ
push_scopeZ	pop_scope)r!   rM   r   Ztracing_stateZrecording_scopesrd   r   r$   r$   r%   _slow_forwardP  s    
 
zModule._slow_forwardc                 O   s  t j r| jn| j}| js>| js>| js>ts>t	s>t
s>|||S g g  }}| jsRtr^|  \}}t
sh| jrt
 | j D ]*}|| |}|d k	rzt|ts|f}|}qzd }|rt| |}||}|||}t	s| jr
t	 | j D ]}|| ||}	|	d k	r|	}q|r||}|r|}
t|
t jsbt|
trVtdd |
 D }
n|
d }
q$|
j}|d k	r|D ](}t|| }t|| || qv| ||| |S )Nc                 s   s   | ]}t |tjr|V  qd S r   r   )r.   vr$   r$   r%   	<genexpr>  s      z$Module._call_impl.<locals>.<genexpr>r   )rU   rV   r   r   rc   r[   r\   r]   r:   r=   r<   r   r   rj   r   rB   ZBackwardHookZsetup_input_hookZsetup_output_hookr   dictnextry   	functoolspartialupdate_wrapperregister_hookr   )r!   rM   r   Zforward_callr   r   r@   r   Zbw_hookhook_resultvarry   wrapperr$   r$   r%   
_call_impld  sV    









zModule._call_impl__call__c                 C   sz   | j | d| j krt | _d| j kr0t | _d| j krBt | _d| j krTt | _d| j krft | _d| j krvd | _	d S )Nr]   r^   r_   r`   rZ   rT   )
rl   updater   r]   r^   r_   r`   rY   rZ   rT   r   r$   r$   r%   __setstate__  s    





zModule.__setstate__)rd   rA   c                 C   s   d| j kr$| j d }||kr$|| S d| j krH| j d }||krH|| S d| j krl| j d }||krl|| S tdt| j|d S )NrW   rX   ra   z!'{}' object has no attribute '{}')rl   rm   rq   rO   r&   )r!   rd   rW   rX   modulesr$   r$   r%   __getattr__  s     





 zModule.__getattr__)rd   valuerA   c                    s   fdd}| j d}t|trX|d kr2td|| j | j| j| j |  | n&|d k	r |kr|d k	rt	d
t| |  | n| j d}t|tr|d krtd|| j | j| j| j || < n|d k	r |kr|d k	rt	d
t| || < nf| j d	}|d k	rp |krp|d k	rft|tjsft	d

t| || < nt|  | d S )Nc                     s2   | D ](} |krt |tr"| = q|  qd S r   )rj   r   ru   )Zdicts_or_setsdrd   r$   r%   remove_from  s
    
z'Module.__setattr__.<locals>.remove_fromrW   z6cannot assign parameters before Module.__init__() callzJcannot assign '{}' as parameter '{}' (torch.nn.Parameter or None expected)ra   z2cannot assign module before Module.__init__() callzJcannot assign '{}' as child module '{}' (torch.nn.Module or None expected)rX   zAcannot assign '{}' as buffer '{}' (torch.Tensor or None expected))rl   getrj   r   rm   rX   ra   rZ   r{   rp   rq   rU   rr   r   rW   r   object__setattr__)r!   rd   r   r   paramsr   buffersr$   r   r%   r     sP    
 


 
 
zModule.__setattr__c                 C   sX   || j kr| j |= n@|| jkr4| j|= | j| n || jkrH| j|= nt| | d S r   )rW   rX   rZ   ru   ra   r   __delattr__)r!   rd   r$   r$   r%   r     s    




zModule.__delattr__c                 C   s   t | j}|| j|j< |S )aV  These hooks will be called with arguments: `self`, `state_dict`,
        `prefix`, `local_metadata`, after the `state_dict` of `self` is set.
        Note that only parameters and buffers of `self` or its children are
        guaranteed to exist in `state_dict`. The hooks may modify `state_dict`
        inplace or return a new one.
        )rB   r   r^   rC   r   r$   r$   r%   _register_state_dict_hook  s    z Module._register_state_dict_hookc                 C   s   | j  D ](\}}|dk	r
|r"|n| ||| < q
| j D ]2\}}|dk	r>|| jkr>|r`|n| ||| < q>|t }t| jdtj	tj	k	r| 	 ||< dS )a  Saves module state to `destination` dictionary, containing a state
        of the module, but not its descendants. This is called on every
        submodule in :meth:`~torch.nn.Module.state_dict`.

        In rare cases, subclasses can achieve class-specific behavior by
        overriding this method with custom logic.

        Args:
            destination (dict): a dict where state will be stored
            prefix (str): the prefix for parameters and buffers used in this
                module
        Nr   )
rW   r   detachrX   rZ   _EXTRA_STATE_KEY_SUFFIXr   r#   r   r   )r!   destinationprefix	keep_varsrd   rx   r   extra_state_keyr$   r$   r%   _save_to_state_dict  s    zModule._save_to_state_dictT_destinationr   )r   r   )r   r   r   rA   c                C   s   d S r   r$   )r!   r   r   r   r$   r$   r%   
state_dict  s    zModule.state_dict)r   r   rA   c                C   s   d S r   r$   )r!   r   r   r$   r$   r%   r    s    rh   r   r   r   c          
      G   s  t |dkr^|dkr|d }t |dkr8|dkr8|d }t |dkrT|dkrT|d }td |dkrtt }t |_t| jd}t|d	r||j|dd
 < | ||| | j	
 D ](\}}|dk	r|j||| d |d q| j D ]}|| |||}	|	dk	r|	}q|S )a0  Returns a dictionary containing a whole state of the module.

        Both parameters and persistent buffers (e.g. running averages) are
        included. Keys are corresponding parameter and buffer names.
        Parameters and buffers set to ``None`` are not included.

        .. warning::
            Currently ``state_dict()`` also accepts positional arguments for
            ``destination``, ``prefix`` and ``keep_vars`` in order. However,
            this is being deprecated and keyword arguments will be enforced in
            future releases.

        .. warning::
            Please avoid the use of argument ``destination`` as it is not
            designed for end-users.

        Args:
            destination (dict, optional): If provided, the state of module will
                be updated into the dict and the same object is returned.
                Otherwise, an ``OrderedDict`` will be created and returned.
                Default: ``None``.
            prefix (str, optional): a prefix added to parameter and buffer
                names to compose the keys in state_dict. Default: ``''``.
            keep_vars (bool, optional): by default the :class:`~torch.Tensor` s
                returned in the state dict are detached from autograd. If it's
                set to ``True``, detaching will not be performed.
                Default: ``False``.

        Returns:
            dict:
                a dictionary containing a whole state of the module

        Example::

            >>> module.state_dict().keys()
            ['bias', 'weight']

        r   Nr,   rh   r   FzPositional args are being deprecated, use kwargs instead. Refer to https://pytorch.org/docs/master/generated/torch.nn.Module.html#torch.nn.Module.state_dict for details.)version	_metadatarg   r  )r4   r   r   r   r  r   rR   rt   r  ra   r   r  r^   r   )
r!   r   r   r   r   local_metadatard   r|   r@   r   r$   r$   r%   r  $  s2    )
c                 C   s,   t | j}|rt|| }|| j|j< |S )a  These hooks will be called with arguments: `state_dict`, `prefix`,
        `local_metadata`, `strict`, `missing_keys`, `unexpected_keys`,
        `error_msgs`, before loading `state_dict` into `self`. These arguments
        are exactly the same as those of `_load_from_state_dict`.

        If ``with_module`` is ``True``, then the first argument to the hook is
        an instance of the module.

        Arguments:
            hook (Callable): Callable hook that will be invoked before
                loading the state dict.
            with_module (bool, optional): Whether or not to pass the module
                instance to the hook as the first parameter.
        )rB   r   r_   r   r   rC   )r!   r@   Zwith_modulerE   r$   r$   r%   "_register_load_state_dict_pre_hookl  s
    z)Module._register_load_state_dict_pre_hookc                 C   s   t | j}|| j|j< |S )a  Registers a post hook to be run after module's ``load_state_dict``
        is called.

        It should have the following signature::
            hook(module, incompatible_keys) -> None

        The ``module`` argument is the current module that this hook is registered
        on, and the ``incompatible_keys`` argument is a ``NamedTuple`` consisting
        of attributes ``missing_keys`` and ``unexpected_keys``. ``missing_keys``
        is a ``list`` of ``str`` containing the missing keys and
        ``unexpected_keys`` is a ``list`` of ``str`` containing the unexpected keys.

        The given incompatible_keys can be modified inplace if needed.

        Note that the checks performed when calling :func:`load_state_dict` with
        ``strict=True`` are affected by modifications the hook makes to
        ``missing_keys`` or ``unexpected_keys``, as expected. Additions to either
        set of keys will result in an error being thrown when ``strict=True``, and
        clearning out both missing and unexpected keys will avoid an error.

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        )rB   r   r`   rC   r   r$   r$   r%   "register_load_state_dict_post_hook  s    z)Module.register_load_state_dict_post_hookc                    sd   j  D ]}|||||||| q
 fdd j D }	t j |	 }
dd |
D }| D ]"\}}|| }||kr~|| }tj	|s|
d|t| qhtjj|}|st|jdkrt|jdkr|d }|s|j|jkr|
d||j|j qhz"t  || W 5 Q R X W nD tk
rz } z$|
d|| | |j W 5 d	}~X Y nX qh|rh|
| qh|t }t jd
tjtjk	r||krȈ ||  n|r|
| n|r||kr|
| |r`| D ]\}||r||kr|t|d	 }|ddd }| jkr||kr|
| qd	S )ay  Copies parameters and buffers from :attr:`state_dict` into only
        this module, but not its descendants. This is called on every submodule
        in :meth:`~torch.nn.Module.load_state_dict`. Metadata saved for this
        module in input :attr:`state_dict` is provided as :attr:`local_metadata`.
        For state dicts without metadata, :attr:`local_metadata` is empty.
        Subclasses can achieve class-specific backward compatible loading using
        the version number at `local_metadata.get("version", None)`.

        .. note::
            :attr:`state_dict` is not the same object as the input
            :attr:`state_dict` to :meth:`~torch.nn.Module.load_state_dict`. So
            it can be modified.

        Args:
            state_dict (dict): a dict containing parameters and
                persistent buffers.
            prefix (str): the prefix for parameters and buffers used in this
                module
            local_metadata (dict): a dict containing the metadata for this module.
                See
            strict (bool): whether to strictly enforce that the keys in
                :attr:`state_dict` with :attr:`prefix` match the names of
                parameters and buffers in this module
            missing_keys (list of str): if ``strict=True``, add missing keys to
                this list
            unexpected_keys (list of str): if ``strict=True``, add unexpected
                keys to this list
            error_msgs (list of str): error messages should be added to this
                list, and will be reported together in
                :meth:`~torch.nn.Module.load_state_dict`
        c                    s    i | ]\}}| j kr||qS r$   )rZ   r.   kr   r    r$   r%   
<dictcomp>  s     
  z0Module._load_from_state_dict.<locals>.<dictcomp>c                 S   s   i | ]\}}|d k	r||qS r   r$   r  r$   r$   r%   r    s       zsWhile copying the parameter named "{}", expected torch.Tensor or Tensor-like object from checkpoint but received {}r   r,   zfsize mismatch for {}: copying a param with shape {} from checkpoint, the shape in current model is {}.zWhile copying the parameter named "{}", whose dimensions in the model are {} and whose dimensions in the checkpoint are {}, an exception occurred : {}.Nr   rg   ) r_   r   rX   r   	itertoolschainrW   rU   Z	overridesZis_tensor_likeappendrq   rO   r   	parameterZis_lazyr4   shaper   Zcopy_	Exceptionsizer   r   r   r#   r   r   keys
startswithr3   ra   )r!   r  r   r	  strictr   r   
error_msgsr@   Zpersistent_buffersZlocal_name_paramsZlocal_staterd   rx   r   Zinput_paramZis_param_lazyexr  Z
input_namer$   r    r%   _load_from_state_dict  sh    !
    
   

zModule._load_from_state_dict)r  r  c              	      s   t tstdtg g g  tddtdk	rJ_d fdd	|  |rtdkr 	ddd	
d
d D  tdkr̈ 	ddd	
dd D  t dkrtd| jjd
 tS )ab  Copies parameters and buffers from :attr:`state_dict` into
        this module and its descendants. If :attr:`strict` is ``True``, then
        the keys of :attr:`state_dict` must exactly match the keys returned
        by this module's :meth:`~torch.nn.Module.state_dict` function.

        Args:
            state_dict (dict): a dict containing parameters and
                persistent buffers.
            strict (bool, optional): whether to strictly enforce that the keys
                in :attr:`state_dict` match the keys returned by this module's
                :meth:`~torch.nn.Module.state_dict` function. Default: ``True``

        Returns:
            ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
                * **missing_keys** is a list of str containing the missing keys
                * **unexpected_keys** is a list of str containing the unexpected keys

        Note:
            If a parameter or buffer is registered as ``None`` and its corresponding key
            exists in :attr:`state_dict`, :meth:`load_state_dict` will raise a
            ``RuntimeError``.
        z,Expected state_dict to be dict-like, got {}.r  Nrh   c              	      s   d kri n |d d i }| ||d  | j D ]"\}}|d k	r@||| d  q@t}| j D ]}|| |}|d ksxtdqxd S )Nr  Trg   zHooks registered with ``register_load_state_dict_post_hook`` are notexpected to return new values, if incompatible_keys need to be modified,it should be done inplace.)r   r  ra   r   r   r`   r   r   )r|   r   r	  rd   childZincompatible_keysr@   outr  loadmetadatar   r  r   r$   r%   r  $  s&           


z$Module.load_state_dict.<locals>.loadr   z%Unexpected key(s) in state_dict: {}. z, c                 s   s   | ]}d  |V  qdS z"{}"Nrq   r.   r  r$   r$   r%   r   =  s     z)Module.load_state_dict.<locals>.<genexpr>z"Missing key(s) in state_dict: {}. c                 s   s   | ]}d  |V  qdS r!  r"  r#  r$   r$   r%   r   A  s     z*Error(s) in loading state_dict for {}:
	{}z
	)rh   )rj   r   rp   rq   rO   r   r   r  r4   insertr6   rJ   r#   r&   r   )r!   r  r  r$   r  r%   load_state_dict  sB    
   zModule.load_state_dictc                 c   s   t  }|r| j|dn|| fg}|D ]X\}}||}|D ]B\}	}
|
dks8|
|krRq8||
 ||rfdnd |	 }||
fV  q8q$dS )z>Helper method for yielding various names + members of modules.)r   Nrg   rh   )rY   named_modulesrv   )r!   Zget_members_fnr   recursememor   Zmodule_prefixr|   membersr  r   rd   r$   r$   r%   _named_membersH  s    
zModule._named_members)r'  rA   c                 c   s    | j |dD ]\}}|V  qdS )aR  Returns an iterator over module parameters.

        This is typically passed to an optimizer.

        Args:
            recurse (bool): if True, then yields parameters of this module
                and all submodules. Otherwise, yields only parameters that
                are direct members of this module.

        Yields:
            Parameter: module parameter

        Example::

            >>> for param in model.parameters():
            >>>     print(type(param), param.size())
            <class 'torch.Tensor'> (20L,)
            <class 'torch.Tensor'> (20L, 1L, 5L, 5L)

        r'  N)named_parameters)r!   r'  rd   rx   r$   r$   r%   
parametersU  s    zModule.parameters)r   r'  rA   c                 c   s(   | j dd ||d}|D ]
}|V  qdS )a  Returns an iterator over module parameters, yielding both the
        name of the parameter as well as the parameter itself.

        Args:
            prefix (str): prefix to prepend to all parameter names.
            recurse (bool): if True, then yields parameters of this module
                and all submodules. Otherwise, yields only parameters that
                are direct members of this module.

        Yields:
            (string, Parameter): Tuple containing the name and parameter

        Example::

            >>> for name, param in self.named_parameters():
            >>>    if name in ['bias']:
            >>>        print(param.size())

        c                 S   s
   | j  S r   )rW   r   r|   r$   r$   r%   r     r   z)Module.named_parameters.<locals>.<lambda>r   r'  Nr*  r!   r   r'  genelemr$   r$   r%   r,  m  s     zModule.named_parametersc                 c   s    | j |dD ]\}}|V  qdS )a  Returns an iterator over module buffers.

        Args:
            recurse (bool): if True, then yields buffers of this module
                and all submodules. Otherwise, yields only buffers that
                are direct members of this module.

        Yields:
            torch.Tensor: module buffer

        Example::

            >>> for buf in model.buffers():
            >>>     print(type(buf), buf.size())
            <class 'torch.Tensor'> (20L,)
            <class 'torch.Tensor'> (20L, 1L, 5L, 5L)

        r+  N)named_buffers)r!   r'  r   r   r$   r$   r%   r     s    zModule.buffersc                 c   s(   | j dd ||d}|D ]
}|V  qdS )a  Returns an iterator over module buffers, yielding both the
        name of the buffer as well as the buffer itself.

        Args:
            prefix (str): prefix to prepend to all buffer names.
            recurse (bool): if True, then yields buffers of this module
                and all submodules. Otherwise, yields only buffers that
                are direct members of this module.

        Yields:
            (string, torch.Tensor): Tuple containing the name and buffer

        Example::

            >>> for name, buf in self.named_buffers():
            >>>    if name in ['running_var']:
            >>>        print(buf.size())

        c                 S   s
   | j  S r   )rX   r   r.  r$   r$   r%   r     r   z&Module.named_buffers.<locals>.<lambda>r/  Nr0  r1  r$   r$   r%   r4    s     zModule.named_buffersc                 c   s   |   D ]\}}|V  qdS )zqReturns an iterator over immediate children modules.

        Yields:
            Module: a child module
        N)named_childrenr}   r$   r$   r%   r     s    zModule.childrenc                 c   sB   t  }| j D ],\}}|dk	r||kr|| ||fV  qdS )a  Returns an iterator over immediate children modules, yielding both
        the name of the module as well as the module itself.

        Yields:
            (string, Module): Tuple containing a name and child module

        Example::

            >>> for name, module in model.named_children():
            >>>     if name in ['conv4', 'conv5']:
            >>>         print(module)

        N)rY   ra   r   rv   )r!   r(  rd   r|   r$   r$   r%   r5    s
    
zModule.named_childrenc                 c   s   |   D ]\}}|V  qdS )a  Returns an iterator over all modules in the network.

        Yields:
            Module: a module in the network

        Note:
            Duplicate modules are returned only once. In the following
            example, ``l`` will be returned only once.

        Example::

            >>> l = nn.Linear(2, 2)
            >>> net = nn.Sequential(l, l)
            >>> for idx, m in enumerate(net.modules()):
                    print(idx, '->', m)

            0 -> Sequential(
              (0): Linear(in_features=2, out_features=2, bias=True)
              (1): Linear(in_features=2, out_features=2, bias=True)
            )
            1 -> Linear(in_features=2, out_features=2, bias=True)

        N)r&  )r!   r   r|   r$   r$   r%   r     s    zModule.modules)r(  r   remove_duplicatec                 c   s~   |dkrt  }| |krz|r$||  || fV  | j D ]@\}}|dkrJq8||rTdnd | }||||D ]
}|V  qlq8dS )aH  Returns an iterator over all modules in the network, yielding
        both the name of the module as well as the module itself.

        Args:
            memo: a memo to store the set of modules already added to the result
            prefix: a prefix that will be added to the name of the module
            remove_duplicate: whether to remove the duplicated module instances in the result
                or not

        Yields:
            (string, Module): Tuple of name and module

        Note:
            Duplicate modules are returned only once. In the following
            example, ``l`` will be returned only once.

        Example::

            >>> l = nn.Linear(2, 2)
            >>> net = nn.Sequential(l, l)
            >>> for idx, m in enumerate(net.named_modules()):
                    print(idx, '->', m)

            0 -> ('', Sequential(
              (0): Linear(in_features=2, out_features=2, bias=True)
              (1): Linear(in_features=2, out_features=2, bias=True)
            ))
            1 -> ('0', Linear(in_features=2, out_features=2, bias=True))

        Nrg   rh   )rY   rv   ra   r   r&  )r!   r(  r   r6  rd   r|   Zsubmodule_prefixmr$   r$   r%   r&    s     

zModule.named_modules)r!   moderA   c                 C   s4   t |tstd|| _|  D ]}|| q | S )a  Sets the module in training mode.

        This has any effect only on certain modules. See documentations of
        particular modules for details of their behaviors in training/evaluation
        mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
        etc.

        Args:
            mode (bool): whether to set training mode (``True``) or evaluation
                         mode (``False``). Default: ``True``.

        Returns:
            Module: self
        z'training mode is expected to be boolean)rj   boolrz   rS   r   train)r!   r8  r|   r$   r$   r%   r:    s    
zModule.trainc                 C   s
   |  dS )a9  Sets the module in evaluation mode.

        This has any effect only on certain modules. See documentations of
        particular modules for details of their behaviors in training/evaluation
        mode, if they are affected, e.g. :class:`Dropout`, :class:`BatchNorm`,
        etc.

        This is equivalent with :meth:`self.train(False) <torch.nn.Module.train>`.

        See :ref:`locally-disable-grad-doc` for a comparison between
        `.eval()` and several similar mechanisms that may be confused with it.

        Returns:
            Module: self
        F)r:  r    r$   r$   r%   eval2  s    zModule.eval)r!   r   rA   c                 C   s   |   D ]}|| q| S )a  Change if autograd should record operations on parameters in this
        module.

        This method sets the parameters' :attr:`requires_grad` attributes
        in-place.

        This method is helpful for freezing part of the module for finetuning
        or training parts of a model individually (e.g., GAN training).

        See :ref:`locally-disable-grad-doc` for a comparison between
        `.requires_grad_()` and several similar mechanisms that may be confused with it.

        Args:
            requires_grad (bool): whether autograd should record operations on
                                  parameters in this module. Default: ``True``.

        Returns:
            Module: self
        )r-  r   )r!   r   pr$   r$   r%   r   D  s    zModule.requires_grad_)set_to_nonerA   c                 C   sl   t | ddrtd |  D ]H}|jdk	r|r8d|_q|jjdk	rP|j  n|jd |j  qdS )a7  Sets gradients of all model parameters to zero. See similar function
        under :class:`torch.optim.Optimizer` for more context.

        Args:
            set_to_none (bool): instead of setting to zero, set the grads to None.
                See :meth:`torch.optim.Optimizer.zero_grad` for details.
        _is_replicaFaG  Calling .zero_grad() from a module created with nn.DataParallel() has no effect. The parameters are copied (in a differentiable manner) from the original module. This means they are not leaf nodes in autograd and so don't accumulate gradients. If you need gradients in your forward method, consider using autograd.grad instead.N)	r   r   r   r-  r   ry   Zdetach_r   Zzero_)r!   r=  r<  r$   r$   r%   	zero_grad\  s    
zModule.zero_gradc                 C   s   |  dd S )z&See :meth:`torch.Tensor.share_memory_`c                 S   s   |   S r   )Zshare_memory_r   r$   r$   r%   r   x  r   z%Module.share_memory.<locals>.<lambda>r   r    r$   r$   r%   share_memoryv  s    zModule.share_memoryc                 C   s   | j jS r   )r#   r&   r    r$   r$   r%   r   z  s    zModule._get_namec                 C   s   dS )zSet the extra representation of the module

        To print customized extra information, you should re-implement
        this method in your own modules. Both single-line and multi-line
        strings are acceptable.
        rh   r$   r    r$   r$   r%   
extra_repr}  s    zModule.extra_reprc           	      C   s   g }|   }|r|d}g }| j D ]0\}}t|}t|d}|d| d |  q(|| }|  d }|rt|dkr|s||d 7 }n|dd	| d 7 }|d7 }|S )	Nr+   r   (z): r,   r   z
  ))
rA  r3   ra   r   reprr9   r  r   r4   r6   )	r!   Zextra_linesrA  Zchild_linesr   r|   Zmod_strlinesZmain_strr$   r$   r%   r     s"    

zModule.__repr__c                 C   sl   t | j}t| j }t| j }t| j }t| j }|| | | | }dd |D }t|S )Nc                 S   s   g | ]}|d    s|qS r   )isdigit)r.   r   r$   r$   r%   r2     s      z"Module.__dir__.<locals>.<listcomp>)	dirr#   listrl   r  rW   ra   rX   sorted)r!   Zmodule_attrsattrsr-  r   r   r  r$   r$   r%   __dir__  s    
zModule.__dir__c                 C   sD   |  t| }| j |_t |_|j |_|j |_d|_|S )NT)	__new__rO   rl   copyr   rW   rX   ra   r>  )r!   Zreplicar$   r$   r%   _replicate_for_data_parallel  s    z#Module._replicate_for_data_parallel)T)N)N)N)...).).)F)T)rh   T)T)rh   T)T)rh   T)Nrh   T)T)T)F)]r&   r'   r(   __doc__rQ   r9  __annotations__rR   intr   rb   rP   rc   r   r   strr   rw   r   r{   r~   r   r   r   r   r   r   r   r   r   r	   r   r   r   r   r   r   rO   r   r   r   r   r   r   r   _grad_tr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r  r  r
  r  r  r   r%  r*  r   r-  r
   r,  r   r4  r   r5  r   r   r&  r:  r;  r   r?  r@  r   rA  r   rK  rN  r$   r$   r$   r%   r      s   
 6*D&%4+        k++4/$H
_ J
  	-	)0collectionsr   r   r  r   r   rU   r  r   Ztorch.utils.hooksutilsrB   r   r   r   typingr	   r
   r   r   r   r   r   r   r   r   r   r   Zutils.hooksr   rS  r   r   r9   r:   rQ  rP  r;   r9  r<   r=   r   rF   rG   rK   rL   rP   r   r$   r$   r$   r%   <module>   s:    8	  1