o
    h                     @   s   d dl Z d dlmZmZ d dlmZmZmZ d dl	m
Z
mZ d dlmZmZmZmZmZ d dlmZmZ d dlZd dlmZ d dlmZ d	d
lmZ g dZededZdd Zeded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)abcOrderedDict)IterableIteratorMapping)chainislice)AnyOptionaloverloadTypeVarUnion)
deprecatedSelf)_copy_to_script_wrapper)	Parameter   )Module)	Container
Sequential
ModuleList
ModuleDictParameterListParameterDictT)boundc                    sP   |  d}t|dkr| S |d} fdd|D }d|}|d | }|S )N
r   r   c                    s   g | ]} d  | qS )  ).0line	numSpacesr   n/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/torch/nn/modules/container.py
<listcomp>$       z_addindent.<locals>.<listcomp>)splitlenpopjoin)s_r"   sfirstr   r!   r#   
_addindent   s   


r-   zq`nn.Container` is deprecated. All of it's functionality is now implemented in `nn.Module`. Subclass that instead.)categoryc                       s&   e Zd Zdeddf fddZ  ZS )r   kwargsreturnNc                    s,   t    | D ]
\}}| || q	d S N)super__init__items
add_module)selfr/   keyvalue	__class__r   r#   r3   0   s   
zContainer.__init__)__name__
__module____qualname__r	   r3   __classcell__r   r   r9   r#   r   *   s    r   c                       s  e Zd ZU dZeeef ed< ededdfddZ	ed3d
dZ	 fddZ	de
fddZedeeef ded e
f fddZdededdfddZdeeef ddfddZedefddZd4ddZdeeef defddZdefddZdedd fd d!Zdedd fd"d#Zdedefd$d%Ze fd&d'Zedee fd(d)Zd*d+ Zdedd fd,d-Zd.ededd fd/d0Z d4d1d2Z!  Z"S )5r   a  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())
                ]))
    _modulesargsr0   Nc                 G      d S r1   r   )r6   r@   r   r   r#   r3   f      zSequential.__init__argOrderedDict[str, Module]c                 C   rA   r1   r   )r6   rC   r   r   r#   r3   j   rB   c                    sp   t    t|dkr%t|d tr%|d  D ]
\}}| || qd S t|D ]\}}| t|| q)d S )Nr   r   )	r2   r3   r'   
isinstancer   r4   r5   	enumeratestr)r6   r@   r7   moduleidxr9   r   r#   r3   n   s   
c                 C   sR   t | }t|}| |  kr|k sn td| d||; }tt||dS )z$Get the idx-th item of the iterator.index  is out of rangeN)r'   operatorindex
IndexErrornextr   )r6   iteratorrI   sizer   r   r#   _get_item_by_idxw   s   
zSequential._get_item_by_idxrI   c                 C   s8   t |tr| tt| j | S | | j |S r1   )	rE   slicer:   r   listr?   r4   rR   valuesr6   rI   r   r   r#   __getitem__   s   
zSequential.__getitem__rH   c                 C   s   |  | j |}t| ||S r1   )rR   r?   keyssetattr)r6   rI   rH   r7   r   r   r#   __setitem__   s   zSequential.__setitem__c                 C   s   t |trt| j | D ]}t| | qn| | j |}t| | dd tt| jD }t	tt
|| j | _d S )Nc                 S      g | ]}t |qS r   rG   r   ir   r   r#   r$          z*Sequential.__delitem__.<locals>.<listcomp>)rE   rS   rT   r?   rX   delattrrR   ranger'   r   ziprU   )r6   rI   r7   str_indicesr   r   r#   __delitem__   s   

zSequential.__delitem__c                 C   
   t | jS r1   r'   r?   r6   r   r   r#   __len__      
zSequential.__len__c                 C   sT   t |trt }| D ]}|| q
|D ]}|| q|S tdtt| dNz<add operator supports only objects of Sequential class, but z
 is given.)rE   r   append
ValueErrorrG   type)r6   otherretlayerr   r   r#   __add__   s   

zSequential.__add__r7   c                 C      | | }| |= |S r1   r   r6   r7   vr   r   r#   r(         zSequential.popc                 C   sT   t |trt| }t|D ]\}}| t|| | q| S tdtt| drj   )rE   r   r'   rF   r5   rG   rl   rm   )r6   rn   offsetr^   rH   r   r   r#   __iadd__   s   

zSequential.__iadd__rn   c                 C   s   t |tstdt|  dt| |dkr#td| dt|  t }d}t|D ]}| D ]}|t|| |d7 }q0q,|S Nz#unsupported operand type(s) for *: z and r   z#Non-positive multiplication factor z for r   )	rE   int	TypeErrorrm   rl   r   ra   r5   rG   )r6   rn   combinedrv   _rH   r   r   r#   __mul__   s    

zSequential.__mul__c                 C   
   |  |S r1   )r}   r6   rn   r   r   r#   __rmul__      
zSequential.__rmul__c                 C   s   t |tstdt|  dt| |dkr#td| dt|  t| }t| }t|d D ]}t|D ]}| t|| | j	t|  q7||7 }q1| S rx   )
rE   ry   rz   rm   rl   r'   ra   r5   rG   r?   )r6   rn   len_originalrv   r|   r^   r   r   r#   __imul__   s   
 
zSequential.__imul__c                       t   }dd |D }|S )Nc                 S      g | ]}|  s|qS r   isdigitr   r7   r   r   r#   r$      r%   z&Sequential.__dir__.<locals>.<listcomp>r2   __dir__r6   rX   r9   r   r#   r         
zSequential.__dir__c                 C      t | j S r1   iterr?   rU   rg   r   r   r#   __iter__      zSequential.__iter__c                 C   s   | D ]}||}q|S r1   r   )r6   inputrH   r   r   r#   forward      
zSequential.forwardc                 C      |  tt| | | S )zjAppend a given module to the end.

        Args:
            module (nn.Module): module to append
        r5   rG   r'   r6   rH   r   r   r#   rk         zSequential.appendrM   c                 C   s   t |tstdt t| j}| |  kr|ks$n td| |dk r,||7 }t||dD ]}| jt|d  | jt|< q2|| jt|< | S )Nzmodule should be of type: zIndex out of range: r   r   )rE   r   AssertionErrorr'   r?   rN   ra   rG   )r6   rM   rH   nr^   r   r   r#   insert   s   

zSequential.insertc                 C   s   |D ]}|  | q| S r1   )rk   )r6   
sequentialrp   r   r   r#   extend	  s   zSequential.extend)rC   rD   r0   N)r0   r   )#r;   r<   r=   __doc__dictrG   r   __annotations__r   r3   r   rR   r   r   rS   ry   rW   rZ   rd   rh   rq   r(   r   rw   r}   r   r   r   r   r   r   rk   r   r   r>   r   r   r9   r#   r   6   s:   
 -		$
	r   c                       s  e Zd ZU dZeeef ed< d+dee	e  ddf fddZ
dd	 Zed
edd fddZed
edefddZed
eeef deed f fddZd
ededdfddZd
eeef ddfddZedefddZedee fddZde	e defddZde	e dd fddZdd Ze fdd Zd!ededdfd"d#Zdedd fd$d%Zd&eeef defd'd(Zde	e defd)d*Z  Z S ),r   a  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) -> None:
                super().__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modulesr0   c                    s"   t    |d ur| |7 } d S d S r1   )r2   r3   r6   r   r9   r   r#   r3   )  s   
zModuleList.__init__c                 C   V   t |}t|  |  krt| k sn td| d|dk r'|t| 7 }t|S z/Get the absolute index for the list of modules.rJ   rK   r   rL   rM   r'   rN   rG   rV   r   r   r#   _get_abs_string_index.     
 z ModuleList._get_abs_string_indexrI   c                 C   rA   r1   r   rV   r   r   r#   rW   7  rB   zModuleList.__getitem__c                 C   rA   r1   r   rV   r   r   r#   rW   ;  rB   c                 C   s2   t |tr| t| j | S | j| | S r1   )rE   rS   r:   rT   r?   rU   r   rV   r   r   r#   rW   ?  s   
rH   c                 C   s   |  |}t| t||S r1   )r   rY   rG   )r6   rI   rH   r   r   r#   rZ   F  s   
zModuleList.__setitem__c                 C   sx   t |trtt| j| D ]	}t| t| qnt| | | dd tt| jD }tt	t
|| j | _d S )Nc                 S   r[   r   r\   r]   r   r   r#   r$   Q  r_   z*ModuleList.__delitem__.<locals>.<listcomp>)rE   rS   ra   r'   r?   r`   rG   r   r   rT   rb   rU   )r6   rI   krc   r   r   r#   rd   J  s   
zModuleList.__delitem__c                 C   re   r1   rf   rg   r   r   r#   rh   T  ri   zModuleList.__len__c                 C   r   r1   r   rg   r   r   r#   r   X  r   zModuleList.__iter__c                 C   r~   r1   r   r   r   r   r#   rw   \  r   zModuleList.__iadd__rn   c                 C   s2   t  }tt| |D ]\}}|t|| q
|S r1   )r   rF   r   r5   rG   )r6   rn   r{   r^   rH   r   r   r#   rq   _  s   zModuleList.__add__c              	   C   s.  dd | D }t |dkr|  d S ddgg}|d g}t|dd dD ]!\}}||d kr;|d d  d7  < q&|||g || q&g }|  d }t||D ]0\\}}	}
d| d	|
 }||	kr{|	| d }d| d
|	 d	| d|
 }t|d}|| qU|dd| d 7 }|d7 }|S )zTReturn a custom repr for ModuleList that compresses repeated module representations.c                 S   r[   r   )repr)r   itemr   r   r#   r$   g  r_   z'ModuleList.__repr__.<locals>.<listcomp>r   z()r   Nr   (): -z x    z
  r   ))r'   	_get_namerF   rk   rb   r-   r)   )r6   list_of_reprsstart_end_indicesrepeated_blocksr^   rlinesmain_strstart_idend_idb
local_reprr   r   r   r#   __repr__e  s.   


zModuleList.__repr__c                    r   )Nc                 S   r   r   r   r   r   r   r#   r$     r%   z&ModuleList.__dir__.<locals>.<listcomp>r   r   r9   r   r#   r     r   zModuleList.__dir__rM   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   r   N)ra   r'   r?   rG   )r6   rM   rH   r^   r   r   r#   r     s   zModuleList.insertc                 C   r   )zvAppend a given module to the end of the list.

        Args:
            module (nn.Module): module to append
        r   r   r   r   r#   rk     r   zModuleList.appendr7   c                 C   rr   r1   r   rs   r   r   r#   r(     ru   zModuleList.popc                 C   sP   t |tjstdt|j t| }t|D ]\}}| t	|| | q| S )zAppend 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 )
rE   container_abcsr   rz   rm   r;   r'   rF   r5   rG   )r6   r   rv   r^   rH   r   r   r#   r     s   zModuleList.extendr1   )!r;   r<   r=   r   r   rG   r   r   r
   r   r3   r   r   rS   rW   ry   r   r   rZ   rd   rh   r   r   r   rw   rq   r   r   r   rk   r(   r   r>   r   r   r9   r#   r     s4   
  	$
 	r   c                       sF  e Zd ZU dZeeef ed< d"dee	eef  ddf fddZ
ededefd	d
ZdededdfddZdeddfddZedefddZedee fddZededefddZd#ddZdedefddZedee fddZedeeeef  fddZedee fddZde	eef ddfd d!Z  ZS )$r   a,  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) -> None:
                super().__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   r0   c                    s$   t    |d ur| | d S d S r1   )r2   r3   updater   r9   r   r#   r3     s   
zModuleDict.__init__r7   c                 C   s
   | j | S r1   r?   r6   r7   r   r   r#   rW     ri   zModuleDict.__getitem__rH   c                 C   s   |  || d S r1   )r5   )r6   r7   rH   r   r   r#   rZ     s   zModuleDict.__setitem__c                 C   s   | j |= d S r1   r   r   r   r   r#   rd     s   zModuleDict.__delitem__c                 C   re   r1   rf   rg   r   r   r#   rh     ri   zModuleDict.__len__c                 C   re   r1   )r   r?   rg   r   r   r#   r     ri   zModuleDict.__iter__c                 C   
   || j v S r1   r   r   r   r   r#   __contains__  ri   zModuleDict.__contains__c                 C   s   | j   dS )z%Remove all items from the ModuleDict.N)r?   clearrg   r   r   r#   r      r   zModuleDict.clearc                 C   rr   )zRemove key from the ModuleDict and return its module.

        Args:
            key (str): key to pop from the ModuleDict
        r   rs   r   r   r#   r(        zModuleDict.popc                 C   
   | j  S )z*Return an iterable of the ModuleDict keys.)r?   rX   rg   r   r   r#   rX        
zModuleDict.keysc                 C   r   )z5Return an iterable of the ModuleDict key/value pairs.)r?   r4   rg   r   r   r#   r4     r   zModuleDict.itemsc                 C   r   )z,Return an iterable of the ModuleDict values.)r?   rU   rg   r   r   r#   rU     r   zModuleDict.valuesc                 C   s   t |tjstdt|j t |tttjfr'|	 D ]\}}|| |< qd	S t
|D ]9\}}t |tjsDtdt| d t|j t|dks\tdt| d tt| d |d | |d < q+d	S )
a  Update the :class:`~torch.nn.ModuleDict` with key-value pairs from a mapping, 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)rE   r   r   rz   rm   r;   r   r   r   r4   rF   rG   r'   rl   )r6   r   r7   rH   jmr   r   r#   r     sF   

zModuleDict.updater1   r0   N)r;   r<   r=   r   r   rG   r   r   r
   r   r3   r   rW   rZ   rd   ry   rh   r   r   boolr   r   r(   r   rX   tupler4   rU   r   r>   r   r   r9   r#   r     s.   
 +$

"r   c                       s
  e Zd ZdZd$deee  ddf fddZdd Ze	d	e
defd
dZe	ded	edefddZdd Zd	e
deddfddZde
fddZdee fddZdee defddZ fddZdedd fddZdee defddZdefd d!Zd"d# Z  ZS )%r   a>  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.ParameterList.append` method and the :meth:`~torch.nn.ParameterList.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) -> None:
                super().__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
    NrU   r0   c                    s(   t    d| _|d ur| |7 } d S d S )Nr   )r2   r3   _size)r6   rU   r9   r   r#   r3   a  s
   
zParameterList.__init__c                 C   r   r   r   rV   r   r   r#   r   g  r   z#ParameterList._get_abs_string_indexrI   c                 C   rA   r1   r   rV   r   r   r#   rW   p  rB   zParameterList.__getitem__r6   c                 C   rA   r1   r   rV   r   r   r#   rW   t  rB   c                 C   sb   t |tr%|t| \}}}|  }t|||D ]	}|| |  q|S | |}t| t	|S r1   )
rE   rS   indicesr'   r:   ra   rk   r   getattrrG   )r6   rI   startstopstepoutr^   r   r   r#   rW   x  s   

paramc                 C   s8   |  |}t|tjrt|tst|}t| t||S r1   )r   rE   torchTensorr   rY   rG   )r6   rI   r   r   r   r#   rZ     s   
zParameterList.__setitem__c                 C   s   | j S r1   )r   rg   r   r   r#   rh     s   zParameterList.__len__c                    s   t  fddtt D S )Nc                 3       | ]} | V  qd S r1   r   r]   rg   r   r#   	<genexpr>      z)ParameterList.__iter__.<locals>.<genexpr>)r   ra   r'   rg   r   rg   r#   r     s   zParameterList.__iter__
parametersc                 C   r~   r1   r   r6   r   r   r   r#   rw     r   zParameterList.__iadd__c                    r   )Nc                 S   r   r   r   r   r   r   r#   r$     r%   z)ParameterList.__dir__.<locals>.<listcomp>r   r   r9   r   r#   r     s   
zParameterList.__dir__r8   c                 C   s"   t | }|  jd7  _|| |< | S )zmAppend a given value at the end of the list.

        Args:
            value (Any): value to append
        r   )r'   r   )r6   r8   new_idxr   r   r#   rk     s   zParameterList.appendc                 C   sB   t |tjrt |tjrtdt|j |D ]}| | q| S )zAppend 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 )	rE   r   r   r   r   rz   rm   r;   rk   )r6   rU   r8   r   r   r#   r     s   zParameterList.extendc                 C   s   g }t | D ]Y\}}t|tjrOddd | D }|jjdtj	 fv r/d|j d}nd}d
t|tr:d	nd
|j||}|dt| d |  q|dt| d t|j  qd|}|S )Nxc                 s       | ]}t |V  qd S r1   r\   r   rQ   r   r   r#   r     r   z+ParameterList.extra_repr.<locals>.<genexpr>cuda (r     {} containing: [{} of size {}{}]r   r     (r   ): Object of type: r   )rF   rE   r   r   r)   rQ   devicerm   _C_get_privateuse1_backend_nameformatr   dtyperk   rG   r;   r6   child_linesr   psize_str
device_strparastrtmpstrr   r   r#   
extra_repr  s&   
zParameterList.extra_reprc                 O      t d)Nz#ParameterList should not be called.RuntimeError)r6   r@   r/   r   r   r#   __call__     zParameterList.__call__r1   )r;   r<   r=   r   r
   r   r	   r3   r   r   ry   rW   r   rS   rZ   rh   r   r   r   rw   r   rk   r   rG   r   r   r>   r   r   r9   r#   r   E  s$     	r   c                       s  e Zd ZdZd<deddf fddZdedefdd	Zdedefd
dZdededdfddZ	deddfddZ
defddZdee fddZdee fddZd=ddZdedefddZd<dedee defddZd>ddZdedefd d!Zdeeef fd"d#Zd<dedee defd$d%Z	d<d&ee dee dd fd'd(Zdee fd)d*Zdeeeef  fd+d,Zdee fd-d.Zdee eef d f ddfd/d0Z!defd1d2Z"d3d4 Z#d?d6d7Z$d?d8d9Z%d5d de&fd:d;Z'  Z(S )@r   a  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) -> None:
                super().__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   r0   c                    s*   t    i | _|d ur| | d S d S r1   )r2   r3   _keysr   r   r9   r   r#   r3     s
   
zParameterDict.__init__r7   c                 C   s$   t |tstdt|j 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.)rE   rG   rz   rm   r;   r   r   r   r#   _key_to_attr   s   
zParameterDict._key_to_attrc                 C   s   |  |}t| |S r1   )r   r   r6   r7   attrr   r   r#   rW     s   

zParameterDict.__getitem__r8   c                 C   sB   d | j |< | |}t|tjrt|tst|}t| || d S r1   )r   r   rE   r   r   r   rY   )r6   r7   r8   r   r   r   r#   rZ     s
   

zParameterDict.__setitem__c                 C   s    | j |= | |}t| | d S r1   )r   r   r`   r   r   r   r#   rd     s   
zParameterDict.__delitem__c                 C   re   r1   )r'   r   rg   r   r   r#   rh      r   zParameterDict.__len__c                 C   re   r1   )r   r   rg   r   r   r#   r   #  r   zParameterDict.__iter__c                 C   s   t t| jS r1   )reversedrT   r   rg   r   r   r#   __reversed__&  s   zParameterDict.__reversed__c                    s   t t fdd jD S )z@Return a copy of this :class:`~torch.nn.ParameterDict` instance.c                 3       | ]	}| | fV  qd S r1   r   r   r   rg   r   r#   r   -      z%ParameterDict.copy.<locals>.<genexpr>)r   r   r   rg   r   rg   r#   copy)  s   zParameterDict.copyc                 C   r   r1   r   r   r   r   r#   r   /  r   zParameterDict.__contains__defaultc                 C   s   || vr|| |< | | S )a\  Set the default for a key in the Parameterdict.

        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 (str): key to set default for
            default (Any): the parameter set to the key
        r   r6   r7   r  r   r   r#   
setdefault2  s   zParameterDict.setdefaultc                 C   s   | j  D ]}| |= qdS )z(Remove all items from the ParameterDict.N)r   r  )r6   r   r   r   r#   r   A  s   zParameterDict.clearc                 C   rr   )zRemove key from the ParameterDict and return its parameter.

        Args:
            key (str): key to pop from the ParameterDict
        r   rs   r   r   r#   r(   F  r   zParameterDict.popc                 C   s.   | j  \}}d| j |< | | }| |= ||fS )zSRemove and return the last inserted `(key, parameter)` pair from the ParameterDict.N)r   popitem)r6   r   r|   valr   r   r#   r	  P  s
   
zParameterDict.popitemc                 C   s   || v r| | S |S )a  Return the parameter associated with key if present. Otherwise return default if provided, None if not.

        Args:
            key (str): key to get from the ParameterDict
            default (Parameter, optional): value to return if key not present
        r   r  r   r   r#   getY  s   zParameterDict.getrX   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 r1   r   r  r  r   r#   r   k  r   z)ParameterDict.fromkeys.<locals>.<genexpr>)r   )r6   rX   r  r   r  r#   fromkeysb  s   	zParameterDict.fromkeysc                 C   r   )z-Return an iterable of the ParameterDict keys.)r   rX   rg   r   r   r#   rX   m  ri   zParameterDict.keysc                        fdd j D S )z8Return an iterable of the ParameterDict key/value pairs.c                 3   r  r1   r   r  rg   r   r#   r   s  r  z&ParameterDict.items.<locals>.<genexpr>r  rg   r   rg   r#   r4   q     zParameterDict.itemsc                    r  )z/Return an iterable of the ParameterDict values.c                 3   r   r1   r   r  rg   r   r#   r   w  r   z'ParameterDict.values.<locals>.<genexpr>r  rg   r   rg   r#   rU   u  r  zParameterDict.valuesc                 C   s   t |tjstdt|j t |ttfr%| D ]\}}|| |< qd	S t |tj	r<t
| D ]\}}|| |< q1d	S t|D ]9\}}t |tjsYtdt| d t|j t|dksqtdt| d tt| d |d | |d < q@d	S )
a-  Update the :class:`~torch.nn.ParameterDict` with key-value pairs from ``parameters``, 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)rE   r   r   rz   rm   r;   r   r   r4   r   sortedrF   rG   r'   rl   )r6   r   r7   	parameterr   r   r   r   r#   r   y  sN   


zParameterDict.updatec                 C   s   g }|   D ][\}}t|tjrQddd | D }|jjdtj	 fv r/d|j d}nd}d
t|tr:d	nd
t|||}|dt| d |  q|dt| d t|j  qd|}|S )Nr   c                 s   r   r1   r\   r   r   r   r#   r     r   z+ParameterDict.extra_repr.<locals>.<genexpr>r   r   r   r   r   r   r   r   r   r   r   )r4   rE   r   r   r)   rQ   r   rm   r   r   r   r   typenamerk   rG   r;   r   r   r   r#   r     s&   
zParameterDict.extra_reprc                 C   r   )Nz#ParameterDict should not be called.r   )r6   r   r   r   r#   r     r   zParameterDict.__call__rn   c                 C   s   |   }|| |S r1   r  r   r6   rn   r  r   r   r#   __or__  r   zParameterDict.__or__c                 C   s   |  }||  |S r1   r  r  r   r   r#   __ror__  r   zParameterDict.__ror__c                 C   s   |  | | S r1   )r   r   r   r   r#   __ior__  s   
zParameterDict.__ior__r1   )r0   r   r   )rn   r   r0   r   ))r;   r<   r=   r   r	   r3   rG   r   rW   rZ   rd   ry   rh   r   r   r   r  r   r   r
   r  r   r(   r   r	  r  r   r  rX   r4   rU   r   r   r   r   r   r  r  r   r  r>   r   r   r9   r#   r     sD    $


	

"'

r   )&rL   collectionsr   r   r   collections.abcr   r   r   	itertoolsr   r   typingr	   r
   r   r   r   typing_extensionsr   r   r   torch._jit_internalr   torch.nn.parameterr   rH   r   __all__r   r-   FutureWarningr   r   r   r   r   r   r   r   r   r#   <module>   s6   	 Z )  