
    ^j1                        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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j0                  d
efdZ	 	 	 d/de	dej0                  dededej0                  f
dZ	 	 	 d/dej0                  dededefdZ	 	 	 d/dej0                  dededefdZdZ	 	 d0deeeef      dee
e	f   dedefdZ 	 	 d0dej0                  dedefdZ!	 	 d0dej0                  dedefdZ"	 	 	 d1deeeej0                  f      de#deeeed f   f   d!eeeeej0                        f   fd"Z$dd#d$ee   fd%Z%	 	 	 	 d2d&e#d'ed(ed$ee   fd)Z&d*e#d+edefd,Z'd	ej0                  dee   fd-Z(y)3    N)defaultdict)chain)	AnyCallableDictIteratorList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
checkpointreinit_non_persistent_buffersmodelexclude_headc                 r    |r!| j                         D cg c]  }| c}d d S | j                         S c c}w )N)
parameters)r   r   ps      b/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/models/_manipulate.pyr   r      s:     ++-.a.s33!! /s   	4fnmoduledepth_firstinclude_rootreturnc                     |s|r
 | ||       |j                         D ],  \  }}|rdj                  ||f      n|}t        | |||d       . |r|r
 | ||       |S )N)r%   name.T)r$   r%   r*   r&   r'   )named_childrenjoinr   )r$   r%   r*   r&   r'   
child_namechild_modules          r#   r   r      sp     <
&t$$*$9$9$; m 
L59SXXtZ01z
r,Z[gklm |
&t$M    r*   c              #      K   |s|r|| f | j                         D ]3  \  }}|rdj                  ||f      n|}t        |||d      E d {    5 |r
|r|| f y y y 7 wNr+   T)r%   r*   r&   r'   )r,   r-   r   r%   r*   r&   r'   r.   r/   s         r#   r   r   -   s      <Fl$*$9$9$; ^ 
L59SXXtZ01z
 jkX\^ 	^ 	^^ |Fl ${	^s   A
A"A A"c              #      K   | j                   r
|s|r|| f | j                         D ]3  \  }}|rdj                  ||f      n|}t        |||d      E d {    5 | j                   r|r
|r|| f y y y y 7  wr2   )_parametersr,   r-   r   r3   s         r#   r   r   =   s      +,Fl$*$9$9$; ^ 
L59SXXtZ01z
,jkX\^ 	^ 	^^ klFl /;k	^s   AA;A9!A;)i named_objectsgroup_matcherreturn_valuesreversec                    t        t              rg }t        j                               D ]i  \  }\  }}|t        |t        t
        f      r+|D ]%  }|t        j                  |d         |f|d   fgz  }' M|t        j                  |      |fd fgz  }k |fd}	t        t
              }
| D ]#  \  }}|
 |	|         j                  |r|n|       % t        t
              }d}t        t        d |
j                                     D ]2  }|dk  s|d   t        d   k7  r|dz  }||   j                  |
|          4 |r1|rJ d       i }|j                         D ]  \  }}|D ]  }|||<   	  |S |S )Nr      c                    t        t        t        f      ruD ]d  \  }}}|j                  |       }|s||j	                         |f}t        t        t        t        j                  t        d |                        c S  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ordr7   s          r#   _get_groupingz)group_with_matcher.<locals>._get_groupinge   s    mdE]3,9 W(&&NN4(#QXXZ8E UE,?,?tU@S,T!UVVW <= %Cc;??#;#;<t:r0   c                 
    | d uS )N )xs    r#   <lambda>z$group_with_matcher.<locals>.<lambda>|   s
    Qd] r0   z-reverse mapping only sensible for name output)r>   dict	enumerateitemsr@   r?   recompiler   appendsortedrF   keysMATCH_PREV_GROUPextend)r6   r7   r8   r9   compiledgroup_ordinal
group_namemspecsspecrP   groupingkvlayer_id_to_paramlidparam_to_layer_idlmns    `                r#   r   r   P   s    -&2;M<O<O<Q2R 		J.M.J}%%/" UE"**U1X"68H%PQ(!S TTHU bjj/-1A4HII		J !  4 H E1q!"))}!!DE $D)
CF2HMMODE 37ae/221HC#%%hqk23
  Q"QQ (..0 	+GC +'*!!$+	+ ! r0   c                 <    t        | j                         |||      S N)r8   r9   )r   named_parametersr%   r7   r8   r9   s       r#   r   r      s&     !=W^` `r0   c                 2    t        t        |       |||      S rn   )r   r   rp   s       r#   r   r      s"     !&)=_fh hr0   r   depthrK   .module_typesc              #     K   t        |t              }t        |t              rF|dk(  r0t        j                  t        j
                  t        j                  f}nt        j                  f}| D ]k  \  }}|r:t        ||      r.t        |j                         |dz
  |r|fn||      E d {    B|r||fz   }||f Q|rdj                  ||g      }||f m y 7 2w)N	containerr;   )rK   rs   r+   )
r>   r@   strr   
Sequential
ModuleList
ModuleDictr   r,   r-   )r   rr   rK   rs   prefix_is_tupler*   r%   s          r#   r   r      s      !/O,$;&MM2=="--HLMM+L% #fZ5&%%'	"1wt)	   'Fl"88VTN3DFl"#s   B%C'C(3Cuse_reentrantr|   c                x    |
t               }t        j                  j                  j                  | g|d|i|S )z~ checkpoint wrapper fn

    A thin wrapper around torch.utils.checkpoint.checkpoint to default
    use_reentrant to False
    r|   )r   torchutilsr   )functionr|   argskwargss       r#   r   r      sN     *,;;!!,,	 $ 	 r0   everyflatten	skip_lastc                    |
t               }d }t        | t        j                  j                        r| j                         } |rt        j                  |       } t        | t        t        f      st        |       } t        |       }|r|dz  }d}t        d||      D ]K  }	t        |	|z   dz
  |dz
        }t        j                  j                  j                   ||	||       ||      }M |r  ||dz   t        |       dz
  |       |      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)
    c                       fd}|S )Nc                 F    t        dz         D ]  } |   |       }  | S )Nr;   )range)_xjend	functionsstarts     r#   forwardz5checkpoint_seq.<locals>.run_function.<locals>.forward  s2    5#'* &!Yq\"%&Ir0   rS   )r   r   r   r   s   ``` r#   run_functionz$checkpoint_seq.<locals>.run_function  s    	 r0   r;   rQ   r   r{   )r   r>   r~   r   rw   childrenr   rE   r@   r?   lenr   minr   r   )
r   rT   r   r   r   r|   r   num_checkpointedr   r   s
             r#   r   r      s   V *, )UXX001&&(	''	2	i%/)$	9~A
Cq*E2 
%%-!#%5%9:KK""--Y/' . 

 C|C!GS^a%7CAFFHr0   in_chansconv_weightc                 h   |j                   }|j                         }|j                  dk7  rt        d|j                   d      |j                  \  }}}}| dk(  r\|dkD  rC|j                  d   dz  dk(  sJ |j                  ||dz  d||      }|j                  dd	      }n~|j                  dd
	      }nj| dk7  re|dk7  rt        d      t        t        j                  | dz              }|j                  d|dd      d d d | d d d d f   }|dt        |       z  z  }|j                  |      }|S )N   z;adapt_input_conv only supports 4D Conv2d weights; got ndim=r+   r;      r      F)dimkeepdimTz*Weight format not supported by conversion.)dtyperD   ndimNotImplementedErrorshapereshapesumintmathceilrepeatto)r   r   	conv_typeOIJKr   s           r#   r   r   !  sO   !!I##%K1 "I+JZJZI[[\]
 	
 ""JAq!Q1}q5$$Q'!+q000%--aaAqAK%//a/?K%//a/>K	Q6%&RSS 8a<01F%,,Q1=a(Aq>PQKAh/0K..+Kr0   c                     g }| j                         D ]7  \  }}t        |d      s|j                          |j                  |r|nd       9 |S )a  Walk model and call init_non_persistent_buffers() on modules that have it.

    This reinitializes computed buffers (like RoPE frequencies, attention bias indices)
    that are marked as non-persistent and thus not saved in checkpoints. These buffers
    are typically computed from module configuration and need to be reinitialized after
    loading a checkpoint.

    Args:
        model: Model to reinitialize buffers for

    Returns:
        List of module names that were reinitialized

    Example:
        >>> model = create_model('vit_base', pretrained=True)
        >>> # After loading checkpoint or moving to new device
        >>> reinitialized = reinit_non_persistent_buffers(model)
        >>> print(f"Reinitialized {len(reinitialized)} modules")
    init_non_persistent_buffersz(root))r   hasattrr   r[   )r   reinitializedr*   r%   s       r#   r   r   A  sV    ( M++- =f689..0  8<= r0   )F) TF)FF)r;   r   
sequential)r;   FFN))collections.abcrG   r   rY   r   	itertoolsr   typingr   r   r   r   r	   r
   r   r   r   r~   torch.utils.checkpointr   r   timm.layersr   __all__Moduleboolr   r   rv   r   r   r^   r   r   r   r   r   r   r   r   r   rS   r0   r#   <module>r      s     	 #  T T T     *,
"BII "T " !# "			  	
 YY$  "			  	$  "			  	    $	:c3h0:T8^,: : 	:@ $	`		` ` 	` $	h		h h 	h .0;G	#c299n 56## c5c?*+# CtBII!778	#B %) D>2 (,I I 	I
 I  ~IXs  F @ tCy r0   