o
    h                 	   @   s  U d dl Z d dlZd dlZd dlZd dlZd dlmZmZ d dlm	Z	m
Z
 d dlmZmZmZmZmZmZ d dlmZ d dlZd dlmZmZmZ d dlmZ d dlmZmZ d d	lmZ d d
lm Z m!Z! g d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< e Z,e)e*ef e+d< e Z-e)e*ef e+d< G dd dZ.	 e Z/e)e*ef e+d< e Z0e)e*ef e+d< da1ee2 e+d< e Z3e)e*ef e+d< e Z4e)e*ef e+d < e Z5e)e*e2f e+d!< e Z6e)e*e2f e+d"< d#Z7d$ed% d&e!fd'd(Z8d$ed% d&e!fd)d*Z9d$ed% d&e!fd+d,Z:d$ed% d&e!fd-d.Z;d/d/d0d$ed% d1e2d2e2d&e!fd3d4Z<d$ede$e$gede$f f d&e!fd5d6Z=d$ede$gede$f f d&e!fd7d8Z>d$ede$e$gede$f f d&e!fd9d:Z?d;ed&dfd<d=Z@G d>d dZAdS )?    N)
namedtupleOrderedDict)IteratorMapping)AnyCallableOptionaloverloadTypeVarUnion)Self)devicedtypeTensor)DeviceLikeType)Buffer	Parameter)is_traceable_wrapper_subclass)BackwardHookRemovableHandle)	 register_module_forward_pre_hookregister_module_forward_hook&register_module_full_backward_pre_hookregister_module_backward_hook"register_module_full_backward_hook(register_module_buffer_registration_hook(register_module_module_registration_hook+register_module_parameter_registration_hookModule.Tr   boundc                       s$   e Zd ZdZ fddZeZ  ZS )_IncompatibleKeys c                    s   | j s| jsdS t  S )Nz<All keys matched successfully>)missing_keysunexpected_keyssuper__repr__self	__class__r#   k/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/modules/module.pyr'   -   s   
z_IncompatibleKeys.__repr__)__name__
__module____qualname__	__slots__r'   __str____classcell__r#   r#   r*   r,   r"   (   s    r"   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)s_r:   sfirstr#   r9   r,   
_addindent5   s   


rC   !_global_buffer_registration_hooks!_global_module_registration_hooks$_global_parameter_registration_hooksc                   @   sV   e Zd Zddeded fddZdeded	efd
dZd	efddZ	defddZ
dS )_WrappedHookNhookmoduler   c                 C   s:   || _ t| | d| _|d urt|| _d| _d S d S )NFT)rH   	functoolsupdate_wrapperwith_moduleweakrefrefrI   )r)   rH   rI   r#   r#   r,   __init__I   s   
z_WrappedHook.__init__argskwargsreturnc                 O   sF   | j r|  }|d u rtd| j|g|R i |S | j|i |S )Nz1You are trying to call the hook of a dead Module!)rL   rI   RuntimeErrorrH   )r)   rP   rQ   rI   r#   r#   r,   __call__S   s   z_WrappedHook.__call__c                 C   s$   | j | jd}| jr|  |d< |S )N)rH   rL   rI   )rH   rL   rI   )r)   resultr#   r#   r,   __getstate__[   s   z_WrappedHook.__getstate__statec                 C   sF   |d | _ |d | _| jr!|d d u rtdt|d | _d S d S )NrH   rL   rI   z3You are trying to revive the hook of a dead Module!)rH   rL   rS   rM   rN   rI   r)   rW   r#   r#   r,   __setstate__b   s   

z_WrappedHook.__setstate__N)r-   r.   r/   r   r   rO   r   rT   dictrV   rY   r#   r#   r#   r,   rG   H   s
    
rG   _global_backward_pre_hooks_global_backward_hooks_global_is_full_backward_hook_global_forward_pre_hooks_global_forward_hooks#_global_forward_hooks_always_called!_global_forward_hooks_with_kwargs_extra_staterH   ).NrR   c                 C      t t}| t|j< |S )a=  Register a buffer registration hook common to all modules.

    .. warning ::

        This adds global state to the `nn.Module` module

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

        hook(module, name, buffer) -> None or new buffer

    The hook can modify the input or return a single modified value in the hook.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )r   rD   idrH   handler#   r#   r,   r   |      
r   c                 C   rd   )aC  Register a module registration hook common to all modules.

    .. warning ::

        This adds global state to the `nn.Module` module

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

        hook(module, name, submodule) -> None or new submodule

    The hook can modify the input or return a single modified value in the hook.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )r   rE   re   rf   r#   r#   r,   r      rh   r   c                 C   rd   )aE  Register a parameter registration hook common to all modules.

    .. warning ::

        This adds global state to the `nn.Module` module

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

        hook(module, name, param) -> None or new parameter

    The hook can modify the input or return a single modified value in the hook.

    Returns:
        :class:`torch.utils.hooks.RemovableHandle`:
            a handle that can be used to remove the added hook by calling
            ``handle.remove()``
    )r   rF   re   rf   r#   r#   r,   r      rh   r   c                 C   rd   )a  Register 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()``
    )r   r_   re   rf   r#   r#   r,   r      s   
r   F)with_kwargsalways_callri   rj   c                C   s6   t ttd}| t|j< |rdt|j< |rdt|j< |S )a  Register 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``.
    You can optionally modify the output of the module by returning a new value
    that will replace the output from the :func:`forward` function.

    Parameters:
        hook (Callable): The user defined hook to be registered.
        always_call (bool): If ``True`` the ``hook`` will be run regardless of
            whether an exception is raised while calling the Module.
            Default: ``False``
    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``.
    
extra_dictT)r   r`   ra   re   rb   )rH   ri   rj   rg   r#   r#   r,   r      s   $


r   c                 C   *   t du rtdda tt}| t|j< |S )a  Register 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^   rS   r   r]   re   rf   r#   r#   r,   r     s   
r   c                 C   rd   )a  Register a backward pre-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.

    Hooks registered using this function behave in the same way as those
    registered by :meth:`torch.nn.Module.register_full_backward_pre_hook`.
    Refer to its documentation for more details.

    Hooks registered using this function will be called before hooks registered
    using :meth:`torch.nn.Module.register_full_backward_pre_hook`.

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

    )r   r\   re   rf   r#   r#   r,   r   6  s   
r   c                 C   rm   )a  Register 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.

    Hooks registered using this function behave in the same way as those
    registered by :meth:`torch.nn.Module.register_full_backward_hook`.
    Refer to its documentation for more details.

    Hooks registered using this function will be called before hooks registered
    using :meth:`torch.nn.Module.register_full_backward_hook`.

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

    Frn   Tro   rf   r#   r#   r,   r   Q  s   
r   inputc                 G   s   t dt| j d)a  Define 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" function)NotImplementedErrortyper-   )r)   rp   r#   r#   r,   _forward_unimplementedx  s   rs   c                       s  e Zd ZU dZdZeed< dZeed< 	 eed< e	e
ee f ed< e	e
ee f ed< ee
 ed	< e	eef ed
< e	eef ed< ee ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	eef ed< e	e
ed  f ed< dZeed< dZee ed< dڇ fddZeZedef ed< 	dd e
d!ee d"eddfd#d$Zd e
d%ee ddfd&d'Zd e
d(ed  ddfd)d*Zd e
d(ed  ddfd+d,Zd-e
dd fd.d/Z	dd-e
d(d d0eddfd1d2Zd-e
dd3fd4d5Zd-e
dd6fd7d8Zdefd9d:Zd;eddfd<d=Zdd>d?Z d@e!dAed gdf de!fdBdCZ"dd@e!dDee#ee$f  de!fdEdFZ%dd@e!dDee#ee$f  de!fdGdHZ&dd@e!dDee#ee$f  de!fdIdJZ'dd@e!dDee#ee$f  de!fdKdLZ(d@e!de!fdMdNZ)d@e!dOe#e*e
f de!fdPdQZ+d@e!de!fdRdSZ,d@e!de!fdTdUZ-d@e!de!fdVdWZ.d@e!de!fdXdYZ/ddZd@e!dDee0 d[ede!fd\d]Z1e2			ddDee0 d^ee* d_ede3fd`daZ4e2dd^e*d_ede3fdbdaZ4e2dd!ed_ede3fdcdaZ4ddda Z4	ddeed e5ge#de5f f dfede6fdgdhZ7deed e5e5ge#de5f f de6fdidjZ8	ddeed e5e5ge#de5f f dfede6fdkdlZ9dmdn Z:dodp Z;dqdr Z<dddsdee#ee!e=edf gee f ee!e=edf e	e
ef gee=ee	e
ef f  f f dfedtede6fdudvZ>ddddwdee#ee!e=edf egee f ee!e=edf e	e
ef egee f f dfedtedxede6f
dydzZ?d{d| Z@d}d~ ZAdd ZBeAZCedef ed< dd ZDdd ZEd e
de#ed f fddZFd e
de#ed f ddf fddZG fddZHdd ZIdd ZJdd ZKdd ZLeMde	e
ef dZNe2ddddeNde
dedeNfddZOe2dddde
dede	e
ef fddZOddddddZOdddZPdd ZQdd ZRdd ZS	ddeTe
ef d0edefddZU	ddefddZVdd[edeWe fddZX	dde
d[ededeWe=e
ef  fddZYdd[edeWe fddZZ	dde
d[ededeWe=e
ef  fddZ[deWd  fddZ\deWe=e
d f  fddZ]deWd  fddZ^			ddeed   de
defddZ_dd@e!dede!fddÄZ`d@e!de!fddńZadd@e!dede!fddȄZbddeddfdd˄Zcd@e!de!fdd̈́Zdddτ Zede
fddфZfddӄ ZgddՄ Zhddׄ Ziddل Zj  ZkS )r   a2  Base class for all neural network modules.

    Your models should also subclass this class.

    Modules can also contain other Modules, allowing them to be nested 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) -> None:
                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 also have their
    parameters converted 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_patchesr5   _versiontraining_parameters_buffers_non_persistent_buffers_set_backward_pre_hooks_backward_hooks_is_full_backward_hook_forward_hooks_forward_hooks_with_kwargs_forward_hooks_always_called_forward_pre_hooks_forward_pre_hooks_with_kwargs_state_dict_hooks_load_state_dict_pre_hooks_state_dict_pre_hooks_load_state_dict_post_hooks_modulescall_super_initN_compiled_call_implrR   c                    s  t jd | jdu r t|r tt| j dtt	| d| jdu r:t|r:tt| j dt
|d  d	 t dd	 t d
i  t di  t dt  t dt  t dt  t dd t dt  t dt  t dt  t dt  t dt  t dt  t dt  t dt  t dt  t di  | jrt j|i | dS dS )zLInitialize internal Module state, shared by both nn.Module and ScriptModule.zpython.nn_moduleFz0.__init__() got an unexpected keyword argument ''z,.__init__() takes 1 positional argument but r5   z were givenrv   Trw   rx   ry   rz   r{   r|   Nr}   r~   r   r   r   r   r   r   r   r   )torch_C_log_api_usage_oncer   bool	TypeErrorrr   r-   nextiterr=   r&   __setattr__setr   rO   r)   rP   rQ   r*   r#   r,   rO     s<   zModule.__init__.forwardTnametensor
persistentc                 C   s  |du rt | tjjrtdd| jvrtdt |ts'tdt	| d|v r/t
d|dkr7t
d	t| |rI|| jvrIt
d
| d|durat |tjsatdt	| d| dt D ]}|| ||}|durs|}qe|| j|< |r| j| dS | j| dS )a+  Add 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 (str): 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::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> 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 existsNcannot assign 'z' object to buffer 'z!' (torch Tensor or None required))
isinstancer   jitScriptModulerS   __dict__AttributeErrorstrr   typenameKeyErrorhasattrrx   r   rD   valuesry   discardadd)r)   r   r   r   rH   outputr#   r#   r,   register_buffer   s6   


zModule.register_bufferparamc                 C   s   d| j vr	tdt|tstdt| d|v r td|dkr(tdt| |r:|| j	vr:td| d	|d
u rEd
| j	|< d
S t|t
sXtdt| d| d|jrftd| d| dt D ]}|| ||}|d
urx|}qj|| j	|< d
S )a)  Add a parameter to the module.

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

        Args:
            name (str): 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 r   z parameter name can't contain "."r   z'parameter name can't be empty string ""r   r   Nr   z' object to parameter 'z'' (torch.nn.Parameter or None required)z,Cannot assign non-leaf Tensor to parameter 'z<'. Model parameters must be created explicitly. To express 'zM' as a function of another Tensor, compute the value in the forward() method.)r   r   r   r   r   r   r   r   r   rw   r   grad_fn
ValueErrorrF   r   )r)   r   r   rH   r   r#   r#   r,   register_parameter>  s@   


zModule.register_parameterrI   c                 C   s   t |ts|durtt| dt |ts"tdt| t| |r4|| jvr4td| dd|v r?td| |dkrGtd	t	
 D ]}|| ||}|durY|}qK|| j|< dS )
aY  Add a child module to the current module.

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

        Args:
            name (str): 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 r   r   r   z$module name can't contain ".", got: r   z$module name can't be empty string "")r   r   r   r   r   r   r   r   r   rE   r   )r)   r   rI   rH   r   r#   r#   r,   
add_modulep  s$   

zModule.add_modulec                 C   s   |  || dS )zAlias for :func:`add_module`.N)r   )r)   r   rI   r#   r#   r,   register_module  s   zModule.register_moduletargetc                 C   sr   |dkr| S | d}| }|D ]'}t||s"t| d | d t||}t|tjjs6td| d q|S )a?  Return the submodule given by ``target`` if it exists, otherwise throw 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`` which 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 at any point along the path resulting from
                the target string the (sub)path resolves to a non-existent
                attribute name or an object that is not an instance of ``nn.Module``.
        r   r    has no attribute ``` is not an nn.Module)	r<   r   r   	_get_namegetattrr   r   nnr   )r)   r   atomsmoditemr#   r#   r,   get_submodule  s   .


zModule.get_submodulestrictc                 C   s   |dkrt d|d}t|tjjst ddt|  t|dkr(| }nd|dd }| 	|}|rMt
||d sMt| d	 |d  d
 t
||d rlt||d }t|tjjsltd
|d  d t||d | dS )a	  
        Set the submodule given by ``target`` if it exists, otherwise throw an error.

        .. note::
            If ``strict`` is set to ``False`` (default), the method will replace an existing submodule
            or create a new submodule if the parent module exists. If ``strict`` is set to ``True``,
            the method will only attempt to replace an existing submodule and throw an error if
            the submodule does not exist.

        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(3, 3, 3)
                    )
                    (linear): Linear(3, 3)
                )
            )

        (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 override the ``Conv2d`` with a new submodule ``Linear``, you
        could call ``set_submodule("net_b.net_c.conv", nn.Linear(1, 1))``
        where ``strict`` could be ``True`` or ``False``

        To add a new submodule ``Conv2d`` to the existing ``net_b`` module,
        you would call ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1))``.

        In the above if you set ``strict=True`` and call
        ``set_submodule("net_b.conv", nn.Conv2d(1, 1, 1), strict=True)``, an AttributeError
        will be raised because ``net_b`` does not have a submodule named ``conv``.

        Args:
            target: The fully-qualified string name of the submodule
                to look for. (See above example for how to specify a
                fully-qualified string.)
            module: The module to set the submodule to.
            strict: If ``False``, the method will replace an existing submodule
                or create a new submodule if the parent module exists. If ``True``,
                the method will only attempt to replace an existing submodule and throw an error
                if the submodule doesn't already exist.

        Raises:
            ValueError: If the ``target`` string is empty or if ``module`` is not an instance of ``nn.Module``.
            AttributeError: If at any point along the path resulting from
                the ``target`` string the (sub)path resolves to a non-existent
                attribute name or an object that is not an instance of ``nn.Module``.
        r   z/Cannot set the submodule without a target name!r   z`modulez` is not an nn.Module, found r5   Nr   r   r   )r   r<   r   r   r   r   rr   r=   r?   r   r   r   r   r   setattr)r)   r   rI   r   r   parent
parent_keyr   r#   r#   r,   set_submodule  s(   9

zModule.set_submoduler   c                 C   sh   | d\}}}| |}t||st| d | d t||}t|tjj	s2td| d |S )a  Return the parameter given by ``target`` if it exists, otherwise throw 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``
        r   r   r   z` is not an nn.Parameter)

rpartitionr   r   r   r   r   r   r   r   r   )r)   r   module_path_
param_namer   r   r#   r#   r,   get_parameter"  s   


zModule.get_parameterr   c                 C   sd   | d\}}}| |}t||st| d | d t||}||jvr0td| d |S )a  Return the buffer given by ``target`` if it exists, otherwise throw 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
        r   r   r   z` is not a buffer)r   r   r   r   r   r   rx   )r)   r   r   r   buffer_namer   bufferr#   r#   r,   
get_bufferF  s   



zModule.get_bufferc                 C      t d)a  Return 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 picklable to ensure working serialization
        of the state_dict. We only 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.rS   r(   r#   r#   r,   get_extra_statej  s   zModule.get_extra_staterW   c                 C   r   )a  Set extra state contained in the loaded `state_dict`.

        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.r   rX   r#   r#   r,   set_extra_state  s   zModule.set_extra_statec                 C   sd  |r|   D ]}|| qdd }tj }| j D ]\}}|d u r%qt  ||}W d    n1 s8w   Y  |||}	|pGt|}
|j	}|
rz|d urUd |_	tj
j||jd}tj|| W n  ty } z|d uru||_	td|   d| |d }~ww |}n|	r||_|}nt|tsJ |jsJ t||j}|| j|< |d urt  ||}W d    n1 sw   Y  |||}|
r||j z	tj|| W n ty } ztd|   d| d|d }~ww ||_	q|r|j	d usJ ||j	_q|jsJ ||j|_	q| j D ]\}}|d ur.||| j|< q| S )Nc                 S   s   t | |rt j  S dS NF)r   !_has_compatible_shallow_copy_type
__future__)get_overwrite_module_params_on_conversion)r   tensor_appliedr#   r#   r,   compute_should_use_set_data  s   	z2Module._apply.<locals>.compute_should_use_set_datarequires_gradz_apply(): Couldn't swap r   z.grad)children_applyr   r   $get_swap_module_params_on_conversionrw   itemsno_gradr   gradr   r   r   utilsswap_tensors	ExceptionrS   r   datar   is_leafrequires_grad_rx   )r)   fnrecurserI   r   should_use_swap_tensorskeyr   param_appliedp_should_use_set_datap_should_use_swap_tensors
param_grade	out_paramgrad_appliedg_should_use_set_databufr#   r#   r,   r     s   










zModule._applyr)   r   c                 C   s$   |   D ]}|| q||  | S )a  Apply ``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.]], requires_grad=True)
            Linear(in_features=2, out_features=2, bias=True)
            Parameter containing:
            tensor([[1., 1.],
                    [1., 1.]], requires_grad=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   rI   r#   r#   r,   r     s   $zModule.applyr   c                       |   fddS )a  Move all model parameters and buffers to the GPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing the 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 rZ   )cudatr   r#   r,   <lambda>)     
 zModule.cuda.<locals>.<lambda>r   r)   r   r#   r   r,   r        zModule.cudac                    r   )a  Move all model parameters and buffers to the IPU.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing the 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                    r   rZ   )ipur   r   r#   r,   r   <  r   zModule.ipu.<locals>.<lambda>r   r   r#   r   r,   r   +  r   z
Module.ipuc                    r   )a  Move 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                    r   rZ   )xpur   r   r#   r,   r   O  r   zModule.xpu.<locals>.<lambda>r   r   r#   r   r,   r   >  r   z
Module.xpuc                    r   )a   Move all model parameters and buffers to the MTIA.

        This also makes associated parameters and buffers different objects. So
        it should be called before constructing the optimizer if the module will
        live on MTIA 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                    r   rZ   )mtiar   r   r#   r,   r   b  r   zModule.mtia.<locals>.<lambda>r   r   r#   r   r,   r   Q  r   zModule.mtiac                 C      |  dd S )zMove all model parameters and buffers to the CPU.

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

        Returns:
            Module: self
        c                 S      |   S rZ   )cpur   r#   r#   r,   r   m      zModule.cpu.<locals>.<lambda>r   r(   r#   r#   r,   r   d     	z
Module.cpudst_typec                    r   )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                    r   rZ   )rr   r   r  r#   r,   r   {  r   zModule.type.<locals>.<lambda>r   )r)   r  r#   r  r,   rr   o  s   zModule.typec                 C   r   )zCasts all floating point parameters and buffers to ``float`` datatype.

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

        Returns:
            Module: self
        c                 S      |   r|  S | S rZ   )is_floating_pointfloatr   r#   r#   r,   r         zModule.float.<locals>.<lambda>r   r(   r#   r#   r,   r  }  r  zModule.floatc                 C   r   )zCasts all floating point parameters and buffers to ``double`` datatype.

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

        Returns:
            Module: self
        c                 S   r  rZ   )r  doubler   r#   r#   r,   r     r  zModule.double.<locals>.<lambda>r   r(   r#   r#   r,   r	    r  zModule.doublec                 C   r   )zCasts all floating point parameters and buffers to ``half`` datatype.

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

        Returns:
            Module: self
        c                 S   r  rZ   )r  halfr   r#   r#   r,   r     r  zModule.half.<locals>.<lambda>r   r(   r#   r#   r,   r
    r  zModule.halfc                 C   r   )zCasts all floating point parameters and buffers to ``bfloat16`` datatype.

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

        Returns:
            Module: self
        c                 S   r  rZ   )r  bfloat16r   r#   r#   r,   r     r  z!Module.bfloat16.<locals>.<lambda>r   r(   r#   r#   r,   r    r  zModule.bfloat16r   r   c                   s   | j  fdd|dS )a  Move 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.
            recurse (bool): Whether parameters and buffers of submodules should
                be recursively moved to the specified device.

        Returns:
            Module: self
        c                    s   t j|  dS )Nr   )r   
empty_liker   r   r#   r,   r     s    z!Module.to_empty.<locals>.<lambda>r  r   )r)   r   r   r#   r   r,   to_empty  s   zModule.to_emptyr   non_blockingc                 C      d S rZ   r#   )r)   r   r   r  r#   r#   r,   to     z	Module.toc                 C   r  rZ   r#   )r)   r   r  r#   r#   r,   r       c                 C   r  rZ   r#   )r)   r   r  r#   r#   r,   r    r  c                    sj   t jjj|i |\ dur'jsjstd jr'td  fdd}| 	|S )a  Move and/or cast 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::

            >>> # xdoctest: +IGNORE_WANT("non-deterministic")
            >>> 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)
            >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_CUDA1)
            >>> 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)

        NzRnn.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   z3 d ur|   dv r| j|  s|  rnd  dW S | |  s*|  r/W S d W S  tyN } zt|dkrIt| dd  d }~ww )N)      )memory_formatz(Cannot copy out of meta tensor; no data!zz Please use torch.nn.Module.to_empty() instead of torch.nn.Module.to() when moving module from meta to a different device.)dimr  r  
is_complexrq   r   )r   r   convert_to_formatr   r   r  r#   r,   convert4  s4   zModule.to.<locals>.convert)
r   r   _nn	_parse_tor  r  r   warningswarnr   )r)   rP   rQ   r  r#   r  r,   r    s$   V
rH   prependc                 C   s0   t | j}|| j|j< |r| jj|jdd |S )a  Register a backward pre-hook on the module.

        The hook will be called every time the gradients for the module are computed.
        The hook should have the following signature::

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

        The :attr:`grad_output` is a tuple. The hook should
        not modify its arguments, but it can optionally return a new gradient with
        respect to the output that will be used in place of :attr:`grad_output` in
        subsequent computations. Entries in :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 inplace is not allowed when using backward hooks and
            will raise an error.

        Args:
            hook (Callable): The user-defined hook to be registered.
            prepend (bool): If true, the provided ``hook`` will be fired before
                all existing ``backward_pre`` hooks on this
                :class:`torch.nn.Module`. Otherwise, the provided
                ``hook`` will be fired after all existing ``backward_pre`` hooks
                on this :class:`torch.nn.Module`. Note that global
                ``backward_pre`` hooks registered with
                :func:`register_module_full_backward_pre_hook` will fire before
                all hooks registered by this method.

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

        Flast)r   rz   re   move_to_endr)   rH   r   rg   r#   r#   r,   register_full_backward_pre_hookM  s
   
+z&Module.register_full_backward_pre_hookc                 C   s2   | j du r	tdd| _ t| j}|| j|j< |S )a  Register 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)r|   rS   r   r{   re   r)   rH   rg   r#   r#   r,   register_backward_hook~  s   

zModule.register_backward_hookc                 C   sH   | j du r	tdd| _ t| j}|| j|j< |r"| jj|jdd |S )a  Register a backward hook on the module.

        The hook will be called every time the gradients with respect to a module
        are computed, i.e. the hook will execute if and only if the gradients with
        respect to module outputs 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.

        Args:
            hook (Callable): The user-defined hook to be registered.
            prepend (bool): If true, the provided ``hook`` will be fired before
                all existing ``backward`` hooks on this
                :class:`torch.nn.Module`. Otherwise, the provided
                ``hook`` will be fired after all existing ``backward`` hooks on
                this :class:`torch.nn.Module`. Note that global
                ``backward`` hooks registered with
                :func:`register_module_full_backward_hook` will fire before
                all hooks registered by this method.

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

        Fr&  Tr!  )r|   rS   r   r{   re   r#  r$  r#   r#   r,   register_full_backward_hook  s   
0
z"Module.register_full_backward_hookc                 C   sh   g }t du r|t 7 }| jdu r|| j 7 }g }t du r$|t 7 }| jdu r0|| j 7 }||fS )zReturn 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]   r   r|   r{   )r)   full_backward_hooksnon_full_backward_hooksr#   r#   r,   _get_backward_hooks  s   

zModule._get_backward_hooksc                 C   s"   g }|t  7 }|| j 7 }|S rZ   )r\   r   rz   )r)   backward_pre_hooksr#   r#   r,   _get_backward_pre_hooks  s   zModule._get_backward_pre_hooksc                 C   s(  t |tjst |trtdd |D stjdtdd d S n|f}t |tjsAt |tr6tdd |D s@tjdtdd d S n|f}dd	 |D }t|d
ks[t|dkre||vretjdtdd d S t|dkrutjdtdd d S dd	 |D }dd	 |j	D }||krtjdtdd d S d S )Nc                 s       | ]	}t |tjV  qd S rZ   r   r   r   r7   rr#   r#   r,   	<genexpr>      z<Module._maybe_warn_non_full_backward_hook.<locals>.<genexpr>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.   
stacklevelc                 s   r/  rZ   r0  r7   ir#   r#   r,   r3    r4  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      h | ]
}|j d ur|j qS rZ   r   r1  r#   r#   r,   	<setcomp>      z<Module._maybe_warn_non_full_backward_hook.<locals>.<setcomp>r   r5   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   r:  rZ   r;  r8  r#   r#   r,   r<  *  r=  c                 S   s   h | ]}|d  qS r   r#   )r7   nr#   r#   r,   r<  ,  r  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.)
r   r   r   tupleallr  r  FutureWarningr=   next_functions)r)   inputsrU   r   out_grad_fninputs_grad_fnrC  r#   r#   r,   "_maybe_warn_non_full_backward_hook  sb   

	
z)Module._maybe_warn_non_full_backward_hook)r   ri   ri   c                C   sF   t | j| jd}|| j|j< |rd| j|j< |r!| jj|jdd |S )a  Register a forward pre-hook on the module.

        The hook will be called every time before :func:`forward` is invoked.


        If ``with_kwargs`` is false or not specified, 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). The hook should have the
        following signature::

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

        If ``with_kwargs`` is true, the forward pre-hook will be passed the
        kwargs given to the forward function. And if the hook modifies the
        input, both the args and kwargs should be returned. The hook should have
        the following signature::

            hook(module, args, kwargs) -> None or a tuple of modified input and kwargs

        Args:
            hook (Callable): The user defined hook to be registered.
            prepend (bool): If true, the provided ``hook`` will be fired before
                all existing ``forward_pre`` hooks on this
                :class:`torch.nn.Module`. Otherwise, the provided
                ``hook`` will be fired after all existing ``forward_pre`` hooks
                on this :class:`torch.nn.Module`. Note that global
                ``forward_pre`` hooks registered with
                :func:`register_module_forward_pre_hook` will fire before all
                hooks registered by this method.
                Default: ``False``
            with_kwargs (bool): If true, the ``hook`` will be passed the kwargs
                given to the forward function.
                Default: ``False``

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        rk   TFr!  )r   r   r   re   r#  )r)   rH   r   ri   rg   r#   r#   r,   register_forward_pre_hook8  s   7z Module.register_forward_pre_hook)r   ri   rj   rj   c                C   s\   t | j| j| jgd}|| j|j< |rd| j|j< |r!d| j|j< |r,| jj|jdd |S )af  Register a forward hook on the module.

        The hook will be called every time after :func:`forward` has computed an output.

        If ``with_kwargs`` is ``False`` or not specified, 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. The hook
        should have the following signature::

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

        If ``with_kwargs`` is ``True``, the forward hook will be passed the
        ``kwargs`` given to the forward function and be expected to return the
        output possibly modified. The hook should have the following signature::

            hook(module, args, kwargs, output) -> None or modified output

        Args:
            hook (Callable): The user defined hook to be registered.
            prepend (bool): If ``True``, the provided ``hook`` will be fired
                before all existing ``forward`` hooks on this
                :class:`torch.nn.Module`. Otherwise, the provided
                ``hook`` will be fired after all existing ``forward`` hooks on
                this :class:`torch.nn.Module`. Note that global
                ``forward`` hooks registered with
                :func:`register_module_forward_hook` will fire before all hooks
                registered by this method.
                Default: ``False``
            with_kwargs (bool): If ``True``, the ``hook`` will be passed the
                kwargs given to the forward function.
                Default: ``False``
            always_call (bool): If ``True`` the ``hook`` will be run regardless of
                whether an exception is raised while calling the Module.
                Default: ``False``

        Returns:
            :class:`torch.utils.hooks.RemovableHandle`:
                a handle that can be used to remove the added hook by calling
                ``handle.remove()``
        rk   TFr!  )r   r}   r~   r   re   r#  )r)   rH   r   ri   rj   rg   r#   r#   r,   register_forward_hookz  s   5zModule.register_forward_hookc                 O   s   t j }|rt| jt jjr| j|i |S t jjjd u}|r:| t jjjv r.t jjj|  nd }|r8|	| nd}z| j|i |}W |rJ|
  |S |rS|
  w w r   )r   r   _get_tracing_stater   r   ScriptMethodr   _trace_trace_module_map
push_scope	pop_scope)r)   rp   rQ   tracing_staterecording_scopesr   rU   r#   r#   r,   _slow_forward  s"   
 
zModule._slow_forwardc                 O   s*   | j d ur| j |i |S | j|i |S rZ   )r   
_call_implr   r#   r#   r,   _wrapped_call_impl  s   
zModule._wrapped_call_implc                    s  t j rjnjjs&js&js&js&t	s&t
s&ts&ts& i S d t  fdd}t j r>| S z| W S  ty   t D ]7\}}|tv r|vrz| }|d urf|W qM ty } ztdt|  W Y d }~qMd }~ww qMj D ]E\}}|jv r|vrz|jv r| }n| }|d ur|W q ty } ztdt|  W Y d }~qd }~ww q w )Nc                     sH  g g } }g }j str }jstr \} }ts jrlg t j R D ]?\}}|j	v rX| }|d urWt
|trOt|dkrO|\ q,td| dq,| }|d urkt
|tsi|f}| q,d }| sr|r}t| |}|   i tsjrg t j R D ]/\}}|jv s|tv r| |jv s|tv r| }n| }|d ur|q|rt
tjtfstdt  ||r"}	t
|	tjst
|	trtdd |	 D }	n|	d }	t
|	tjr|	j }
|
d ur"|D ]}|
!t"| q# |
 S )Nr5  zPforward pre-hook must return None or a tuple of (new_args, new_kwargs), but got r   zeFor backward hooks to be called, module output should be a Tensor or a tuple of Tensors but received c                 s   s     | ]}t |tjr|V  qd S rZ   r0  )r7   vr#   r#   r,   r3  +  s    z3Module._call_impl.<locals>.inner.<locals>.<genexpr>r   )$rz   r\   r.  r{   r]   r,  r_   r   r   r   r   r@  r=   rS   r   setup_input_hookr`   r}   r   ra   r   r~   rb   r   r   r  r  rr   setup_output_hookr[   r   r   r   register_hookrG   rG  )r*  r+  r-  hook_idrH   args_kwargs_resultargs_resultbw_hookhook_resultvarr   rP   called_always_called_hooksforward_callrQ   rU   r)   r#   r,   inner  s   






	






z Module._call_impl.<locals>.innerzglobal module forward hook with ``always_call=True`` raised an exception that was silenced as another error was raised in forward: z|module forward hook with ``always_call=True`` raised an exception that was silenced as another error was raised in forward: )r   r   rJ  rR  r   r{   rz   r}   r   r\   r]   r`   r_   r   compileris_compilingr   r   ra   r  r  r   r   r~   )r)   rP   rQ   rb  rY  rH   r]  r   r#   r_  r,   rS    sj   
V
zModule._call_implrT   c                 C   s   | j  }|dd  |S )Nr   )r   copyr>   rX   r#   r#   r,   rV   d  s   
zModule.__getstate__c                 C   s   | j | d| j vrt | _d| j vrt | _d| j vr!t | _d| j vr*t | _d| j vr3t | _d| j vr<t | _d| j vrEt | _	d| j vrNt | _
d	| j vrWt | _d
| j vr_d | _d| j vrjt | _d S d S )Nr   r   r~   r   r   r   r   r   ry   r|   rz   )r   updater   r   r   r~   r   r   r   r   r   r   ry   r|   rz   rX   r#   r#   r,   rY   i  s0   










zModule.__setstate__c                 C   s   d| j v r| j d }||v r|| S d| j v r$| j d }||v r$|| S d| j v r6| j d }||v r6|| S tdt| j d| d)Nrw   rx   r   r   z' object has no attribute ')r   r   rr   r-   )r)   r   rw   rx   modulesr#   r#   r,   __getattr__  s   





zModule.__getattr__valuec                    sd   fdd}| j d}t|tr,|d u rtd|| j | j| j| j |  | d S |d urN |v rN|d urFt	dt
| d  d|  | d S | j d}t|tr|d u ratd	|| j | j| j| j t D ]}||  |}|d ur~|}qp|| < d S |d ur |v r|d urt	dt
| d
  dt D ]}||  |}|d ur|}q|| < d S | j d}t|ts|d ur) |v r)|d urt|t
jst	dt
| d  dt|tr|j}	n | jv}	| jt
jjju r|  ||	 d S t| j}
d|
jv r|  ||	 d S |	s!td|  | d S t  | d S )Nc                     s2   | D ]} |v rt |tr| = q|  qd S rZ   )r   r[   r   )dicts_or_setsdr   r#   r,   remove_from  s   

z'Module.__setattr__.<locals>.remove_fromrw   z6cannot assign parameters before Module.__init__() callr   z' as parameter 'z'' (torch.nn.Parameter or None expected)r   z2cannot assign module before Module.__init__() callz' as child module 'z$' (torch.nn.Module or None expected)rx   z' as buffer 'z2' (torch.nn.Buffer, torch.Tensor or None expected)r   zRegistering a non-persistent buffer on a Module subclass that implements register_buffer() without the persistent argument is not allowed.)r   getr   r   r   rx   r   ry   r   r   r   r   r   rw   rE   r   r   r   r   r   r   inspect	signature
parametersrS   r&   r   )r)   r   ri  rm  paramsrg  rH   r   buffersr   signr*   rl  r,   r     s   



	zModule.__setattr__c                    s^   || j v r| j |= d S || jv r| j|= | j| d S || jv r'| j|= d S t | d S rZ   )rw   rx   ry   r   r   r&   __delattr__)r)   r   r*   r#   r,   ru    s   


zModule.__delattr__c                 C   s.   t |ddr
tdt| j}|| j|j< |S )a  Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method.

        It should have the following signature::
            hook(module, state_dict, prefix, local_metadata) -> None or state_dict

        The registered hooks can modify the ``state_dict`` inplace or return a new one.
        If a new ``state_dict`` is returned, it will only be respected if it is the root
        module that :meth:`~nn.Module.state_dict` is called from.
        _from_public_apiFz~Cannot register the same function as the state dict post hook that was previously registered via register_state_dict_post_hook)r   rS   r   r   re   r'  r#   r#   r,   _register_state_dict_hook  s   

z Module._register_state_dict_hookc                 C   s    d|_ t| j}|| j|j< |S )a  Register a post-hook for the :meth:`~torch.nn.Module.state_dict` method.

        It should have the following signature::
            hook(module, state_dict, prefix, local_metadata) -> None

        The registered hooks can modify the ``state_dict`` inplace.
        T)rv  r   r   re   r'  r#   r#   r,   register_state_dict_post_hook  s   
z$Module.register_state_dict_post_hookc                 C      t | j}|| j|j< |S )a*  Register a pre-hook for the :meth:`~torch.nn.Module.state_dict` method.

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

        The registered hooks can be used to perform pre-processing before the ``state_dict``
        call is made.
        )r   r   re   r'  r#   r#   r,   register_state_dict_pre_hook1  s   
	z#Module.register_state_dict_pre_hookc                 C   s   | j  D ]\}}|dur|r|n| ||| < q| j D ]\}}|dur8|| jvr8|r0|n| ||| < q|t }t| jdtj	tj	urP| 	 ||< dS dS )a+  Save module state to the `destination` dictionary.

        The `destination` dictionary will contain the 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   ry   _EXTRA_STATE_KEY_SUFFIXr   r+   r   r   )r)   destinationprefix	keep_varsr   r   r   extra_state_keyr#   r#   r,   _save_to_state_dict>  s   zModule._save_to_state_dictT_destinationr    )r~  r  r}  r~  r  c                C   r  rZ   r#   )r)   r}  r~  r  r#   r#   r,   
state_dict^  s   zModule.state_dictc                C   r  rZ   r#   )r)   r~  r  r#   r#   r,   r  d  r  r   r}  r~  r  c          
      G   sL  t |dkr2tjdtdd |du r|d }t |dkr$|dkr$|d }t |dkr2|du r2|d }|du r=t }t |_t| jd	}t|d
rQ||j|dd < | j	
 D ]}|| || qV| ||| | j D ]\}}|dur|j||| d |d qk| j
 D ]}|| |||}	t|dds|	dur|	}q|	durtdq|S )a  Return a dictionary containing references to the 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.

        .. note::
            The returned object is a shallow copy. It contains references
            to the module's parameters and buffers.

        .. 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::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> module.state_dict().keys()
            ['bias', 'weight']

        r   zPositional args are being deprecated, use kwargs instead. Refer to https://pytorch.org/docs/main/generated/torch.nn.Module.html#torch.nn.Module.state_dict for details.r5  r6  Nr5   r   F)version	_metadatar   r   r  rv  z%state_dict post-hook must return None)r=   r  r  rB  r   r  r[   ru   r   r   r   r  r   r   r  r   r   rS   )
r)   r}  r~  r  rP   local_metadatarH   r   rI   r]  r#   r#   r,   r  j  sN   -

c                 C   s(   t | j}t||r| nd| j|j< |S )a|  See :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` for details.

        A subtle difference is that if ``with_module`` is set to ``False``, then the
        hook will not take the ``module`` as the first argument whereas
        :meth:`~torch.nn.Module.register_load_state_dict_pre_hook` always takes the
        ``module`` as the first argument.

        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.
        N)r   r   rG   re   )r)   rH   rL   rg   r#   r#   r,   "_register_load_state_dict_pre_hook  s
   
z)Module._register_load_state_dict_pre_hookc                 C   s   | j |ddS )a  Register a pre-hook to be run before module's :meth:`~nn.Module.load_state_dict` is called.

        It should have the following signature::
            hook(module, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs) -> None  # noqa: B950

        Arguments:
            hook (Callable): Callable hook that will be invoked before
                loading the state dict.
        T)rL   )r  )r)   rH   r#   r#   r,   !register_load_state_dict_pre_hook  s   
z(Module.register_load_state_dict_pre_hookc                 C   ry  )a  Register a post-hook to be run after module's :meth:`~nn.Module.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
        clearing 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()``
        )r   r   re   r'  r#   r#   r,   "register_load_state_dict_post_hook  s   
z)Module.register_load_state_dict_post_hookc                    s   j  D ]}|||||||| q fdd j D }	t j |	 }
dd |
D }|dd}tj	
 }| D ]2\}}|| }||v rj|| }tj|se|d| dt|  q?tjj|}|st|jdkrt|jd	kr|d }|s|j|jkr|d
| d|j d|j d q?|jr|js|std| d zt { |r|j||d}t|t|kst|t|krtdt|tjjrt|tjjstjj||jd}n||j tj || ~n/|rt|tjjrt|tjjstjj||jd}n||j t! || n|"| W d   n	1 s/w   Y  W q? t#yi } z'|rCdnd}|d| d| d|$  d|$  d|j% d W Y d}~q?d}~ww |rr|| q?|t& }t' j(dt)j*t)j*ur||v r *||  n|r|| n|r||v r|| |r|+ D ]>}|,|r||kr|t|d -dd	}t|d	kr|d  j.vr|| q|d |vr|| qdS dS )aF  Copy 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)`.
        Additionally, :attr:`local_metadata` can also contain the key
        `assign_to_params_buffers` that indicates whether keys should be
        assigned their corresponding tensor in the state_dict.

        .. 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 vr||qS r#   )ry   r7   krU  r(   r#   r,   
<dictcomp>8	  s
    
z0Module._load_from_state_dict.<locals>.<dictcomp>c                 S   s   i | ]\}}|d ur||qS rZ   r#   r  r#   r#   r,   r  @	  s    assign_to_params_buffersFz#While copying the parameter named "zL", expected torch.Tensor or Tensor-like object from checkpoint but received r   r5   zsize mismatch for z: copying a param with shape z0 from checkpoint, the shape in current model is r   zfor a	  : copying from a non-meta parameter in the checkpoint to a meta parameter in the current model, which is a no-op. (Did you mean to pass `assign=True` to assign items in the state dictionary to their corresponding key in the module instead of copying them in place?))assignztmodule_load returned one of self or other, please .detach() the result if returning one of the inputs in module_loadr   NswappingcopyingzWhile z the parameter named "z%", whose dimensions in the model are z, and whose dimensions in the checkpoint are z, an exception occurred : r   )/r   r   rx   r   	itertoolschainrw   rn  r   r   r   	overridesis_tensor_likeappendrr   r   	parameteris_lazyr=   shapeis_metar  r  r   module_loadre   rS   r   r   r   r   r   r   r   copy_r   sizerP   r|  r   r+   r   r   keys
startswithr<   r   )r)   r  r~  r  r   r$   r%   
error_msgsrH   persistent_bufferslocal_name_paramslocal_stater  use_swap_tensorsr   r   r   input_paramis_param_lazynew_input_paramexactionr  
input_namer#   r(   r,   _load_from_state_dict 	  s   -






"





zModule._load_from_state_dictr  r  c              	      s   t |tstdt| dg g g t|ddt|}dur&|_d fdd	| | |rhtdkrQdd		d

dd D  tdkrhdd	d

dd D  tdkr{td	| jjd
tS )a  Copy 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.

        .. warning::
            If :attr:`assign` is ``True`` the optimizer must be created after
            the call to :attr:`load_state_dict` unless
            :func:`~torch.__future__.get_swap_module_params_on_conversion` is ``True``.

        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``
            assign (bool, optional): When set to ``False``, the properties of the tensors
                in the current module are preserved whereas setting it to ``True`` preserves
                properties of the Tensors in the state dict. The only
                exception is the ``requires_grad`` field of :class:`~torch.nn.Parameter`s
                for which the value from the module is preserved.
                Default: ``False``

        Returns:
            ``NamedTuple`` with ``missing_keys`` and ``unexpected_keys`` fields:
                * **missing_keys** is a list of str containing any keys that are expected
                    by this module but missing from the provided ``state_dict``.
                * **unexpected_keys** is a list of str containing the keys that are not
                    expected by this module but present in the provided ``state_dict``.

        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   r  Nr   c           
   	      s   d u ri n	 |d d i }r|d< | |||d | j D ]\}}|d urE|| d   fdd| D }||  q&t}| j D ]}|| |}	|	d u s_J dqPd S )Nr   r  Tr   c                    s    i | ]\}}|  r||qS r#   )r  r  child_prefixr#   r,   r  	  s    z8Module.load_state_dict.<locals>.load.<locals>.<dictcomp>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.)rn  r  r   r   r"   r   r   )
rI   local_state_dictr~  r  r   childchild_state_dictincompatible_keysrH   outr  r  loadmetadatar$   r%   r  r,   r  	  s6    	



z$Module.load_state_dict.<locals>.loadr   z%Unexpected key(s) in state_dict: {}. z, c                 s       | ]	}d | d V  qdS "Nr#   r7   r  r#   r#   r,   r3  
  r4  z)Module.load_state_dict.<locals>.<genexpr>z"Missing key(s) in state_dict: {}. c                 s   r  r  r#   r  r#   r#   r,   r3  
  r4  z*Error(s) in loading state_dict for {}:
	{}z
	)r   )r   r   r   rr   r   r   r  r=   insertformatr?   rS   r+   r-   r"   )r)   r  r   r  r#   r  r,   load_state_dict	  sH   
'
!
zModule.load_state_dictremove_duplicatec                 c   s    t  }|r| j||dn|| fg}|D ].\}}||}	|	D ]#\}
}|du s*||v r+q|r2|| ||r7dnd |
 }||fV  qqdS )z.Help yield various names + members of modules.)r~  r  Nr   r   )r   named_modulesr   )r)   get_members_fnr~  r   r  memorg  module_prefixrI   membersr  rU  r   r#   r#   r,   _named_members(
  s"   
zModule._named_membersc                 c   "    | j |dD ]\}}|V  qdS )a  Return 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::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> 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   _namer   r#   r#   r,   rq  <
  s   zModule.parametersc                 c   &    | j dd |||d}|E dH  dS )aU  Return 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.
            remove_duplicate (bool, optional): whether to remove the duplicated
                parameters in the result. Defaults to True.

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

        Example::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> for name, param in self.named_parameters():
            >>>     if name in ['bias']:
            >>>         print(param.size())

        c                 S   
   | j  S rZ   )rw   r   rI   r#   r#   r,   r   n
  r   z)Module.named_parameters.<locals>.<lambda>r~  r   r  Nr  r)   r~  r   r  genr#   r#   r,   r  U
  s   zModule.named_parametersc                 c   r  )a@  Return 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::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> 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,   rs  u
  s   zModule.buffersc                 c   r  )aL  Return 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, optional): if True, then yields buffers of this module
                and all submodules. Otherwise, yields only buffers that
                are direct members of this module. Defaults to True.
            remove_duplicate (bool, optional): whether to remove the duplicated buffers in the result. Defaults to True.

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

        Example::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> for name, buf in self.named_buffers():
            >>>     if name in ['running_var']:
            >>>         print(buf.size())

        c                 S   r  rZ   )rx   r   r  r#   r#   r,   r   
  r   z&Module.named_buffers.<locals>.<lambda>r  Nr  r  r#   r#   r,   r  
  s   zModule.named_buffersc                 c       |   D ]\}}|V  qdS )zpReturn an iterator over immediate children modules.

        Yields:
            Module: a child module
        N)named_children)r)   r  rI   r#   r#   r,   r   
  s   zModule.childrenc                 c   sD    t  }| j D ]\}}|dur||vr|| ||fV  q	dS )a  Return an iterator over immediate children modules, yielding both the name of the module as well as the module itself.

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

        Example::

            >>> # xdoctest: +SKIP("undefined vars")
            >>> for name, module in model.named_children():
            >>>     if name in ['conv4', 'conv5']:
            >>>         print(module)

        N)r   r   r   r   )r)   r  r   rI   r#   r#   r,   r  
  s   

zModule.named_childrenc                 c   r  )a  Return 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   rI   r#   r#   r,   rg  
  s   zModule.modulesr  c                 c   s~    |du rt  }| |vr;|r||  || fV  | j D ]\}}|du r&q||r+dnd | }||||E dH  qdS dS )a<  Return 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:
            (str, 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))

        Nr   r   )r   r   r   r   r  )r)   r  r~  r  r   rI   submodule_prefixr#   r#   r,   r  
  s    #

zModule.named_modulesmodec                 C   s4   t |ts	td|| _|  D ]}|| q| S )a  Set the module in training mode.

        This has an effect only on certain modules. See the documentation of
        particular modules for details of their behaviors in training/evaluation
        mode, i.e., whether 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)r   r   r   rv   r   train)r)   r  rI   r#   r#   r,   r    s   
zModule.trainc                 C   s
   |  dS )aD  Set the module in evaluation mode.

        This has an effect only on certain modules. See the documentation of
        particular modules for details of their behaviors in training/evaluation
        mode, i.e. whether 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,   eval*  s   
zModule.evalr   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
        )rq  r   )r)   r   pr#   r#   r,   r   <  s   zModule.requires_grad_set_to_nonec                 C   sl   t | ddrtd |  D ]$}|jdur3|rd|_q|jjdur(|j  n|jd |j  qdS )a1  Reset gradients of all model parameters.

        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  rq  r   r   detach_r   zero_)r)   r  r  r#   r#   r,   	zero_gradS  s   	

zModule.zero_gradc                 C   r   )z'See :meth:`torch.Tensor.share_memory_`.c                 S   r   rZ   )share_memory_r   r#   r#   r,   r   q  r  z%Module.share_memory.<locals>.<lambda>r   r(   r#   r#   r,   share_memoryo  s   zModule.share_memoryc                 C   s   | j jS rZ   )r+   r-   r(   r#   r#   r,   r   s  s   zModule._get_namec                 C   s   dS )zReturn 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.
        r   r#   r(   r#   r#   r,   
extra_reprv  r  zModule.extra_reprc           	      C   s   g }|   }|r|d}g }| j D ]\}}t|}t|d}|d| d |  q|| }|  d }|rSt|dkrH|sH||d 7 }n|dd	| d 7 }|d7 }|S )	Nr4   r5  (z): r5   r   z
  ))
r  r<   r   r   reprrC   r  r   r=   r?   )	r)   extra_linesr  child_linesr   rI   mod_strlines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)r7   r   r#   r#   r,   r;     r=  z"Module.__dir__.<locals>.<listcomp>)	dirr+   listr   r  rw   r   rx   sorted)r)   module_attrsattrsrq  rg  rs  r  r#   r#   r,   __dir__  s   
zModule.__dir__c                 C   sB   |  t| }| j |_i |_|j |_|j |_d|_|S )NT)__new__rr   r   re  rw   rx   r   r  )r)   replicar#   r#   r,   _replicate_for_data_parallel  s   z#Module._replicate_for_data_parallelc                 O   s    t j| jg|R i || _dS )a  
        Compile this Module's forward using :func:`torch.compile`.

        This Module's `__call__` method is compiled and all arguments are passed as-is
        to :func:`torch.compile`.

        See :func:`torch.compile` for details on the arguments for this function.
        N)r   compilerS  r   r   r#   r#   r,   r    s    	zModule.compile)rR   N)T)FrZ   )...).)TF)r   TT)Nr   T)lr-   r.   r/   __doc__rt   r   __annotations__ru   intr[   r   r   r   r   r   r   r   r   rO   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   r  r	  r
  r  r   r  r	   r   r  _grad_tr   r%  r(  r)  r,  r.  rG  r@  rH  rI  rR  rT  rS  rT   rV   rY   rh  r   ru  rw  rx  rz  r  r
   r  r  r  r  r  r  r   r  r  r   rq  r  rs  r  r   r  rg  r  r  r  r   r  r  r   r  r'   r  r  r  r2   r#   r#   r*   r,   r     s  
  ,
>2B
Q$$
 _$)$$$
 
1

>Q

I&	

E "c(
Y 7

t

 
	

1	)BrJ   ro  r  r  rM   collectionsr   r   collections.abcr   r   typingr   r   r   r	   r
   r   typing_extensionsr   r   r   r   r   torch._prims_commonr   torch.nn.parameterr   r   torch.utils._python_dispatchr   torch.utils.hooksr   r   __all__r@  r  r   r"   rC   rD   r[   r  r  rE   rF   rG   r\   r]   r^   r   r_   r`   ra   rb   r|  r   r   r   r   r   r   r   r   rs   r   r#   r#   r#   r,   <module>   s   
 
&


#
/


'