a
    d)                  	   @   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 g d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d0eeeejf  eeeeed!f f eeeeej  f d"d#d$Z d1d%d&Z!d'd( Z"dS )2    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   `/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/models/_manipulate.py
<listcomp>       z$model_parameters.<locals>.<listcomp>)
parametersr   r   r   r   r      s    r    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$   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    
r   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    
r   )i )named_objectsgroup_matcherreturn_valuesreversec                    sj  t  trg }t  D ]h\}\}}|d u 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| qtt}d}t
tdd |
 D ]:}|dk s|d td kr|d7 }|| |
|  q|rf|r6J 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r2   r   r   _get_grouping`   s    
 
z)group_with_matcher.<locals>._get_groupingc                 S   s   | d uS )Nr   )xr   r   r   <lambda>w   r   z$group_with_matcher.<locals>.<lambda>z-reverse mapping only sensible for name output)r7   dict	enumerateitemsr9   r8   recompiler   appendsortedr?   keysMATCH_PREV_GROUPextend)r1   r2   r3   r4   ZcompiledZgroup_ordinalZ
group_nameZmspecZsspecrI   groupingkvZlayer_id_to_paramZlidZparam_to_layer_idZlmnr   rH   r   r   K   s8    
$r   )r#   r3   r4   c                 C   s   t |  |||dS N)r3   r4   )r   Znamed_parametersr#   r2   r3   r4   r   r   r   r      s    r   c                 C   s   t t| |||dS r[   )r   r   r\   r   r   r   r      s    r   r5   
sequential.)r   depthrC   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:|rd	||g}||fV  q:d S )N	containerr5   )rC   r_   r(   )
r7   r9   strr   
SequentialZ
ModuleListZ
ModuleDictr   r)   r*   )r   r^   rC   r_   Zprefix_is_tupler'   r#   r   r   r   r      s&    


r   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 )Nr5   )range)_xjend	functionsstartr   r   forward   s    z5checkpoint_seq.<locals>.run_function.<locals>.forwardr   )ri   rg   rh   rj   r   rf   r   run_function   s    z$checkpoint_seq.<locals>.run_functionr5   rJ   r   )preserve_rng_state)r7   torchr   rb   childrenr   r>   r9   r8   lenrc   minr   )
rh   rK   ZeveryflattenZ	skip_lastrl   rk   Znum_checkpointedrg   ri   r   r   r   r      s"    ,
r   c                 C   s   |j }| }|j\}}}}| dkrx|dkrh|jd d dksBJ |||d d||}|jddd}q|jddd}nh| dkr|dkrtdnNtt| d }|	d|ddd d d | d d d d f }|dt|  9 }|
|}|S )	Nr5      r      F)ZdimZkeepdimTz*Weight format not supported by conversion.)Zdtyper=   shapeZreshapesumNotImplementedErrorintmathceilrepeatto)Zin_chansZconv_weightZ	conv_typeOIJKrz   r   r   r   r      s"    
,
r   )F)r!   TF)r!   TF)r!   TF)FF)FF)FF)r5   r!   r]   )r5   FFT)#collections.abcr@   rx   rP   r   	itertoolsr   typingr   r   r   r   r   r	   r
   rm   r   Ztorch.utils.checkpointr   __all__Moduleboolr   r   ra   r   r   rU   r   r   r   rw   r   r   r   r   r   r   r   <module>   s   $
           
@       !    
F