o
    پi|+                     @   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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 g dZd<d
ejdefddZ				d=de	dejdededejf
ddZ				d=dejdededefddZ				d=dejdededefddZdZ				d>deeeef  dee
e	f ded efd!d"Z				d>dejded efd#d$Z 				d>dejded efd%d&Z!	'		(d?deeeejf  d)e"d*eeeed+f f d,eeeeej  f fd-d.Z#dd/d0ee fd1d2Z$	'					d@d3e"d4ed5ed0ee fd6d7Z%d8e"d9edefd:d;Z&dS )A    N)defaultdict)chain)AnyCallableDictIteratorOptionalTupleTypeUnion)nn)Tensor)use_reentrant_ckpt)model_parametersnamed_applynamed_modulesnamed_modules_with_paramsadapt_input_convgroup_with_matchergroup_modulesgroup_parametersflatten_modulescheckpoint_seq
checkpointFmodelexclude_headc                 C   s&   |rdd |   D d d S |   S )Nc                 S   s   g | ]}|qS  r   ).0pr   r   K/home/ubuntu/.local/lib/python3.10/site-packages/timm/models/_manipulate.py
<listcomp>   s    z$model_parameters.<locals>.<listcomp>)
parameters)r   r   r   r   r   r      s   r    Tfnmoduledepth_firstinclude_rootreturnc                 C   sf   |s
|r
| ||d |  D ]\}}|rd||fn|}t| |||dd q|r1|r1| ||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)   c                 c   sp    |s
|r
|| fV  |   D ]\}}|rd||fn|}t|||ddE d H  q|r4|r6|| fV  d S d S d S Nr*   T)r%   r)   r&   r'   )r+   r,   r   r%   r)   r&   r'   r-   r.   r   r   r   r   ,   s   
r   c                 c   s    | j r|s|r|| fV  |  D ]\}}|rd||fn|}t|||ddE d H  q| j r:|r<|r>|| fV  d S d S d S d S r/   )_parametersr+   r,   r   r0   r   r   r   r   <   s   
r   )i named_objectsgroup_matcherreturn_valuesreversec                    s^  t  trDg }t  D ]4\}\}}|d u rqt |ttfr5|D ]}|t|d |f|d fg7 }q!q|t||fd fg7 }q|  fdd}	tt}
| D ]\}}|
|	| 	|r^|n| qPtt}d}t
tdd |
 D ]}|dk s|d td kr|d7 }|| |
|  qs|r|rJ di }| D ]\}}|D ]}|||< qq|S |S )	Nr      c              	      s   t  ttfr1 D ]"\}}}|| }|r+|| |f}ttttt	d |  S q	tdfS  | }t |t
jjs?|fS t|S )Ninf)
isinstancelisttuplematchgroupsmapfloatr   from_iterablefiltercollectionsabcIterable)r)   match_fnprefixsuffixrpartsordr3   r   r   _get_groupingd   s   

z)group_with_matcher.<locals>._get_groupingc                 S   s   | d uS )Nr   )xr   r   r   <lambda>{   s    z$group_with_matcher.<locals>.<lambda>z-reverse mapping only sensible for name output)r8   dict	enumerateitemsr:   r9   recompiler   appendsortedr@   keysMATCH_PREV_GROUPextend)r2   r3   r4   r5   compiledgroup_ordinal
group_namemspecsspecrK   groupingkvlayer_id_to_paramlidparam_to_layer_idlmnr   rJ   r   r   O   s<   
"
r   c                 C   s   t |  |||dS N)r4   r5   )r   named_parametersr%   r3   r4   r5   r   r   r   r         r   c                 C   s   t t| |||dS rf   )r   r   rh   r   r   r   r      ri   r   r6   
sequentialdepthrE   .module_typesc                 c   s    t |t}t |tr|dkrtjtjtjf}ntjf}| D ];\}}|r>t ||r>t| |d |r5|fn||dE d H  q|rK||f }||fV  q|rTd	||g}||fV  qd S )N	containerr6   )rE   rl   r*   )
r8   r:   strr   
Sequential
ModuleList
ModuleDictr   r+   r,   )r   rk   rE   rl   prefix_is_tupler)   r%   r   r   r   r      s*   


r   use_reentrantrt   c                O   s.   |du rt  }tjjj| g|R d|i|S )z~ checkpoint wrapper fn

    A thin wrapper around torch.utils.checkpoint.checkpoint to default
    use_reentrant to False
    Nrt   )r   torchutilsr   )functionrt   argskwargsr   r   r   r      s   r   everyflatten	skip_lastc           
      C   s   |du rt  }dd }t| tjjr|  } |rt| } t| tt	fs(t| } t
| }|r2|d8 }d}td||D ]}	t|	| d |d }tjjj||	|| ||d}q:|rf||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: flatten nn.Sequential of nn.Sequentials
        skip_last: skip checkpointing the last function in the sequence if True
        use_reentrant: Use re-entrant checkpointing

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

    Example:
        >>> model = nn.Sequential(...)
        >>> input_var = checkpoint_seq(model, input_var, every=2)
    Nc                    s    fdd}|S )Nc                    s$   t  d D ]}| | } q| S )Nr6   )range)_xjend	functionsstartr   r   forward  s   z5checkpoint_seq.<locals>.run_function.<locals>.forwardr   )r   r   r   r   r   r   r   run_function  s   z$checkpoint_seq.<locals>.run_functionr6   rL   r   rs   )r   r8   ru   r   ro   childrenr   r?   r:   r9   lenr}   minrv   r   )
r   rM   rz   r{   r|   rt   r   num_checkpointedr   r   r   r   r   r      s.   +

r   in_chansconv_weightc                 C   s   |j }| }|j\}}}}| dkr<|dkr4|jd d dks!J |||d d||}|jddd}n;|jddd}n3| dkro|dkrHtdtt| d }|	d|ddd d d | d d d d f }|dt|  9 }|
|}|S )	Nr6      r      F)dimkeepdimTz*Weight format not supported by conversion.)dtyper>   shapereshapesumNotImplementedErrorintmathceilrepeatto)r   r   	conv_typeOIJKr   r   r   r   r      s"   ,
r   )F)r#   TF)FF)r6   r#   rj   )r6   FFN)'collections.abcrA   r   rR   r   	itertoolsr   typingr   r   r   r   r   r	   r
   r   ru   torch.utils.checkpointr   r   timm.layersr   __all__Moduleboolr   r   rn   r   r   rW   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s    (





@


!

L