
    Z j4B              
          S r SSKrSSKrSSKrSSKJr  SSKJr  SSKJ	r	  \R                  " \5      r " S S\R                  5      r " S	 S
5      rS r " S S5      r    SS\S-  S\S-  S\S-  S\S-  4S jjrS rg)zACollection of utils to be used by backbones and their components.    N)repo_exists   )logging)maybe_install_capturing_hooksc                       \ rS rSrSrSrSrg)BackboneType   timmtransformers N)__name__
__module____qualname____firstlineno__TIMMTRANSFORMERS__static_attributes__r       l/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/backbone_utils.pyr   r      s    D!Lr   r   c                      ^  \ rS rSrSrS\S-  S\S-  4S jrS r\S 5       r	\	R                  S\\   4S	 j5       r	\S
 5       r\R                  S\\S4   \\   -  4S j5       rU 4S jrSrU =r$ )BackboneConfigMixin#   zn
A Mixin to support handling the `out_features` and `out_indices` attributes for the backbone configurations.
out_featuresNout_indicesc                    Xl         [        U[        5      (       a  [        U5      OUU l        U R                  5         U R                   U R                  p!Uc-  Uc*  [        U R                  5      S-
  /nU R                  S   /nOUUc.  Ub+  U Vs/ s H  o0R                  R                  U5      PM     nnO$Uc!  Ub  U Vs/ s H  o@R                  U   PM     nnXsU l         U l        U R                  5         gs  snf s  snf )a(  
Sets output indices and features to new values and aligns them with the given `stage_names`.
If one of the inputs is not given, find the corresponding `out_features` or `out_indices`
for the given `stage_names`.

Args:
    out_features (`list[str]`, *optional*):
        The names of the features for the backbone to output. Defaults to `config._out_features` if not provided.
    out_indices (`list[int]` or `tuple[int]`, *optional*):
        The indices of the features for the backbone to output. Defaults to `config._out_indices` if not provided.
Nr   )	_out_features
isinstancetuplelist_out_indicesverify_out_features_out_indiceslenstage_namesindex)selfr   r   layeridxs        r   "set_output_features_output_indices6BackboneConfigMixin.set_output_features_output_indices(   s      *1;K1O1OD-U` 	,,. %)$6$68I8Ik<#7t//0145K ,,R01L \%=FRSlU++11%8lKSK!k&==HI[c,,S1[LI 1=-D-,,. TIs   $C9 C>c                   ^  T R                   c  [        S5      eT R                  Gb0  [        T R                  [        45      (       d!  [        S[        T R                  5       35      e[        U 4S jT R                   5       5      (       a%  [        ST R                    ST R                   35      e[        T R                  5      [        [        T R                  5      5      :w  a  [        ST R                   35      eT R                  T R                    Vs/ s H  oT R                  ;   d  M  UPM     sn=n:w  a  [        SU ST R                   35      eT R                  GbY  [        T R                  [        5      (       d!  [        S	[        T R                  5       35      e[        U 4S
 jT R                   5       5      n[        U 4S jU 5       5      (       a%  [        ST R                    ST R                   35      e[        U5      [        [        U5      5      :w  a4  ST R                   3nXCT R                  :w  a  SU S3OS-  n[        U5      eU[        [        U5      5      :w  aN  [        [        UT R                  5      S S9 VVs/ s H  u  pVUPM	     nnn[        SU ST R                   35      eT R                  b  T R                  b{  [        T R                  5      [        T R                  5      :w  a  [        S5      eT R                  T R                   Vs/ s H  nT R                   U   PM     sn:w  a  [        S5      egggs  snf s  snnf s  snf )zO
Verify that out_indices and out_features are valid for the given stage_names.
Nz2Stage_names must be set for transformers backbonesz out_features must be a list got c              3   @   >#    U  H  oTR                   ;  v   M     g 7fN)r$   ).0featr&   s     r   	<genexpr>FBackboneConfigMixin.verify_out_features_out_indices.<locals>.<genexpr>V   s     O<NDt///<Ns   z.out_features must be a subset of stage_names: z got z2out_features must not contain any duplicates, got z@out_features must be in the same order as stage_names, expected z out_indices must be a list, got c              3   b   >#    U  H$  oS :  a  U[        TR                  5      -  OUv   M&     g7f)r   N)r#   r$   r.   r(   r&   s     r   r0   r1   g   s.     $r`qY\!GS3t/?/?+@%@QT%T`qs   ,/c              3   n   >#    U  H*  o[        [        TR                  5      5      ;  d  M&  Uv   M,     g 7fr-   )ranger#   r$   r3   s     r   r0   r1   h   s*     ^"23s4K[K[G\A]6]33"2s   %5	5z2out_indices must be valid indices for stage_names z, got z1out_indices must not contain any duplicates, got z(equivalent to z)) c                     U S   $ )Nr   r   )xs    r   <lambda>EBackboneConfigMixin.verify_out_features_out_indices.<locals>.<lambda>r   s    efgheir   )keyz?out_indices must be in the same order as stage_names, expected zHout_features and out_indices should have the same length if both are setzQout_features and out_indices should correspond to the same stages if both are set)r$   
ValueErrorr   r   r    typeanyr#   setr!   r   sortedzip)r&   r/   sorted_featspositive_indicesmsg_r(   sorted_negatives   `       r   r"   3BackboneConfigMixin.verify_out_features_out_indicesL   sG    #QRR)d004':: #CDI[I[D\C]!^__OD<N<NOOO DTEUEUDVV[\`\n\n[op  4%%&#c$2D2D.E*FF #UVZVhVhUi!jkk!!262B2B a2B$dN`N`F`2B aa !VWcVddijnj|j|i}~  (d//66 #CDIZIZD[C\!]^^$$r`d`q`q$rr^"2^^^ HIYIYHZZ`aearar`st  #$C0@,A(BBI$J[J[I\]UYUfUfAf)9(:"=lnn o%50@)A#BB&,S1A4CTCT-U[i&j#&jFAC&j   # !UVeUffklpl}l}k~  )d.?.?.K4%%&#d.?.?*@@ !kll!!tGXGX%YGXd&6&6s&;GX%YY !tuu Z /L)7 !b(# &Zs   M/MM)M!c                     U R                   $ r-   )r   r&   s    r   r    BackboneConfigMixin.out_features~   s    !!!r   c                 $    U R                  USS9  g)p
Set the out_features attribute. This will also update the out_indices attribute to match the new out_features.
Nr   r   )r)   r&   r   s     r   r   rJ      s    
 	//\W[/\r   c                     U R                   $ r-   )r!   rI   s    r   r   BackboneConfigMixin.out_indices   s       r   .c                 D    Ub  [        U5      OUnU R                  SUS9  g)o
Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
NrM   )r    r)   r&   r   s     r   r   rP      s(    
 ,7+Bd;'//T{/[r   c                 x   > [         TU ]  5       nUR                  SS5      US'   UR                  SS5      US'   U$ )z
Serializes this instance to a Python dictionary. Override the default `to_dict()` from `PreTrainedConfig` to
include the `out_features` and `out_indices` attributes.
r   Nr   r!   r   )superto_dictpop)r&   output	__class__s     r   rV   BackboneConfigMixin.to_dict   s@    
 "!'OT!B~ &

>4 @}r   )r   r!   )r   r   r   r   __doc__r    r)   r"   propertyr   setterstrr   r   intrV   r   __classcell__rY   s   @r   r   r   #   s    "/Tk"/ D["/H0vd " " ]c ] ] ! ! \uS#Xc'B \ \ r   r   c                 F   ^  [         R                  " T 5      U 4S j5       nU$ )aW  
Wrapper to filer out `hidden_states` as backbones tend to always use them to get their feature maps, i.e.
they also always output `hidden_states`. This controls for user-defined behavior again.

NOTE: We assume a `can_return_tuple` decorator to be applied before so that we always expect a dict like
      object to remove the hidden states.
c                   > UR                  S[        U R                  SS5      5      nT" U /UQ70 UD6nU(       d=  UR                  5        VVs0 s H  u  pVUS;  d  M  XV_M     nnn[	        U5      " S0 UD6nU$ s  snnf )Noutput_hidden_statesFhidden_statesr   )getgetattrconfigitemsr=   )	r&   argskwargsrd   rX   kvfiltered_output_dataforward_functions	           r   wrapper,filter_output_hidden_states.<locals>.wrapper   s    %zz*@'$++WmotBuv!$888#5;\\^#b^TQqQ`GaDAD^ #b&\9$89F $cs   A;A;)	functoolswraps)ro   rp   s   ` r   filter_output_hidden_statesrt      s(     __%& ' Nr   c                   X  ^  \ rS rSr% Sr\S-  \S'   Sr\\S'   SU 4S jjr	U 4S jr
SS jrSS	 jr\S
 5       r\R                  S\\   4S j5       r\S 5       r\R                  S\\   \\   -  4S j5       r\S 5       r\S 5       rS r   SS\S-  S\S-  S\S-  4S jjrSrU =r$ )BackboneMixin   Nbackbone_typeThas_attentionsc                   > [         TU ]  " U0 UD6  UR                  SS5      nUb  [        R                  U l        O[        R                  U l        U R
                  [        R                  :X  a  U R                  US9  gU R
                  [        R                  :X  a  U R                  5         g[        SU R
                   S35      e)z
Method to initialize the backbone. This method is called by the constructor of the base class after the
pretrained model weights have been loaded.
timm_backboneN)backbonezbackbone_type z not supported.)
rU   __init__rW   r   r   rx   r   _init_timm_backbone_init_transformers_backboner<   )r&   rj   rk   r{   rY   s       r   r}   BackboneMixin.__init__   s    
 	$)&)

?D9$!-!2!2D!-!:!:D!2!22$$m$<<#<#<<,,.~d.@.@-AQRRr   c                 8   > [         TU ]  5         [        U 5        g)am  
Override `post_init` to always install capturing hooks, as backbone will ALWAYS capture outputs. We need to do
it in `post_init`, as modules need to be already instantiated.
It avoids some mixups with `torch.compile`, as the first hook installation will need/create a graph break,
which can clash with external user call such as `model = torch.compile(model...)`.
N)rU   	post_initr   )r&   rY   s    r   r   BackboneMixin.post_init   s     	%d+r   c                 z   [        U R                  SS5      n[        U R                  SS5      nUR                  R                   Vs/ s H  oDS   PM	     snU l        UR                  R                   Vs/ s H  oDS   PM	     snU l        [        UR                  R                  5      nUR                  R                  5       nUb  X&:w  a  [        SU S35      eUb  X0R                  :w  a  [        SU S	35      eU R                  U R                  l        U R                  R                  Xe5        gs  snf s  snf )
zZ
Initialize the backbone model from timm. The backbone must already be loaded to backbone
r   Nr$   modulenum_chsz!Config has `out_features` set to z which doesn't match `out_features` from backbone's feature_info. Please check if your checkpoint has correct out features/indices saved.z Config has `stage_names` set to z which doesn't match `stage_names` from backbone's feature_info. Please check if your checkpoint has correct `stage_names` saved.)rg   rh   feature_infoinfor$   num_featuresr    r   module_namer<   r)   )r&   r|   out_features_from_configstage_names_from_configstager   r   s          r   r~   !BackboneMixin._init_timm_backbone   s;   
 $+4;;#M ")$++}d"K
 :B9N9N9S9ST9S(O9ST;C;P;P;U;UV;U%9-;UV800<<=,,88:#/4L4\34L3M Nx x 
 #.3JN^N^3^23J2K Lq q  #'"2"266|Q) UVs   D35D8c                 |    U R                   R                  U l        U R                   R                  5         S U l        g r-   )rh   r$   r"   r   rI   s    r   r   )BackboneMixin._init_transformers_backbone   s,    ;;22335 r   c                 .    U R                   R                  $ r-   )rh   r   rI   s    r   r   BackboneMixin.out_features  s    {{(((r   r   c                 $    XR                   l        g)rL   N)rh   r   rN   s     r   r   r     s    
 $0 r   c                 .    U R                   R                  $ r-   )rh   r!   rI   s    r   r   BackboneMixin.out_indices  s    {{'''r   r   c                 $    XR                   l        g)rR   N)rh   r   rS   s     r   r   r     s    
 #.r   c                 |    [        U R                  5       VVs0 s H  u  pX R                  U   _M     snn$ s  snnf r-   )	enumerater$   r   )r&   ir   s      r   out_feature_channels"BackboneMixin.out_feature_channels  s:     =FdFVFV<WX<W((++<WXXXs   8c                 ^    U R                    Vs/ s H  oR                  U   PM     sn$ s  snf r-   )r   r   )r&   names     r   channelsBackboneMixin.channels  s+    <@<M<MN<MD))$/<MNNNs   *c                 \   U R                   (       d  UR                  SS 5        U R                  [        R                  :X  a^  [        [        R                  " U R                  5      R                  5      nUR                  5        VVs0 s H  u  pEXC;   d  M  XE_M     nnnU " U0 UD6$ s  snnf )Noutput_attentions)ry   rW   rx   r   r   dictinspect	signatureforward
parametersri   )r&   rj   rk   r   rl   rm   s         r   forward_with_filtered_kwargs*BackboneMixin.forward_with_filtered_kwargs"  s    ""JJ*D1!2!22W..t||<GGHI'-||~H~tqdad~FHT$V$$ Is   B(B(rd   r   return_dictc                     [        S5      e)Nz7This method should be implemented by the derived class.)NotImplementedError)r&   pixel_valuesrd   r   r   s        r   r   BackboneMixin.forward*  s     ""[\\r   )rx   r   r$   )returnN)NNN)r   r   r   r   rx   r   __annotations__ry   boolr}   r   r~   r   r\   r   r]   r    r^   r   r   r_   r   r   r   r   r   r`   ra   s   @r   rv   rv      s%   )-M<$&-  NDS&
,RB! ) ) 0c 0 0 ( ( .uSzDI'= . . Y Y
 O O% -1)-#'] #Tk]  $;	]
 D[] ]r   rv   default_backbonedefault_config_typedefault_config_kwargstimm_default_kwargsc                    SSK Jn  SSKJn  UR	                  SS5      nUR	                  S0 5      n	UR                  S5      b  UR	                  S5      OUn
UR	                  SS 5        Ub$  U(       a  U
b  U c  U	(       d  US	   " SSU
0UD6n X4$ U
bZ  U cW  [        U
5      (       a6  UR                  U
5      u  pX{S
      nUR                  U	5        U" S0 UD6n X4$ US	   " SSU
0U	D6n  X4$ U c4  Ub1  [        R                  SU S35        U=(       d    0 nXr   " S0 UD6n X4$ [        U [        5      (       a&  U R                  S
5      nX~   nUR                  U 5      n X4$ )Nr   )PreTrainedConfig)CONFIG_MAPPINGuse_timm_backboneTbackbone_kwargsr|   use_pretrained_backboner{   
model_typezG`backbone_config` is `None`. Initializing the config with the default `z` vision config.r   )configuration_utilsr   models.autor   rW   rf   r   get_config_dictupdateloggerr   r   r   	from_dict)backbone_configr   r   r   r   rk   r   r   r   r   r|   config_dictrE   config_classbackbone_model_types                  r   %consolidate_backbone_kwargs_to_configr   4  s    6+

#6=jj!2B7O)/J)?)Kvzz*%QaH
JJ($/
 	' #(9c8cObc( ""' 
	/"9x  -==hGNK)l*CDL/*9[9O "" -_=cxcSbcO "" 
	 %8%DUViUjjz{	
 !6 ;(=V@UV "" 
OT	*	*-11,?%:&00A""r   c                 r    SSK Jn  [        U SS5      nUc  UR                  U S9nU$ UR                  US9nU$ )a&  
Loads the backbone model from a config object.

If the config is from the backbone model itself, then we return a backbone model with randomly initialized
weights.

If the config is from the parent model of the backbone model itself, then we load the pretrained backbone weights
if specified.
r   )AutoBackboner   N)rh   )r   r   rg   from_config)rh   r   r   r|   s       r   load_backboner   f  sP     *f&7>O++6+: O  ++?+COr   )NNNN)r[   enumrr   r   huggingface_hubr   utilsr   utils.output_capturingr   
get_loggerr   r   Enumr   r   rt   rv   r^   r   r   r   r   r   r   <module>r      s    H    '  A 
		H	%"499 "
z zz*|] |]B $(&*)-'+/#Dj/# t/#  $;	/#
 /#dr   