
    笜i;              
           d Z ddlZddlZddlmZ ddlmZ  ej                  e      Z	 G d dej                        Z G d d	      Z G d
 d      Z	 	 	 	 ddedz  dedz  dedz  dedz  fdZd Zy)zACollection of utils to be used by backbones and their components.    N)repo_exists   )loggingc                       e Zd ZdZdZy)BackboneTypetimmtransformersN)__name__
__module____qualname__TIMMTRANSFORMERS     W/mnt/e/genesis-system/.venv/lib/python3.12/site-packages/transformers/backbone_utils.pyr   r      s    D!Lr   r   c                        e Zd ZdZdedz  dedz  fdZd Zed        Zej                  dee
   fd       Zed	        Zej                  deed
f   ee   z  fd       Z fdZ xZS )BackboneConfigMixinzv
    A Mixin to support handling the `out_features` and `out_indices` attributes for the backbone configurations.
    out_featuresNout_indicesc                    || _         t        |t              rt        |      n|| _        | j                          | j                   | j                  }}|,|*t        | j                        dz
  g}| j                  d   g}nM|+|)|D cg c]  }| j                  j                  |       }}n |||D cg c]  }| j                  |    }}||c| _         | _        | j                          yc c}w c c}w )ap  
        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_indicesz6BackboneConfigMixin.set_output_features_output_indices&   s     *1;K1OD-U` 	,,. %)$6$68I8Ik<#7t//0145K ,,R01L \%=FRSU4++11%8SKS!k&==HIcD,,S1ILI 1=k-D-,,. TIs   "C-5C2c                 z     j                   t        d       j                  t         j                  t        f      s!t        dt         j                               t         fd j                  D              r%t        d j                    d j                         t         j                        t        t         j                              k7  rt        d j                          j                   j                   D cg c]  }| j                  v s| c}x}k7  rt        d| d j                          j                  Lt         j                  t              s!t        d	t         j                               t         fd
 j                  D              }t         fd|D              r%t        d j                    d j                         t        |      t        t        |            k7  r4d j                   }|| j                  k7  rd| dndz  }t        |      |t        t        |            k7  rOt        t        | j                        d       D cg c]  \  }}|	 }}}t        d| d j                          j                   j                  vt         j                        t         j                        k7  rt        d       j                   j                  D cg c]  } j                   |    c}k7  rt        d      yyyc c}w c c}}w c c}w )z_
        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   :   K   | ]  }|j                   v  y wN)r   ).0featr!   s     r   	<genexpr>zFBackboneConfigMixin.verify_out_features_out_indices.<locals>.<genexpr>T   s     OD4t///Os   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   \   K   | ]#  }|d k  r|t        j                        z  n| % yw)r   N)r   r   r(   r#   r!   s     r   r*   zFBackboneConfigMixin.verify_out_features_out_indices.<locals>.<genexpr>e   s.     $rY\C!GS3t/?/?+@%@QT%T$rs   ),c              3   d   K   | ]'  }|t        t        j                              vs$| ) y wr'   )ranger   r   r,   s     r   r*   zFBackboneConfigMixin.verify_out_features_out_indices.<locals>.<genexpr>f   s(     ^3cs4K[K[G\A]6]3^s   %00z2out_indices must be valid indices for stage_names z, got z1out_indices must not contain any duplicates, got z(equivalent to z)) c                     | d   S )Nr   r   )xs    r   <lambda>zEBackboneConfigMixin.verify_out_features_out_indices.<locals>.<lambda>p   s    efghei r   )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   z3BackboneConfigMixin.verify_out_features_out_indicesJ   s3    #QRR)d004': #CDI[I[D\C]!^__OD<N<NOO DTEUEUDVV[\`\n\n[op  4%%&#c$2D2D.E*FF #UVZVhVhUi!jkk!!262B2B a$ddN`N`F` aa !VWcVddijnj|j|i}~  (d//6 #CDIZIZD[C\!]^^$$r`d`q`q$rr^"2^^ HIYIYHZZ`aearar`st  #$C0@,A(BBI$J[J[I\]AQUYUfUfAf)9(:"=lnn o%50@)A#BB&,S1A4CTCT-U[i&j#"AsC# # !UVeUffklpl}l}k~  )d.?.?.K4%%&#d.?.?*@@ !kll!!tGXGX%Yd&6&6s&;%YY !tuu Z /L)7 !b(# &Zs   
L-L-3L2L8c                     | j                   S r'   )r   r!   s    r   r   z BackboneConfigMixin.out_features|   s    !!!r   c                 *    | j                  |d       y)
        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   z BackboneConfigMixin.out_features   s    
 	//\W[/\r   c                     | j                   S r'   )r   r@   s    r   r   zBackboneConfigMixin.out_indices   s       r   .c                 H    |t        |      n|}| j                  d|       y)
        Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
        NrC   )r   r$   r!   r   s     r   r   zBackboneConfigMixin.out_indices   s(    
 ,7+Bd;'//T{/[r   c                 x    t         |          }|j                  dd      |d<   |j                  dd      |d<   |S )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   rK   zBackboneConfigMixin.to_dict   s@    
 "!'OT!B~ &

>4 @}r   )r
   r   r   __doc__r   r$   r   propertyr   setterstrr   r   intrK   __classcell__rN   s   @r   r   r   !   s    "/Tk"/ D["/H0vd " " ]c ] ] ! ! \uS#Xc'B \ \ r   r   c                   4    e Zd ZU dZedz  ed<   dZeed<   d fdZddZ	ddZ
ed        Zej                  d	ee   fd
       Zed        Zej                  dee   ee   z  fd       Zed        Zed        Zd Z	 	 	 ddedz  dedz  dedz  fdZ xZS )BackboneMixinNbackbone_typeThas_attentionsc                    t        |   |i | |j                  dd      }|t        j                  | _        nt        j                  | _        | j
                  t        j                  k(  r| j                  |       y| j
                  t        j                  k(  r| j                          yt        d| j
                   d      )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.)
rJ   __init__rL   r   r   rX   r   _init_timm_backbone_init_transformers_backboner4   )r!   argskwargsr[   rN   s       r   r]   zBackboneMixin.__init__   s    
 	$)&)

?D9$!-!2!2D!-!:!:D!2!22$$m$<<#<#<<,,.~d.@.@-AQRRr   c                 p   t        | j                  dd      }t        | j                  dd      }|j                  j                  D cg c]  }|d   	 c}| _        |j                  j                  D cg c]  }|d   	 c}| _        t        |j                  j                        }|j                  j                         }|||k7  rt        d| d      ||| j                  k7  rt        d| d	      | j                  | j                  _        | j                  j                  ||       yc c}w c c}w )
zj
        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.)getattrconfigfeature_infoinfor   num_featuresr   r   module_namer4   r$   )r!   r\   out_features_from_configstage_names_from_configstager   r   s          r   r^   z!BackboneMixin._init_timm_backbone   s:   
 $+4;;#M ")$++}d"K
 :B9N9N9S9STE(OT;C;P;P;U;UV%U9-V800<<=,,88:#/4LP\4\34L3M Nx x 
 #.3JdN^N^3^23J2K Lq q  #'"2"266|[Q) UVs   D.3D3c                 |    | j                   j                  | _        | j                   j                          d | _        y r'   )rf   r   r   ri   r@   s    r   r_   z)BackboneMixin._init_transformers_backbone   s,    ;;22335 r   c                 .    | j                   j                  S r'   )rf   r   r@   s    r   r   zBackboneMixin.out_features   s    {{(((r   r   c                 &    || j                   _        y)rB   N)rf   r   rD   s     r   r   zBackboneMixin.out_features   s    
 $0 r   c                 .    | j                   j                  S r'   )rf   r   r@   s    r   r   zBackboneMixin.out_indices   s    {{'''r   r   c                 &    || j                   _        y)rG   N)rf   r   rH   s     r   r   zBackboneMixin.out_indices   s    
 #.r   c                 z    t        | j                        D ci c]  \  }}|| j                  |    c}}S c c}}w r'   )	enumerater   ri   )r!   irm   s      r   out_feature_channelsz"BackboneMixin.out_feature_channels   s8     =FdFVFV<WX5t((++XXXs   7c                 Z    | j                   D cg c]  }| j                  |    c}S c c}w r'   )r   rv   )r!   names     r   channelszBackboneMixin.channels   s'    <@<M<MND))$/NNNs   (c                 H   | j                   s|j                  dd        | j                  t        j                  k(  rZt        t        j                  | j                        j                        }|j                         D ci c]  \  }}||v s|| }}} | |i |S c c}}w )Noutput_attentions)rY   rL   rX   r   r   dictinspect	signatureforward
parametersitems)r!   r`   ra   r~   kvs         r   forward_with_filtered_kwargsz*BackboneMixin.forward_with_filtered_kwargs   s    ""JJ*D1!2!22W..t||<GGHI'-||~Htq!iadHFHT$V$$ Is   BBoutput_hidden_statesr{   return_dictc                     t        d      )Nz7This method should be implemented by the derived class.)NotImplementedError)r!   pixel_valuesr   r{   r   s        r   r   zBackboneMixin.forward  s     ""[\\r   )returnN)NNN)r
   r   r   rX   r   __annotations__rY   boolr]   r^   r_   rP   r   rQ   r   rR   r   r   rS   rv   ry   r   r   rT   rU   s   @r   rW   rW      s   )-M<$&-  NDS&RB! ) ) 0c 0 0 ( ( .uSzDI'= . . Y Y
 O O% -1)-#'] #Tk]  $;	]
 D[]r   rW   default_backbonedefault_config_typedefault_config_kwargstimm_default_kwargsc                    ddl m} ddlm} |j	                  dd      }|j	                  di       }	|j                  d      |j	                  d      n|}
|j	                  dd        ||r|
| |	s |d	   dd|
i|} | |fS |
W| Ut        |
      r9|j                  |
      \  }}||d
      }|j                  |	        |di |} | |fS  |d	   dd|
i|	} | |fS | 0|.t        j                  d| d       |xs i } ||   di |} | |fS t        | t              r'| j                  d
      }||   }|j                  |       } | |fS )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   rL   getr   get_config_dictupdateloggerrh   r   r|   	from_dict)backbone_configr   r   r   r   ra   r   r   r   r   r\   config_dictr=   config_classbackbone_model_types                  r   %consolidate_backbone_kwargs_to_configr     s    6+

#6=jj!2B7O)/J)?)Kvzz*%QaH
JJ($/
 	' #9.9c8cObc( F""' 
	/"9x -==hGNK)+l*CDL/*9[9O F"" >n_=cxcSbcO F"" 
	 %8%DUViUjjz{	
 !6 ;=.)<=V@UV F"" 
OT	*-11,?%&9:&00AF""r   c                 |    ddl m} t        | dd      }||j                  |       }|S |j                  |      }|S )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)rf   )r	   r   re   from_config)rf   r   r   r\   s       r   load_backboner   C  sP     *f&7>O++6+: O  ++?+COr   )NNNN)rO   enumr}   huggingface_hubr   utilsr   
get_loggerr
   r   Enumr   r   rW   rR   r|   r   r   r   r   r   <module>r      s    H   '  
		H	%"499 "
z zzp] p]j $(&*)-'+/#Dj/# t/#  $;	/#
 /#dr   