a
    Ž¥»aÆf  ã                   @   s   d dl Z d dlmZmZ d dlmZ d dlZd dlZddl	m
Z
 d dlmZ d dlmZmZmZmZmZmZmZmZmZmZmZ er�d dlmZ ed	e
d
�ZG dd„ de
ƒZG dd„ de
ƒZG dd„ de
ƒZG dd„ de
ƒZG dd„ de
ƒZ G dd„ de
ƒZ!dS )é    N)ÚOrderedDictÚabc)Úisliceé   )ÚModule)Ú_copy_to_script_wrapper)ÚAnyÚDictÚIterableÚIteratorÚMappingÚOptionalÚTYPE_CHECKINGÚoverloadÚTupleÚTypeVarÚUnion)Ú	ParameterÚT)Úboundc                       s$   e Zd Zeddœ‡ fdd„Z‡  ZS )Ú	ContainerN)ÚkwargsÚreturnc                    s:   t t| ƒ ¡  t d¡ | ¡ D ]\}}|  ||¡ q d S )Nzmnn.Container is deprecated. All of it's functionality is now implemented in nn.Module. Subclass that instead.)Úsuperr   Ú__init__ÚwarningsÚwarnÚitemsÚ
add_module)Úselfr   ÚkeyÚvalue©Ú	__class__© úT/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/torch/nn/modules/container.pyr      s    
zContainer.__init__)Ú__name__Ú
__module__Ú__qualname__r   r   Ú__classcell__r$   r$   r"   r%   r      s   r   c                       sì   e Zd ZU dZeeef ed< eeddœdd„ƒZ	edddœd	d„ƒZ	‡ fd
d„Z	e
dœdd„Zeed e
f dœdd„ƒZeeddœdd„Zeeef ddœdd„Zeedœdd„ƒZe‡ fdd„ƒZeee dœdd„ƒZdd„ Z‡  ZS )Ú
Sequentiala·  A sequential container.
    Modules will be added to it in the order they are passed in the
    constructor. Alternatively, an ``OrderedDict`` of modules can be
    passed in. The ``forward()`` method of ``Sequential`` accepts any
    input and forwards it to the first module it contains. It then
    "chains" outputs to inputs sequentially for each subsequent module,
    finally returning the output of the last module.

    The value a ``Sequential`` provides over manually calling a sequence
    of modules is that it allows treating the whole container as a
    single module, such that performing a transformation on the
    ``Sequential`` applies to each of the modules it stores (which are
    each a registered submodule of the ``Sequential``).

    What's the difference between a ``Sequential`` and a
    :class:`torch.nn.ModuleList`? A ``ModuleList`` is exactly what it
    sounds like--a list for storing ``Module`` s! On the other hand,
    the layers in a ``Sequential`` are connected in a cascading way.

    Example::

        # Using Sequential to create a small model. When `model` is run,
        # input will first be passed to `Conv2d(1,20,5)`. The output of
        # `Conv2d(1,20,5)` will be used as the input to the first
        # `ReLU`; the output of the first `ReLU` will become the input
        # for `Conv2d(20,64,5)`. Finally, the output of
        # `Conv2d(20,64,5)` will be used as input to the second `ReLU`
        model = nn.Sequential(
                  nn.Conv2d(1,20,5),
                  nn.ReLU(),
                  nn.Conv2d(20,64,5),
                  nn.ReLU()
                )

        # Using Sequential with OrderedDict. This is functionally the
        # same as the above code
        model = nn.Sequential(OrderedDict([
                  ('conv1', nn.Conv2d(1,20,5)),
                  ('relu1', nn.ReLU()),
                  ('conv2', nn.Conv2d(20,64,5)),
                  ('relu2', nn.ReLU())
                ]))
    Ú_modulesN)Úargsr   c                 G   s   d S ©Nr$   )r   r,   r$   r$   r%   r   L   s    zSequential.__init__zOrderedDict[str, Module])Úargr   c                 C   s   d S r-   r$   )r   r.   r$   r$   r%   r   P   s    c                    sr   t t| ƒ ¡  t|ƒdkrLt|d tƒrL|d  ¡ D ]\}}|  ||¡ q4n"t|ƒD ]\}}|  t	|ƒ|¡ qTd S )Nr   r   )
r   r*   r   ÚlenÚ
isinstancer   r   r   Ú	enumerateÚstr)r   r,   r    ÚmoduleÚidxr"   r$   r%   r   T   s    ©r   c                 C   sP   t | ƒ}t |¡}| |  kr(|k s8n td |¡ƒ‚||; }tt||dƒƒS )z#Get the idx-th item of the iteratorúindex {} is out of rangeN)r/   ÚoperatorÚindexÚ
IndexErrorÚformatÚnextr   )r   Úiteratorr4   Úsizer$   r$   r%   Ú_get_item_by_idx]   s    
zSequential._get_item_by_idxc                 C   s<   t |tƒr&|  tt| j ¡ ƒ| ƒ¡S |  | j ¡ |¡S d S r-   )	r0   Úslicer#   r   Úlistr+   r   r>   Úvalues©r   r4   r$   r$   r%   Ú__getitem__f   s    
zSequential.__getitem__©r4   r3   r   c                 C   s   |   | j ¡ |¡}t| ||ƒS r-   )r>   r+   ÚkeysÚsetattr)r   r4   r3   r    r$   r$   r%   Ú__setitem__m   s    zSequential.__setitem__©r4   r   c                 C   sN   t |tƒr.t| j ¡ ƒ| D ]}t| |ƒ qn|  | j ¡ |¡}t| |ƒ d S r-   )r0   r?   r@   r+   rE   Údelattrr>   )r   r4   r    r$   r$   r%   Ú__delitem__q   s
    
zSequential.__delitem__c                 C   s
   t | jƒS r-   ©r/   r+   ©r   r$   r$   r%   Ú__len__y   s    zSequential.__len__c                    s    t t| ƒ ¡ }dd„ |D ƒ}|S )Nc                 S   s   g | ]}|  ¡ s|‘qS r$   ©Úisdigit©Ú.0r    r$   r$   r%   Ú
<listcomp>€   ó    z&Sequential.__dir__.<locals>.<listcomp>)r   r*   Ú__dir__©r   rE   r"   r$   r%   rT   }   s    zSequential.__dir__c                 C   s   t | j ¡ ƒS r-   ©Úiterr+   rA   rL   r$   r$   r%   Ú__iter__ƒ   s    zSequential.__iter__c                 C   s   | D ]}||ƒ}q|S r-   r$   )r   Úinputr3   r$   r$   r%   Úforward‹   s    
zSequential.forward)r&   r'   r(   Ú__doc__r	   r2   r   Ú__annotations__r   r   r   r>   r   r   rC   ÚintrG   r?   rJ   rM   rT   r   rX   rZ   r)   r$   r$   r"   r%   r*      s&   
,		r*   c                       s  e Zd ZU dZeeef ed< d"ee	e  ddœ‡ fdd„Z
dd„ Zeeed	œd
d„ƒZeeddœdd„Zeeef dd	œdd„Zeedœdd„ƒZeee dœdd„ƒZe	e d dœdd„Ze‡ fdd„ƒZeeddœdd„Zed dœdd„Ze	e d dœd d!„Z‡  ZS )#Ú
ModuleLista  Holds submodules in a list.

    :class:`~torch.nn.ModuleList` can be indexed like a regular Python list, but
    modules it contains are properly registered, and will be visible by all
    :class:`~torch.nn.Module` methods.

    Args:
        modules (iterable, optional): an iterable of modules to add

    Example::

        class MyModule(nn.Module):
            def __init__(self):
                super(MyModule, self).__init__()
                self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])

            def forward(self, x):
                # ModuleList can act as an iterable, or be indexed using ints
                for i, l in enumerate(self.linears):
                    x = self.linears[i // 2](x) + l(x)
                return x
    r+   N©Úmodulesr   c                    s"   t t| ƒ ¡  |d ur| |7 } d S r-   )r   r^   r   ©r   r`   r"   r$   r%   r   «   s    zModuleList.__init__c                 C   sT   t  |¡}t| ƒ |  kr(t| ƒk s8n td |¡ƒ‚|dk rL|t| ƒ7 }t|ƒS ©z.Get the absolute index for the list of modulesr6   r   ©r7   r8   r/   r9   r:   r2   rB   r$   r$   r%   Ú_get_abs_string_index°   s    
 z ModuleList._get_abs_string_indexrH   c                 C   s6   t |tƒr"|  t| j ¡ ƒ| ¡S | j|  |¡ S d S r-   )r0   r?   r#   r@   r+   rA   rd   rB   r$   r$   r%   rC   ¹   s    
zModuleList.__getitem__rD   c                 C   s   |   |¡}t| t|ƒ|ƒS r-   )rd   rF   r2   )r   r4   r3   r$   r$   r%   rG   À   s    
zModuleList.__setitem__c                 C   sx   t |tƒr2tt| jƒƒ| D ]}t| t|ƒƒ qnt| |  |¡ƒ dd„ tt| jƒƒD ƒ}tt	t
|| j ¡ ƒƒƒ| _d S )Nc                 S   s   g | ]}t |ƒ‘qS r$   ©r2   )rQ   Úir$   r$   r%   rR   Ë   rS   z*ModuleList.__delitem__.<locals>.<listcomp>)r0   r?   Úranger/   r+   rI   r2   rd   r   r@   ÚziprA   )r   r4   ÚkZstr_indicesr$   r$   r%   rJ   Ä   s    
zModuleList.__delitem__r5   c                 C   s
   t | jƒS r-   rK   rL   r$   r$   r%   rM   Î   s    zModuleList.__len__c                 C   s   t | j ¡ ƒS r-   rV   rL   r$   r$   r%   rX   Ò   s    zModuleList.__iter__c                 C   s
   |   |¡S r-   ©Úextendra   r$   r$   r%   Ú__iadd__Ö   s    zModuleList.__iadd__c                    s    t t| ƒ ¡ }dd„ |D ƒ}|S )Nc                 S   s   g | ]}|  ¡ s|‘qS r$   rN   rP   r$   r$   r%   rR   Ü   rS   z&ModuleList.__dir__.<locals>.<listcomp>)r   r^   rT   rU   r"   r$   r%   rT   Ù   s    zModuleList.__dir__)r8   r3   r   c                 C   sF   t t| jƒ|dƒD ] }| jt|d ƒ | jt|ƒ< q|| jt|ƒ< dS )zªInsert a given module before a given index in the list.

        Args:
            index (int): index to insert.
            module (nn.Module): module to insert
        éÿÿÿÿr   N)rg   r/   r+   r2   )r   r8   r3   rf   r$   r$   r%   Úinsertß   s    zModuleList.insert)r3   r   c                 C   s   |   tt| ƒƒ|¡ | S )zwAppends a given module to the end of the list.

        Args:
            module (nn.Module): module to append
        )r   r2   r/   )r   r3   r$   r$   r%   Úappendê   s    zModuleList.appendc                 C   sP   t |tjƒstdt|ƒj ƒ‚t| ƒ}t|ƒD ]\}}|  t	|| ƒ|¡ q.| S )z”Appends modules from a Python iterable to the end of the list.

        Args:
            modules (iterable): iterable of modules to append
        z=ModuleList.extend should be called with an iterable, but got )
r0   Úcontainer_abcsr
   Ú	TypeErrorÚtyper&   r/   r1   r   r2   )r   r`   Úoffsetrf   r3   r$   r$   r%   rk   ó   s    ÿzModuleList.extend)N)r&   r'   r(   r[   r	   r2   r   r\   r   r
   r   rd   r   r]   rC   rG   r   r?   rJ   rM   r   rX   rl   rT   rn   ro   rk   r)   r$   r$   r"   r%   r^   ‘   s$   
	
	r^   c                       s:  e Zd ZU dZeeef ed< d"ee	eef  ddœ‡ fdd„Z
eeedœdd	„ƒZeedd
œdd„Zeddœdd„Zeedœdd„ƒZeee dœdd„ƒZeeedœdd„ƒZddœdd„Zeedœdd„Zeee dœdd„ƒZeeeeef  dœdd„ƒZeee dœdd„ƒZe	eef ddœd d!„Z‡  ZS )#Ú
ModuleDicta2  Holds submodules in a dictionary.

    :class:`~torch.nn.ModuleDict` can be indexed like a regular Python dictionary,
    but modules it contains are properly registered, and will be visible by all
    :class:`~torch.nn.Module` methods.

    :class:`~torch.nn.ModuleDict` is an **ordered** dictionary that respects

    * the order of insertion, and

    * in :meth:`~torch.nn.ModuleDict.update`, the order of the merged
      ``OrderedDict``, ``dict`` (started from Python 3.6) or another
      :class:`~torch.nn.ModuleDict` (the argument to
      :meth:`~torch.nn.ModuleDict.update`).

    Note that :meth:`~torch.nn.ModuleDict.update` with other unordered mapping
    types (e.g., Python's plain ``dict`` before Python version 3.6) does not
    preserve the order of the merged mapping.

    Args:
        modules (iterable, optional): a mapping (dictionary) of (string: module)
            or an iterable of key-value pairs of type (string, module)

    Example::

        class MyModule(nn.Module):
            def __init__(self):
                super(MyModule, self).__init__()
                self.choices = nn.ModuleDict({
                        'conv': nn.Conv2d(10, 10, 3),
                        'pool': nn.MaxPool2d(3)
                })
                self.activations = nn.ModuleDict([
                        ['lrelu', nn.LeakyReLU()],
                        ['prelu', nn.PReLU()]
                ])

            def forward(self, x, choice, act):
                x = self.choices[choice](x)
                x = self.activations[act](x)
                return x
    r+   Nr_   c                    s$   t t| ƒ ¡  |d ur |  |¡ d S r-   )r   rt   r   Úupdatera   r"   r$   r%   r   2  s    zModuleDict.__init__©r    r   c                 C   s
   | j | S r-   ©r+   ©r   r    r$   r$   r%   rC   7  s    zModuleDict.__getitem__)r    r3   r   c                 C   s   |   ||¡ d S r-   )r   )r   r    r3   r$   r$   r%   rG   ;  s    zModuleDict.__setitem__c                 C   s   | j |= d S r-   rw   rx   r$   r$   r%   rJ   >  s    zModuleDict.__delitem__r5   c                 C   s
   t | jƒS r-   rK   rL   r$   r$   r%   rM   A  s    zModuleDict.__len__c                 C   s
   t | jƒS r-   )rW   r+   rL   r$   r$   r%   rX   E  s    zModuleDict.__iter__c                 C   s
   || j v S r-   rw   rx   r$   r$   r%   Ú__contains__I  s    zModuleDict.__contains__c                 C   s   | j  ¡  dS )z.Remove all items from the ModuleDict.
        N)r+   ÚclearrL   r$   r$   r%   rz   M  s    zModuleDict.clearc                 C   s   | | }| |= |S )z†Remove key from the ModuleDict and return its module.

        Args:
            key (string): key to pop from the ModuleDict
        r$   ©r   r    Úvr$   r$   r%   ÚpopR  s    zModuleDict.popc                 C   s
   | j  ¡ S )z3Return an iterable of the ModuleDict keys.
        )r+   rE   rL   r$   r$   r%   rE   \  s    zModuleDict.keysc                 C   s
   | j  ¡ S )z>Return an iterable of the ModuleDict key/value pairs.
        )r+   r   rL   r$   r$   r%   r   b  s    zModuleDict.itemsc                 C   s
   | j  ¡ S )z5Return an iterable of the ModuleDict values.
        )r+   rA   rL   r$   r$   r%   rA   h  s    zModuleDict.valuesc                 C   sÌ   t |tjƒstdt|ƒj ƒ‚t |tttjfƒrL| 	¡ D ]\}}|| |< q8n|t
|ƒD ]r\}}t |tjƒs†tdt|ƒ d t|ƒj ƒ‚t|ƒdks¶tdt|ƒ d tt|ƒƒ d ƒ‚|d | |d < qTd	S )
a!  Update the :class:`~torch.nn.ModuleDict` with the key-value pairs from a
        mapping or an iterable, overwriting existing keys.

        .. note::
            If :attr:`modules` is an ``OrderedDict``, a :class:`~torch.nn.ModuleDict`, or
            an iterable of key-value pairs, the order of new elements in it is preserved.

        Args:
            modules (iterable): a mapping (dictionary) from string to :class:`~torch.nn.Module`,
                or an iterable of key-value pairs of type (string, :class:`~torch.nn.Module`)
        zPModuleDict.update should be called with an iterable of key/value pairs, but got z$ModuleDict update sequence element #ú should be Iterable; isé   ú has length ú; 2 is requiredr   r   N)r0   rp   r
   rq   rr   r&   r   rt   r   r   r1   r2   r/   Ú
ValueError)r   r`   r    r3   ÚjÚmr$   r$   r%   ru   n  s6    þÿÿþÿÿ
ÿþzModuleDict.update)N)r&   r'   r(   r[   r	   r2   r   r\   r   r   r   r   rC   rG   rJ   r]   rM   r   rX   Úboolry   rz   r}   r
   rE   r   r   rA   ru   r)   r$   r$   r"   r%   rt     s,   
+"
rt   c                       s8  e Zd ZU dZeedf ed< d,eed  ddœ‡ fdd„Z	‡ fdd	„Z
d
d„ Zeeddœdd„ƒZeeeedœdd„ƒZdd„ Zedddœdd„Zeeddœ‡ fdd„Zedœdd„Zed dœdd„Zed d dœdd„Z‡ fdd „Zdd d!œd"d#„Zed d dœd$d%„Zedœd&d'„Zd(d)„ Z‡ fd*d+„Z‡  ZS )-ÚParameterLista:  Holds parameters in a list.

    :class:`~torch.nn.ParameterList` can be indexed like a regular Python
    list, but parameters it contains are properly registered, and will be
    visible by all :class:`~torch.nn.Module` methods.

    Args:
        parameters (iterable, optional): an iterable of :class:`~torch.nn.Parameter` to add

    Example::

        class MyModule(nn.Module):
            def __init__(self):
                super(MyModule, self).__init__()
                self.params = nn.ParameterList([nn.Parameter(torch.randn(10, 10)) for i in range(10)])

            def forward(self, x):
                # ParameterList can act as an iterable, or be indexed using ints
                for i, p in enumerate(self.params):
                    x = self.params[i // 2].mm(x) + p.mm(x)
                return x
    r   Ú_parametersN©Ú
parametersr   c                    s(   t t| ƒ ¡  d| _|d ur$| |7 } d S ©NT)r   r†   r   Ú_initialized©r   r‰   r"   r$   r%   r   ®  s    zParameterList.__init__c                    s"   d|d< t t| ƒ |¡ d| _d S ©NFr‹   T)r   r†   Ú__setstate__r‹   ©r   Ústater"   r$   r%   rŽ   ´  s    zParameterList.__setstate__c                 C   sT   t  |¡}t| ƒ |  kr(t| ƒk s8n td |¡ƒ‚|dk rL|t| ƒ7 }t|ƒS rb   rc   rB   r$   r$   r%   rd   ¹  s    
 z#ParameterList._get_abs_string_indexrH   c                 C   s   d S r-   r$   rB   r$   r$   r%   rC   Â  s    zParameterList.__getitem__)r   r4   r   c                 C   s   d S r-   r$   rB   r$   r$   r%   rC   Æ  s    c                 C   s>   t |tƒr"|  t| j ¡ ƒ| ¡S |  |¡}| jt|ƒ S d S r-   )r0   r?   r#   r@   r‡   rA   rd   r2   rB   r$   r$   r%   rC   Ê  s    

)r4   Úparamr   c                 C   s   |   |¡}|  t|ƒ|¡S r-   )rd   Úregister_parameterr2   )r   r4   r‘   r$   r$   r%   rG   Ñ  s    
zParameterList.__setitem__©r    r!   r   c                    sD   t | ddƒr.t| |ƒs.t|tjjƒs.t d¡ tt	| ƒ 
||¡ d S )Nr‹   Fz5Setting attributes on ParameterList is not supported.)ÚgetattrÚhasattrr0   ÚtorchÚnnr   r   r   r   r†   Ú__setattr__©r   r    r!   r"   r$   r%   r˜   Õ  s    
zParameterList.__setattr__r5   c                 C   s
   t | jƒS r-   ©r/   r‡   rL   r$   r$   r%   rM   Û  s    zParameterList.__len__c                 C   s   t | j ¡ ƒS r-   )rW   r‡   rA   rL   r$   r$   r%   rX   Þ  s    zParameterList.__iter__c                 C   s
   |   |¡S r-   rj   rŒ   r$   r$   r%   rl   á  s    zParameterList.__iadd__c                    s    t t| ƒ ¡ }dd„ |D ƒ}|S )Nc                 S   s   g | ]}|  ¡ s|‘qS r$   rN   rP   r$   r$   r%   rR   æ  rS   z)ParameterList.__dir__.<locals>.<listcomp>)r   r†   rT   rU   r"   r$   r%   rT   ä  s    zParameterList.__dir__)Ú	parameterr   c                 C   s   |   tt| ƒƒ|¡ | S )zƒAppends a given parameter at the end of the list.

        Args:
            parameter (nn.Parameter): parameter to append
        )r’   r2   r/   )r   r›   r$   r$   r%   ro   é  s    zParameterList.appendc                 C   sP   t |tjƒstdt|ƒj ƒ‚t| ƒ}t|ƒD ]\}}|  t	|| ƒ|¡ q.| S )z�Appends parameters from a Python iterable to the end of the list.

        Args:
            parameters (iterable): iterable of parameters to append
        z@ParameterList.extend should be called with an iterable, but got )
r0   rp   r
   rq   rr   r&   r/   r1   r’   r2   )r   r‰   rs   rf   r‘   r$   r$   r%   rk   ò  s    ÿzParameterList.extendc                 C   s„   g }| j  ¡ D ]f\}}d dd„ | ¡ D ƒ¡}|js8dnd | ¡ ¡}d t |¡||¡}| 	dt
|ƒ d | ¡ qd	 |¡}|S )
NÚxc                 s   s   | ]}t |ƒV  qd S r-   re   ©rQ   r=   r$   r$   r%   Ú	<genexpr>  rS   z+ParameterList.extra_repr.<locals>.<genexpr>Ú ú	 (GPU {})ú'Parameter containing: [{} of size {}{}]ú  (ú): Ú
)r‡   r   Újoinr=   Úis_cudar:   Ú
get_devicer–   Útypenamero   r2   ©r   Zchild_linesri   ÚpZsize_strZ
device_strZparastrZtmpstrr$   r$   r%   Ú
extra_repr   s    ÿ
zParameterList.extra_reprc                 C   s   t dƒ‚d S )Nz#ParameterList should not be called.©ÚRuntimeError©r   rY   r$   r$   r%   Ú__call__  s    zParameterList.__call__c                    s   t  d¡ tt| ƒ ¡ S )Nz¦nn.ParameterList is being used with DataParallel but this is not supported. This list will appear empty for the models replicated on each GPU except the original one.)r   r   r   r†   Ú_replicate_for_data_parallelrL   r"   r$   r%   r°     s    
z*ParameterList._replicate_for_data_parallel)N)r&   r'   r(   r[   r	   r2   r\   r   r
   r   rŽ   rd   r   r]   rC   r   r?   rG   r   r˜   rM   r   rX   rl   rT   ro   rk   r«   r¯   r°   r)   r$   r$   r"   r%   r†   ”  s*   
		r†   c                       sb  e Zd ZU dZeedf ed< d.eeedf  ddœ‡ fdd„Z	‡ fdd	„Z
edd
œdd„Zedddœdd„Zedd
œdd„Zeeddœ‡ fdd„Zedœdd„Zee dœdd„Zeed
œdd„Zddœdd„Zedd
œdd„Zee dœd d!„Zeeedf  dœd"d#„Zed dœd$d%„Zeedf ddœd&d'„Zedœd(d)„Zd*d+„ Z‡ fd,d-„Z ‡  Z!S )/ÚParameterDicta^  Holds parameters in a dictionary.

    ParameterDict can be indexed like a regular Python dictionary, but parameters it
    contains are properly registered, and will be visible by all Module methods.

    :class:`~torch.nn.ParameterDict` is an **ordered** dictionary that respects

    * the order of insertion, and

    * in :meth:`~torch.nn.ParameterDict.update`, the order of the merged ``OrderedDict``
      or another :class:`~torch.nn.ParameterDict` (the argument to
      :meth:`~torch.nn.ParameterDict.update`).

    Note that :meth:`~torch.nn.ParameterDict.update` with other unordered mapping
    types (e.g., Python's plain ``dict``) does not preserve the order of the
    merged mapping.

    Args:
        parameters (iterable, optional): a mapping (dictionary) of
            (string : :class:`~torch.nn.Parameter`) or an iterable of key-value pairs
            of type (string, :class:`~torch.nn.Parameter`)

    Example::

        class MyModule(nn.Module):
            def __init__(self):
                super(MyModule, self).__init__()
                self.params = nn.ParameterDict({
                        'left': nn.Parameter(torch.randn(5, 10)),
                        'right': nn.Parameter(torch.randn(5, 10))
                })

            def forward(self, x, choice):
                x = self.params[choice].mm(x)
                return x
    r   r‡   Nrˆ   c                    s*   t t| ƒ ¡  d| _|d ur&|  |¡ d S rŠ   )r   r±   r   r‹   ru   rŒ   r"   r$   r%   r   >  s    zParameterDict.__init__c                    s"   d|d< t t| ƒ |¡ d| _d S r�   )r   r±   rŽ   r‹   r�   r"   r$   r%   rŽ   D  s    zParameterDict.__setstate__rv   c                 C   s
   | j | S r-   ©r‡   rx   r$   r$   r%   rC   I  s    zParameterDict.__getitem__)r    r›   r   c                 C   s   |   ||¡ d S r-   )r’   )r   r    r›   r$   r$   r%   rG   L  s    zParameterDict.__setitem__c                 C   s   | j |= d S r-   r²   rx   r$   r$   r%   rJ   O  s    zParameterDict.__delitem__r“   c                    sD   t | ddƒr.t| |ƒs.t|tjjƒs.t d¡ tt	| ƒ 
||¡ d S )Nr‹   Fz5Setting attributes on ParameterDict is not supported.)r”   r•   r0   r–   r—   r   r   r   r   r±   r˜   r™   r"   r$   r%   r˜   R  s    
zParameterDict.__setattr__r5   c                 C   s
   t | jƒS r-   rš   rL   r$   r$   r%   rM   X  s    zParameterDict.__len__c                 C   s   t | j ¡ ƒS r-   )rW   r‡   rE   rL   r$   r$   r%   rX   [  s    zParameterDict.__iter__c                 C   s
   || j v S r-   r²   rx   r$   r$   r%   ry   ^  s    zParameterDict.__contains__c                 C   s   | j  ¡  dS )z1Remove all items from the ParameterDict.
        N)r‡   rz   rL   r$   r$   r%   rz   a  s    zParameterDict.clearc                 C   s   | | }| |= |S )z�Remove key from the ParameterDict and return its parameter.

        Args:
            key (string): key to pop from the ParameterDict
        r$   r{   r$   r$   r%   r}   f  s    zParameterDict.popc                 C   s
   | j  ¡ S )z6Return an iterable of the ParameterDict keys.
        )r‡   rE   rL   r$   r$   r%   rE   p  s    zParameterDict.keysc                 C   s
   | j  ¡ S )zAReturn an iterable of the ParameterDict key/value pairs.
        )r‡   r   rL   r$   r$   r%   r   u  s    zParameterDict.itemsc                 C   s
   | j  ¡ S )z8Return an iterable of the ParameterDict values.
        )r‡   rA   rL   r$   r$   r%   rA   z  s    zParameterDict.valuesc                 C   sô   t |tjƒstdt|ƒj ƒ‚t |ttfƒrH| ¡ D ]\}}|| |< q4n¨t |tj	ƒrtt
| ¡ ƒD ]\}}|| |< q`n|t|ƒD ]r\}}t |tjƒs®tdt|ƒ d t|ƒj ƒ‚t|ƒdksÞtdt|ƒ d tt|ƒƒ d ƒ‚|d | |d < q|d	S )
aC  Update the :class:`~torch.nn.ParameterDict` with the key-value pairs from a
        mapping or an iterable, overwriting existing keys.

        .. note::
            If :attr:`parameters` is an ``OrderedDict``, a :class:`~torch.nn.ParameterDict`, or
            an iterable of key-value pairs, the order of new elements in it is preserved.

        Args:
            parameters (iterable): a mapping (dictionary) from string to
                :class:`~torch.nn.Parameter`, or an iterable of
                key-value pairs of type (string, :class:`~torch.nn.Parameter`)
        zTParametersDict.update should be called with an iterable of key/value pairs, but got z'ParameterDict update sequence element #r~   r   r€   r�   r   r   N)r0   rp   r
   rq   rr   r&   r   r±   r   r   Úsortedr1   r2   r/   r‚   )r   r‰   r    r›   rƒ   rª   r$   r$   r%   ru     s<    þÿÿþÿÿ
ÿþzParameterDict.updatec                 C   s€   g }| j  ¡ D ]b\}}d dd„ | ¡ D ƒ¡}|js8dnd | ¡ ¡}d t |¡||¡}| 	d| d | ¡ qd	 |¡}|S )
Nrœ   c                 s   s   | ]}t |ƒV  qd S r-   re   r�   r$   r$   r%   rž   §  rS   z+ParameterDict.extra_repr.<locals>.<genexpr>rŸ   r    r¡   r¢   r£   r¤   )
r‡   r   r¥   r=   r¦   r:   r§   r–   r¨   ro   r©   r$   r$   r%   r«   ¤  s    ÿ
zParameterDict.extra_reprc                 C   s   t dƒ‚d S )Nz#ParameterDict should not be called.r¬   r®   r$   r$   r%   r¯   ¯  s    zParameterDict.__call__c                    s   t  d¡ tt| ƒ ¡ S )Nz¦nn.ParameterDict is being used with DataParallel but this is not supported. This dict will appear empty for the models replicated on each GPU except the original one.)r   r   r   r±   r°   rL   r"   r$   r%   r°   ²  s    
z*ParameterDict._replicate_for_data_parallel)N)"r&   r'   r(   r[   r	   r2   r\   r   r   r   rŽ   rC   rG   rJ   r   r˜   r]   rM   r   rX   r…   ry   rz   r}   r
   rE   r   r   rA   ru   r«   r¯   r°   r)   r$   r$   r"   r%   r±     s(   
%"
%r±   )"r   Úcollectionsr   r   rp   Ú	itertoolsr   r7   r–   r3   r   Ztorch._jit_internalr   Útypingr   r	   r
   r   r   r   r   r   r   r   r   Ztorch.nnr   r   r   r*   r^   rt   r†   r±   r$   r$   r$   r%   Ú<module>   s$   4ts  