U
    ds                     @   s   d dl Z d dlmZmZ d dlmZ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 d d	lmZmZmZmZmZmZmZmZmZ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)chainislice   )Module   )	Parameter)_copy_to_script_wrapper)
AnyDictIterableIteratorMappingOptionaloverloadTupleTypeVarUnion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__ >/tmp/pip-unpacked-wheel-ua33x9lu/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ed d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   J   s    zSequential.__init__zOrderedDict[str, Module])argr   c                 C   s   d S r.   r%   )r    r/   r%   r%   r&   r   N   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   R   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)r0   operatorindex
IndexErrorformatnextr   )r    iteratorr5   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.   )	r1   slicer$   r   listr,   r   r?   valuesr    r5   r%   r%   r&   __getitem__d   s    
zSequential.__getitem__r5   r4   r   c                 C   s   |  | j |}t| ||S r.   )r?   r,   keyssetattr)r    r5   r4   r!   r%   r%   r&   __setitem__k   s    zSequential.__setitem__r5   r   c                 C   sN   t |tr.t| j | D ]}t| | qn| | j |}t| | d S r.   )r1   r@   rA   r,   rF   delattrr?   )r    r5   r!   r%   r%   r&   __delitem__o   s
    
zSequential.__delitem__c                 C   s
   t | jS r.   r0   r,   r    r%   r%   r&   __len__w   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>~   s      z&Sequential.__dir__.<locals>.<listcomp>)r   r+   __dir__r    rF   r#   r%   r&   rT   {   s    zSequential.__dir__c                 C   s   t | j S r.   iterr,   rB   rM   r%   r%   r&   __iter__   s    zSequential.__iter__c                 C   s   | D ]}||}q|S r.   r%   )r    inputr4   r%   r%   r&   forward   s    
zSequential.forwardr4   r   c                 C   s   |  tt| | | S )zkAppends a given module to the end.

        Args:
            module (nn.Module): module to append
        r   r3   r0   r    r4   r%   r%   r&   append   s    zSequential.append)r'   r(   r)   __doc__r   r3   r   __annotations__r   r   r   r?   r
   r   rD   intrH   r@   rK   rN   rT   r   rX   rZ   r^   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ed 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ee dddZe	e d 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 k	r| |7 } d S r.   )r   rb   r   r    rd   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 modulesr7   r   r8   r9   r0   r:   r;   r3   rC   r%   r%   r&   _get_abs_string_index   s    
 z ModuleList._get_abs_string_indexrI   c                 C   s6   t |tr"| t| j | S | j| | S d S r.   )r1   r@   r$   rA   r,   rB   rh   rC   r%   r%   r&   rD      s    
zModuleList.__getitem__rE   c                 C   s   |  |}t| t||S r.   )rh   rG   r3   )r    r5   r4   r%   r%   r&   rH      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%   r3   rR   ir%   r%   r&   rS      s     z*ModuleList.__delitem__.<locals>.<listcomp>)r1   r@   ranger0   r,   rJ   r3   rh   r   rA   ziprB   )r    r5   kZstr_indicesr%   r%   r&   rK      s    
zModuleList.__delitem__r6   c                 C   s
   t | jS r.   rL   rM   r%   r%   r&   rN      s    zModuleList.__len__c                 C   s   t | j S r.   rV   rM   r%   r%   r&   rX      s    zModuleList.__iter__c                 C   s
   |  |S r.   extendre   r%   r%   r&   __iadd__   s    zModuleList.__iadd__otherr   c                 C   s2   t  }tt| |D ]\}}|t|| q|S r.   )rb   r2   r   r   r3   )r    rs   Zcombinedrk   r4   r%   r%   r&   __add__   s    zModuleList.__add__c                    s    t t|  }dd |D }|S )Nc                 S   s   g | ]}|  s|qS r%   rO   rQ   r%   r%   r&   rS      s      z&ModuleList.__dir__.<locals>.<listcomp>)r   rb   rT   rU   r#   r%   r&   rT      s    zModuleList.__dir__)r9   r4   r   c                 C   sF   t t| j|dD ] }| jt|d  | jt|< q|| jt|< dS )zInsert a given module before a given index in the list.

        Args:
            index (int): index to insert.
            module (nn.Module): module to insert
        r   N)rl   r0   r,   r3   )r    r9   r4   rk   r%   r%   r&   insert   s    zModuleList.insertr[   c                 C   s   |  tt| | | S )zwAppends a given module to the end of the list.

        Args:
            module (nn.Module): module to append
        r\   r]   r%   r%   r&   r^      s    zModuleList.appendc                 C   sP   t |tjstdt|j t| }t|D ]\}}| t	|| | q.| S )zAppends 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 )
r1   container_abcsr   	TypeErrortyper'   r0   r2   r   r3   )r    rd   offsetrk   r4   r%   r%   r&   rp      s    zModuleList.extend)N)r'   r(   r)   r_   r   r3   r   r`   r   r   r   rh   r
   ra   r   rD   rH   r@   rK   rN   r   rX   rq   rt   rT   rv   r^   rp   r*   r%   r%   r#   r&   rb      s&   
	
	rb   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,   Nrc   c                    s$   t t|   |d k	r | | d S r.   )r   r{   r   updatere   r#   r%   r&   r   ?  s    zModuleDict.__init__r!   r   c                 C   s
   | j | S r.   r,   r    r!   r%   r%   r&   rD   D  s    zModuleDict.__getitem__)r!   r4   r   c                 C   s   |  || d S r.   )r   )r    r!   r4   r%   r%   r&   rH   H  s    zModuleDict.__setitem__c                 C   s   | j |= d S r.   r~   r   r%   r%   r&   rK   K  s    zModuleDict.__delitem__r6   c                 C   s
   t | jS r.   rL   rM   r%   r%   r&   rN   N  s    zModuleDict.__len__c                 C   s
   t | jS r.   )rW   r,   rM   r%   r%   r&   rX   R  s    zModuleDict.__iter__c                 C   s
   || j kS r.   r~   r   r%   r%   r&   __contains__V  s    zModuleDict.__contains__c                 C   s   | j   dS )z.Remove all items from the ModuleDict.
        N)r,   clearrM   r%   r%   r&   r   Z  s    zModuleDict.clearc                 C   s   | | }| |= |S )zRemove key from the ModuleDict and return its module.

        Args:
            key (string): key to pop from the ModuleDict
        r%   r    r!   vr%   r%   r&   pop_  s    zModuleDict.popc                 C   s
   | j  S )z3Return an iterable of the ModuleDict keys.
        )r,   rF   rM   r%   r%   r&   rF   i  s    zModuleDict.keysc                 C   s
   | j  S )z>Return an iterable of the ModuleDict key/value pairs.
        )r,   r   rM   r%   r%   r&   r   o  s    zModuleDict.itemsc                 C   s
   | j  S )z5Return an iterable of the ModuleDict values.
        )r,   rB   rM   r%   r%   r&   rB   u  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stdt| d t|j t|dkst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; isr    has length ; 2 is requiredr   r   N)r1   rw   r   rx   ry   r'   r   r{   r   r   r2   r3   r0   
ValueError)r    rd   r!   r4   jmr%   r%   r&   r|   {  s6    
zModuleDict.update)N)r'   r(   r)   r_   r   r3   r   r`   r   r   r   r
   rD   rH   rK   ra   rN   r   rX   boolr   r   r   r   rF   r   r   rB   r|   r*   r%   r%   r#   r&   r{     s,   
+"
r{   c                       s   e Zd ZdZd$eee  dd fddZdd Ze	e
edd	d
Ze	eeeddd
Zdd
 Ze
eddddZe
dddZee dddZee d dddZ fddZed dddZee d dddZedd d!Zd"d# Z  ZS )%ParameterListaD  Holds parameters in a list.

    :class:`~torch.nn.ParameterList` can be used like a regular Python
    list, but Tensors that are :class:`~torch.nn.Parameter` are properly registered,
    and will be visible by all :class:`~torch.nn.Module` methods.

    Note that the constructor, assigning an element of the list, the
    :meth:`~torch.nn.ParameterDict.append` method and the :meth:`~torch.nn.ParameterDict.extend`
    method will convert any :class:`~torch.Tensor` into :class:`~torch.nn.Parameter`.

    Args:
        parameters (iterable, optional): an iterable of elements to add to the list.

    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
    N)rB   r   c                    s(   t t|   d| _|d k	r$| |7 } d S )Nr   )r   r   r   _size)r    rB   r#   r%   r&   r     s    zParameterList.__init__c                 C   sT   t |}t|  |  kr(t| k s8n td||dk rL|t| 7 }t|S rf   rg   rC   r%   r%   r&   rh     s    
 z#ParameterList._get_abs_string_indexrI   c                 C   s   d S r.   r%   rC   r%   r%   r&   rD     s    zParameterList.__getitem__)r    r5   r   c                 C   s   d S r.   r%   rC   r%   r%   r&   rD     s    c                 C   sf   t |trJ|t| \}}}|  }t|||D ]}|| |  q2|S | |}t| t	|S d S r.   )
r1   r@   indicesr0   r$   rl   r^   rh   getattrr3   )r    r5   startstopstepoutrk   r%   r%   r&   rD     s    

)r5   paramr   c                 C   s8   |  |}t|tjr(t|ts(t|}t| t||S r.   )rh   r1   torchTensorr	   rG   r3   )r    r5   r   r%   r%   r&   rH     s    
zParameterList.__setitem__r6   c                 C   s   | j S r.   )r   rM   r%   r%   r&   rN     s    zParameterList.__len__c                    s   t  fddtt D S )Nc                 3   s   | ]} | V  qd S r.   r%   rj   rM   r%   r&   	<genexpr>  s     z)ParameterList.__iter__.<locals>.<genexpr>)rW   rl   r0   rM   r%   rM   r&   rX     s    zParameterList.__iter__
parametersr   c                 C   s
   |  |S r.   ro   r    r   r%   r%   r&   rq     s    zParameterList.__iadd__c                    s    t t|  }dd |D }|S )Nc                 S   s   g | ]}|  s|qS r%   rO   rQ   r%   r%   r&   rS     s      z)ParameterList.__dir__.<locals>.<listcomp>)r   r   rT   rU   r#   r%   r&   rT     s    zParameterList.__dir__)r"   r   c                 C   s"   t | }|  jd7  _|| |< | S )znAppends a given value at the end of the list.

        Args:
            value (Any): value to append
        r   )r0   r   )r    r"   Znew_idxr%   r%   r&   r^     s    zParameterList.appendc                 C   sB   t |tjrt |tjr*tdt|j |D ]}| | q.| S )zAppends values from a Python iterable to the end of the list.

        Args:
            values (iterable): iterable of values to append
        z@ParameterList.extend should be called with an iterable, but got )	r1   rw   r   r   r   rx   ry   r'   r^   )r    rB   r"   r%   r%   r&   rp     s    zParameterList.extendc                 C   s   g }t | D ]\}}t|tjrddd | D }|jsBdnd| }dt|t	rbdndt
|||}|d	t| d
 |  q|d	t| d t|j  qd|}|S )Nxc                 s   s   | ]}t |V  qd S r.   ri   rR   r>   r%   r%   r&   r     s     z+ParameterList.extra_repr.<locals>.<genexpr> 	 (GPU {}) {} containing: [{} of size {}{}]r	   r     (): ): Object of type: 
)r2   r1   r   r   joinr>   is_cudar;   
get_devicer	   typenamer^   r3   ry   r'   r    Zchild_linesrn   pZsize_strZ
device_strZparastrZtmpstrr%   r%   r&   
extra_repr  s      "
zParameterList.extra_reprc                 O   s   t dd S )Nz#ParameterList should not be called.RuntimeError)r    r-   r   r%   r%   r&   __call__!  s    zParameterList.__call__)N)r'   r(   r)   r_   r   r   r   r   rh   r   ra   rD   r   r@   rH   rN   r   rX   rq   rT   r^   rp   r3   r   r   r*   r%   r%   r#   r&   r     s"   	r   c                       s  e Zd ZdZd<edd fddZeedddZeedd	d
ZeeddddZ	edd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edddZd=eee edddZddddZeedd d!Zeeef dd"d#Zd>eee edd$d%Zd?ee ee d d&d'd(Zee dd)d*Zeeeef  dd+d,Zee dd-d.Zee eef d f ddd/d0Z!edd1d2Z"d3d4 Z#d d d5d6d7Z$d d d5d8d9Z%d d d5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.
    Other objects are treated as would be done by a regular Python dictionary

    :class:`~torch.nn.ParameterDict` is an **ordered** dictionary.
    :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. On the other hand, ``OrderedDict`` or another :class:`~torch.nn.ParameterDict`
    will preserve their ordering.

    Note that the constructor, assigning an element of the dictionary and the
    :meth:`~torch.nn.ParameterDict.update` method will convert any :class:`~torch.Tensor` into
    :class:`~torch.nn.Parameter`.

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

    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
    Nr   c                    s*   t t|   i | _|d k	r&| | d S r.   )r   r   r   _keysr|   r   r#   r%   r&   r   J  s    zParameterDict.__init__r}   c                 C   s*   t |ts"tdt|j dn|S d S )NzUIndex given to ParameterDict cannot be used as a key as it is not a string (type is 'z8'). Open an issue on github if you need non-string keys.)r1   r3   rx   ry   r'   r   r%   r%   r&   _key_to_attrP  s    
zParameterDict._key_to_attrc                 C   s   |  |}t| |S r.   )r   r   r    r!   attrr%   r%   r&   rD   Y  s    
zParameterDict.__getitem__)r!   r"   r   c                 C   sB   d | j |< | |}t|tjr2t|ts2t|}t| || d S r.   )r   r   r1   r   r   r	   rG   )r    r!   r"   r   r%   r%   r&   rH   ]  s
    

zParameterDict.__setitem__c                 C   s    | j |= | |}t| | d S r.   )r   r   rJ   r   r%   r%   r&   rK   i  s    
zParameterDict.__delitem__r6   c                 C   s
   t | jS r.   )r0   r   rM   r%   r%   r&   rN   n  s    zParameterDict.__len__c                 C   s
   t | jS r.   )rW   r   rM   r%   r%   r&   rX   q  s    zParameterDict.__iter__c                 C   s   t t| jS r.   )reversedrA   r   rM   r%   r%   r&   __reversed__t  s    zParameterDict.__reversed__c                    s   t t fdd jD S )zJReturns a copy of this :class:`~torch.nn.ParameterDict` instance.
        c                 3   s   | ]}| | fV  qd S r.   r%   rR   rn   rM   r%   r&   r   |  s     z%ParameterDict.copy.<locals>.<genexpr>)r   r   r   rM   r%   rM   r&   copyw  s    zParameterDict.copyc                 C   s
   || j kS r.   r   r   r%   r%   r&   r   ~  s    zParameterDict.__contains__)r!   defaultr   c                 C   s   || kr|| |< | | S )a&  If key is in the ParameterDict, return its value.
        If not, insert `key` with a parameter `default` and return `default`.
        `default` defaults to `None`.

        Args:
            key (string): key to set default for
            default (Any): the parameter set to the key
        r%   r    r!   r   r%   r%   r&   
setdefault  s    
zParameterDict.setdefaultc                 C   s   | j  D ]
}| |= q
dS )z1Remove all items from the ParameterDict.
        N)r   r   )r    rn   r%   r%   r&   r     s    zParameterDict.clearc                 C   s   | | }| |= |S )zRemove key from the ParameterDict and return its parameter.

        Args:
            key (string): key to pop from the ParameterDict
        r%   r   r%   r%   r&   r     s    zParameterDict.popc                 C   s.   | j  \}}d| j |< | | }| |= ||fS )zcRemove and return the last inserted `(key, parameter)` pair
        from the ParameterDict
        N)r   popitem)r    rn   _valr%   r%   r&   r     s
    
zParameterDict.popitemc                 C   s   || kr| | S |S )a  Return the parameter associated with key if present.
        Otherwise return default if provided, None if not.

        Args:
            key (string): key to get from the ParameterDict
            default (Parameter, optional): value to return if key not present
        r%   r   r%   r%   r&   get  s    zParameterDict.get)rF   r   r   c                    s   t  fdd|D S )zReturn a new ParameterDict with the keys provided

        Args:
            keys (iterable, string): keys to make the new ParameterDict from
            default (Parameter, optional): value to set for all keys
        c                 3   s   | ]}| fV  qd S r.   r%   r   r   r%   r&   r     s     z)ParameterDict.fromkeys.<locals>.<genexpr>)r   )r    rF   r   r%   r   r&   fromkeys  s    zParameterDict.fromkeysc                 C   s
   | j  S )z6Return an iterable of the ParameterDict keys.
        )r   rF   rM   r%   r%   r&   rF     s    zParameterDict.keysc                    s    fdd j D S )zAReturn an iterable of the ParameterDict key/value pairs.
        c                 3   s   | ]}| | fV  qd S r.   r%   r   rM   r%   r&   r     s     z&ParameterDict.items.<locals>.<genexpr>r   rM   r%   rM   r&   r     s    zParameterDict.itemsc                    s    fdd j D S )z8Return an iterable of the ParameterDict values.
        c                 3   s   | ]} | V  qd S r.   r%   r   rM   r%   r&   r     s     z'ParameterDict.values.<locals>.<genexpr>r   rM   r%   rM   r&   rB     s    zParameterDict.valuesc                 C   s   t |tjstdt|j t |ttfrH| D ]\}}|| |< q4nt |tj	rtt
| D ]\}}|| |< q`n|t|D ]r\}}t |tjstdt| d t|j t|dkst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)r1   rw   r   rx   ry   r'   r   r   r   r   sortedr2   r3   r0   r   )r    r   r!   	parameterr   r   r%   r%   r&   r|     s<    
zParameterDict.updatec                 C   s   g }|   D ]\}}t|tjrddd | D }|jsBdnd| }dt|t	rbdndt
|||}|d	t| d
 |  q|d	t| d t|j  qd|}|S )Nr   c                 s   s   | ]}t |V  qd S r.   ri   r   r%   r%   r&   r     s     z+ParameterDict.extra_repr.<locals>.<genexpr>r   r   r   r	   r   r   r   r   r   )r   r1   r   r   r   r>   r   r;   r   r	   r   r^   r3   ry   r'   r   r%   r%   r&   r     s      "
zParameterDict.extra_reprc                 C   s   t dd S )Nz#ParameterDict should not be called.r   )r    rY   r%   r%   r&   r      s    zParameterDict.__call__rr   c                 C   s   |   }|| |S r.   r   r|   r    rs   r   r%   r%   r&   __or__  s    
zParameterDict.__or__c                 C   s   |  }||  |S r.   r   r   r%   r%   r&   __ror__  s    
zParameterDict.__ror__c                 C   s   |  | | S r.   )r|   )r    rs   r%   r%   r&   __ior__  s    
zParameterDict.__ior__)N)N)N)N)(r'   r(   r)   r_   r   r   r3   r   rD   rH   rK   ra   rN   r   rX   r   r   r   r   r   r   r   r   r   r   r   r   r   rF   r   rB   r   r   r|   r   r   r   r   r   r*   r%   r%   r#   r&   r   %  s4   $	

	 %r   )"r   collectionsr   r   rw   	itertoolsr   r   r8   r   r4   r   r   r	   Ztorch._jit_internalr
   typingr   r   r   r   r   r   r   r   r   r   r   r   r+   rb   r{   r   r   r%   r%   r%   r&   <module>   s"   0}y  