U
    ¯Ê¹j)  ã                
   @   s¢  d dl 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 d dlZd dlmZ d dlmZ ddd	d
ddddddg
Zd(ejedœdd„Zd)e	ejeeejdœdd„Zd*ejeeedœdd	„Zd+ejeeedœdd
„ZdZd,eeeef  ee
e	f eedœdd„Zd-ejeedœdd„Zd.ejeedœd d„Zd/eeeejf  eeeeed#f f eeeeej  f d$œd%d„Z d0d&d„Z!d'd„ Z"dS )1é    N)Údefaultdict)Úchain)ÚAnyÚCallableÚDictÚIteratorÚTupleÚTypeÚUnion)Únn)Ú
checkpointÚmodel_parametersÚnamed_applyÚnamed_modulesÚnamed_modules_with_paramsÚadapt_input_convÚgroup_with_matcherÚgroup_modulesÚgroup_parametersÚflatten_modulesÚcheckpoint_seqF©ÚmodelZexclude_headc                 C   s*   |rdd„ |   ¡ D ƒd d… S |   ¡ S d S )Nc                 S   s   g | ]}|‘qS © r   )Ú.0Úpr   r   úV/var/www/html/bwave/python/venv/lib/python3.8/site-packages/timm/models/_manipulate.pyÚ
<listcomp>   s     z$model_parameters.<locals>.<listcomp>éþÿÿÿ)Ú
parametersr   r   r   r   r      s    Ú T)ÚfnÚmoduleÚdepth_firstÚinclude_rootÚreturnc                 C   sf   |s|r| ||d� |  ¡ D ]0\}}|r6d ||f¡n|}t| |||dd� q|rb|rb| ||d� |S )N)r"   ÚnameÚ.T)r!   r"   r&   r#   r$   )Únamed_childrenÚjoinr   )r!   r"   r&   r#   r$   Ú
child_nameÚchild_moduler   r   r   r      s    ©r"   r&   r#   r$   c                 c   sf   |s|r|| fV  |   ¡ D ]4\}}|r4d ||f¡n|}t|||dd�E d H  q|rb|rb|| fV  d S ©Nr'   Tr,   )r(   r)   r   ©r"   r&   r#   r$   r*   r+   r   r   r   r   (   s    
   ÿc                 c   sr   | j r|s|r|| fV  |  ¡ D ]4\}}|r:d ||f¡n|}t|||dd�E d H  q | j rn|rn|rn|| fV  d S r-   )Ú_parametersr(   r)   r   r.   r   r   r   r   8   s    
   ÿ)iŸ† )Únamed_objectsÚgroup_matcherÚreturn_valuesÚreversec                    sj  t ˆ tƒrˆg }tˆ  ¡ ƒD ]h\}\}}|d kr0qt |ttfƒrj|D ]$}|t |d ¡|f|d fg7 }qBq|t |¡|fd fg7 }q|‰ ‡ fdd„}	ttƒ}
| D ]"\}}|
|	|ƒ  	|r¼|n|¡ q ttƒ}d}t
tdd„ |
 ¡ ƒƒD ]:}|dk �s|d td k�r|d7 }||  |
| ¡ qæ|�rf|�r6tdƒ‚i }| ¡ D ]\}}|D ]}|||< �qN�qB|S |S )	Nr   é   c              	      sŠ   t ˆ ttfƒrbˆ D ]D\}}}| | ¡}|r|| ¡ |f}tttt t	d |ƒ¡ƒƒ  S qtdƒfS ˆ | ƒ}t |t
jjƒs~|fS t|ƒS d S )NÚinf)Ú
isinstanceÚlistÚtupleÚmatchÚgroupsÚmapÚfloatr   Úfrom_iterableÚfilterÚcollectionsÚabcÚIterable)r&   Zmatch_fnÚprefixÚsuffixÚrÚpartsÚord©r1   r   r   Ú_get_grouping`   s    
 
z)group_with_matcher.<locals>._get_groupingéÿÿÿÿc                 S   s   | d k	S )Nr   )Úxr   r   r   Ú<lambda>w   ó    z$group_with_matcher.<locals>.<lambda>z-reverse mapping only sensible for name output)r6   ÚdictÚ	enumerateÚitemsr8   r7   ÚreÚcompiler   ÚappendÚsortedr>   ÚkeysÚMATCH_PREV_GROUPÚextendÚAssertionError)r0   r1   r2   r3   ÚcompiledZgroup_ordinalÚ
group_nameZmspecZsspecrH   ÚgroupingÚkÚvZlayer_id_to_paramÚlidZparam_to_layer_idZlmÚnr   rG   r   r   K   s8    
$)r"   r2   r3   c                 C   s   t |  ¡ |||d�S ©N)r2   r3   )r   Znamed_parameters©r"   r1   r2   r3   r   r   r   r   ˆ   s       ÿc                 C   s   t t| ƒ|||d�S r_   )r   r   r`   r   r   r   r   ’   s       ÿr4   Ú
sequential.)r   ÚdepthrB   Úmodule_typesc                 c   s¶   t |tƒ}t |tƒr6|dkr.tjtjtjf}ntjf}| D ]v\}}|rzt ||ƒrzt| ¡ |d |rh|fn||d�E d H  q:|r”||f }||fV  q:|r¦d 	||g¡}||fV  q:d S )NÚ	containerr4   )rB   rc   r'   )
r6   r8   Ústrr   Ú
SequentialZ
ModuleListZ
ModuleDictr   r(   r)   )r   rb   rB   rc   Zprefix_is_tupler&   r"   r   r   r   r   œ   s&    

ü
c           
      C   s¼   dd„ }t | tjjƒr|  ¡ } |r,t | ¡} t | ttfƒsBt| ƒ} t	| ƒ}|rV|d8 }d}t
d||ƒD ]0}	t|	| d |d ƒ}t||	|| ƒ||d�}qf|r¸||d t	| ƒd | ƒ|ƒS |S )a�  A helper function for checkpointing sequential models.

    Sequential models execute a list of modules/functions in order
    (sequentially). Therefore, we can divide such a sequence into segments
    and checkpoint each segment. All segments except run in :func:`torch.no_grad`
    manner, i.e., not storing the intermediate activations. The inputs of each
    checkpointed segment will be saved for re-running the segment in the backward pass.

    See :func:`~torch.utils.checkpoint.checkpoint` on how checkpointing works.

    .. warning::
        Checkpointing currently only supports :func:`torch.autograd.backward`
        and only if its `inputs` argument is not passed. :func:`torch.autograd.grad`
        is not supported.

    .. warning:
        At least one of the inputs needs to have :code:`requires_grad=True` if
        grads are needed for model inputs, otherwise the checkpointed part of the
        model won't have gradients.

    Args:
        functions: A :class:`torch.nn.Sequential` or the list of modules or functions to run sequentially.
        x: A Tensor that is input to :attr:`functions`
        every: checkpoint every-n functions (default: 1)
        flatten (bool): flatten nn.Sequential of nn.Sequentials
        skip_last (bool): skip checkpointing the last function in the sequence if True
        preserve_rng_state (bool, optional, default=True):  Omit stashing and restoring
            the RNG state during each checkpoint.

    Returns:
        Output of running :attr:`functions` sequentially on :attr:`*inputs`

    Example:
        >>> model = nn.Sequential(...)
        >>> input_var = checkpoint_seq(model, input_var, every=2)
    c                    s   ‡ ‡‡fdd„}|S )Nc                    s$   t ˆˆ d ƒD ]}ˆ| | ƒ} q| S )Nr4   )Úrange)Z_xÚj©ÚendÚ	functionsÚstartr   r   Úforwardç   s    z5checkpoint_seq.<locals>.run_function.<locals>.forwardr   )rl   rj   rk   rm   r   ri   r   Úrun_functionæ   s    z$checkpoint_seq.<locals>.run_functionr4   rI   r   )Úpreserve_rng_state)r6   Útorchr   rf   Úchildrenr   r=   r8   r7   Úlenrg   Úminr   )
rk   rJ   ZeveryÚflattenZ	skip_lastro   rn   Znum_checkpointedrj   rl   r   r   r   r   º   s"    ,
c                 C   sî   |j }| ¡ }|j\}}}}| dkrx|dkrh|jd d dksBt‚| ||d d||¡}|jddd�}qà|jddd�}nh| dkrà|dkr’tdƒ‚nNtt 	| d ¡ƒ}| 
d|dd¡d d …d | …d d …d d …f }|dt| ƒ 9 }| |¡}|S )	Nr4   é   r   é   F)ÚdimZkeepdimTz*Weight format not supported by conversion.)Zdtyper<   ÚshaperW   ZreshapeÚsumÚNotImplementedErrorÚintÚmathÚceilÚrepeatÚto)Zin_chansZconv_weightZ	conv_typeÚOÚIÚJÚKr~   r   r   r   r      s"    
,
)F)r    TF)r    TF)r    TF)FF)FF)FF)r4   r    ra   )r4   FFT)#Úcollections.abcr?   r|   rP   r   Ú	itertoolsr   Útypingr   r   r   r   r   r	   r
   rp   r   Ztorch.utils.checkpointr   Ú__all__ÚModuleÚboolr   r   re   r   r   rU   r   r   r   r{   r   r   r   r   r   r   r   Ú<module>   s¤   $
    ÿ
   üû   üü   üü  ü
ü@  üü  üü   üü!    ú
F