
    rhC                        d Z ddlZddlZddlmZ ddlmZmZmZ erddl	m
Z
  G d dej                        Zd	eee      d
eee      deee      fdZd	eee      d
eeee   ee   f      dee   fdZd	eee      d
eeee   ee   f      dee   deee   ee   f   fdZ G d d      Z G d d      Zd Zdededee   deeedf      dee   f
dZy)zACollection of utils to be used by backbones and their components.    N)Iterable)TYPE_CHECKINGOptionalUnion   )PretrainedConfigc                       e Zd ZdZdZy)BackboneTypetimmtransformersN)__name__
__module____qualname__TIMMTRANSFORMERS     t/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/utils/backbone_utils.pyr
   r
      s    D!Lr   r
   out_featuresout_indicesstage_namesc                 
   t        d      | t        | t        f      st        dt        |              t	        fd| D              rt        d d|        t        |       t        t        |             k7  rt        d|        | D cg c]	  }|| v s| c}x}k7  rt        d| d|        |t        |t              st        d	t        |             t        fd
|D              }t	        fd|D              rt        d d|       t        |      t        t        |            k7  r d| }|||k7  rd| dndz  }t        |      |t        t        |            k7  r;t        t        ||      d       D cg c]  \  }}|	 }	}}t        d|	 d|       | G|Dt        |       t        |      k7  rt        d      | |D cg c]  }|   	 c}k7  rt        d      yyyc c}w c c}}w c c}w )zW
    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   | ]  }|v 
 y wNr   ).0featr   s     r   	<genexpr>z2verify_out_features_out_indices.<locals>.<genexpr>,   s     @4t;&@s   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   H   K   | ]  }|d k  r|t              z  n|  yw)r   N)lenr   idxr   s     r   r   z2verify_out_features_out_indices.<locals>.<genexpr>9   s'      cPS37s;'7!7!K cs   "c              3   P   K   | ]  }|t        t                    vs|  y wr   )ranger   r    s     r   r   z2verify_out_features_out_indices.<locals>.<genexpr>:   s"     Us#U3{CS=T2TsUs   &&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>z1verify_out_features_out_indices.<locals>.<lambda>A   s    jklmjn 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)

ValueError
isinstancelisttypeanyr   settuplesortedzip)
r   r   r   r   sorted_featspositive_indicesmsg_r!   sorted_negatives
     `       r   verify_out_features_out_indicesr7       s_    MNN,0?\@R?STUU@<@@Mk]Z_`l_mnoo|C$5 66QR^Q_`aak,bdTUaMaT,bbLcRS_R``efrest  +t,?[@Q?RSTT  cWb ccU.UUQR]Q^^depdqrss C,<(=$>>Ek]SC=MQ\=\_%5$6b9bddCS/!uV,<%=>>17<Lk8Z`n1opvq#spOpQRaQbbghsgtu  K$;|K 00ghhDK,DDpqq E %<- -c" q Es   	G5G5G:H c                     || t        |      dz
  g}|d   g} | |fS |$| "| D cg c]  }|j                  |       }}| |fS | ||D cg c]  }||   	 } }| |fS c c}w c c}w )a  
    Finds the corresponding `out_features` and `out_indices` for the given `stage_names`.

    The logic is as follows:
        - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the
        `out_indices`.
        - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the
        `out_features`.
        - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.
        - `out_indices` and `out_features` set: input `out_indices` and `out_features` are returned.

    Args:
        out_features (`list[str]`): The names of the features for the backbone to output.
        out_indices (`list[int]` or `tuple[int]`): The indices of the features for the backbone to output.
        stage_names (`list[str]`): The names of the stages of the backbone.
       )r   index)r   r   r   layerr!   s        r   %_align_output_features_output_indicesr=   M   s    * |3;'!+,#B(
 $$	 
	!9=IJE{((/JJ $$ 
	+"94?@SC(@@$$ K@s   AA#returnc                     |t        |      nd}t        | ||       t        | ||      \  }}t        |||       ||fS )a`  
    Get the `out_features` and `out_indices` so that they are aligned.

    The logic is as follows:
        - `out_features` not set, `out_indices` set: `out_features` is set to the `out_features` corresponding to the
        `out_indices`.
        - `out_indices` not set, `out_features` set: `out_indices` is set to the `out_indices` corresponding to the
        `out_features`.
        - `out_indices` and `out_features` not set: `out_indices` and `out_features` are set to the last stage.
        - `out_indices` and `out_features` set: they are verified to be aligned.

    Args:
        out_features (`list[str]`): The names of the features for the backbone to output.
        out_indices (`list[int]` or `tuple[int]`): The indices of the features for the backbone to output.
        stage_names (`list[str]`): The names of the stages of the backbone.
    Nr   r   r   )r+   r7   r=   )r   r   r   output_featuresoutput_indicess        r   *get_aligned_output_features_output_indicesrC   l   sR    * (3'>${#DK#;dop&K!{'#O^ $njuvN**r   c                   0    e Zd ZU dZee   ed<   d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e   f   fd       Ze
d        Ze
d        Zd Z	 	 	 ddee   dee   dee   fdZ fdZ xZS )BackboneMixinNbackbone_typec                    t        | dd      t        d      | j                  j                  j                  D cg c]  }|d   	 c}| _        | j                  j                  j                  D cg c]  }|d   	 c}| _        t        | j                  j                  j                        }| j                  j                  j                         }t        ||| j
                         ||c| _        | _        yc c}w c c}w )zo
        Initialize the backbone model from timm The backbone must already be loaded to self._backbone
        	_backboneNz=self._backbone must be set before calling _init_timm_backbonemodulenum_chsr@   )getattrr)   rH   feature_infoinfor   num_featuresr+   r   module_namer7   _out_features_out_indices)selfconfigstager   r   s        r   _init_timm_backbonez!BackboneMixin._init_timm_backbone   s     4d+3\]]
 :>9T9T9Y9YZE(OZ;?>>;V;V;[;[\%U9-\ 4>>66BBC~~22>>@ 	(%;DL\L\	
 1=k-D- [\s   C:1C?c                     t        |d      }t        |dd       }t        |dd       }|| _        t        |||      \  | _        | _        d | _        y )Nr   r   r   r@   )rK   r   rC   rP   rQ   rN   )rR   rS   r   r   r   s        r   _init_transformers_backbonez)BackboneMixin._init_transformers_backbone   sX    fm4v~t<fmT:&0Z%;K1
-D- !r   c                    || _         t        |dd      | _        | j                  r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.
        use_timm_backboneFzbackbone_type z not supported.N)
rS   rK   rY   r
   r   r   rF   rU   rW   r)   )rR   rS   s     r   _init_backbonezBackboneMixin._init_backbone   s    
 !(1De!L262H2H\..lNgNg!2!22$$V,<#<#<<,,V4~d.@.@-AQRRr   c                     | j                   S r   rP   rR   s    r   r   zBackboneMixin.out_features       !!!r   r   c                 N    t        |d| j                        \  | _        | _        yz
        Set the out_features attribute. This will also update the out_indices attribute to match the new out_features.
        Nr@   rC   r   rP   rQ   rR   r   s     r   r   zBackboneMixin.out_features   '    
 1[%4TEUEU1
-D-r   c                     | j                   S r   rQ   r]   s    r   r   zBackboneMixin.out_indices          r   r   c                 N    t        d|| j                        \  | _        | _        yz
        Set the out_indices attribute. This will also update the out_features attribute to match the new out_indices.
        Nr@   ra   rR   r   s     r   r   zBackboneMixin.out_indices   '    
 1[;DDTDT1
-D-r   c                 z    t        | j                        D ci c]  \  }}|| j                  |    c}}S c c}}w r   )	enumerater   rN   )rR   irT   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   rn   )rR   names     r   channelszBackboneMixin.channels   s'    <@<M<MND))$/NNNs   (c                     t        t        j                  | j                        j                        }|j                         D ci c]  \  }}||v s|| }}} | |i |S c c}}w r   )dictinspect	signatureforward
parametersitems)rR   argskwargsru   kvfiltered_kwargss          r   forward_with_filtered_kwargsz*BackboneMixin.forward_with_filtered_kwargs   s^    **4<<8CCD	,2LLNMDAqa9n1a4MMT-_-- Ns   A#A#output_hidden_statesoutput_attentionsreturn_dictc                     t        d      )Nz7This method should be implemented by the derived class.)NotImplementedError)rR   pixel_valuesr   r   r   s        r   rv   zBackboneMixin.forward   s     ""[\\r   c                 t    t         |          }|j                  d      |d<   |j                  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.
        rP   r   rQ   r   superto_dictpoprR   output	__class__s     r   r   zBackboneMixin.to_dict   <    
 "!'O!<~ &

> :}r   )r>   N)NNN)r   r   r   rF   r   r
   __annotations__rU   rW   rZ   propertyr   setterr+   strr   r   r/   intrn   rq   r~   boolrv   r   __classcell__r   s   @r   rE   rE      s   ,0M8L)0J0
!S" " " 
c 
 
 ! ! 
uU3Zc-B'C 
 
 Y Y
 O O. 04,0&*] 'tn] $D>	]
 d^] r   rE   c                        e Zd ZdZed        Zej                  dee   fd       Zed        Z	e	j                  de
ee   ee   f   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.
    c                     | j                   S r   r\   r]   s    r   r   z BackboneConfigMixin.out_features  r^   r   r   c                 N    t        |d| j                        \  | _        | _        yr`   ra   rb   s     r   r   z BackboneConfigMixin.out_features
  rc   r   c                     | j                   S r   re   r]   s    r   r   zBackboneConfigMixin.out_indices  rf   r   r   c                 N    t        d|| j                        \  | _        | _        yrh   ra   ri   s     r   r   zBackboneConfigMixin.out_indices  rj   r   c                 t    t         |          }|j                  d      |d<   |j                  d      |d<   |S r   r   r   s     r   r   zBackboneConfigMixin.to_dict   r   r   )r   r   r   __doc__r   r   r   r+   r   r   r   r/   r   r   r   r   s   @r   r   r     s     " " 
c 
 
 ! ! 
uU3Zc-B'C 
 
 r   r   c                    ddl m}m} t        | dd      }t        | dd      }t        | dd      }t        | dd      }t        | dd      }|i n|}|r|t	        d	      |||t	        d
      ||| |j
                  dd| i|S |r%|t	        d       |j                  |f||d|}|S |r"|t	        d       |j                  |fi |}|S ||t	        d      | |j                  |fi |}|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   )AutoBackbone
AutoConfigbackbone_configNrY   use_pretrained_backbonebackbonebackbone_kwargs?You can't specify both `backbone_kwargs` and `backbone_config`.z>Cannot specify both config.backbone_config and config.backbonerS   z8config.backbone must be set if use_timm_backbone is True)rY   r   z>config.backbone must be set if use_pretrained_backbone is Truez<Either config.backbone_config or config.backbone must be set)rS   r   )r   r   r   rK   r)   from_configfrom_pretrained)	rS   r   r   r   rY   r   backbone_checkpointr   r   s	            r   load_backboner   +  s    6f&7>O(;TB%f.GN!&*d;f&7>O+3bO?6Z[[ "':'FKbKnYZZ #4#<ATA\'|''IvIII &WXX 0<//
/$;
 	
  O 
!&]^^/<//0CWW O "':'B[\\"8j889L`P_`O++?+COr   rY   r   r   r   r   r   c                 f    ||t        d      || rt        d      ||r|t        d      yyy)zR
    Verify that the config arguments to be passed to load_backbone are valid
    Nz8You can't specify both `backbone` and `backbone_config`.zAYou can't specify both `backbone_config` and `use_timm_backbone`.r   )r)   )rY   r   r   r   r   s        r    verify_backbone_config_argumentsr   c  sT     "x';STT"'8\]]"?;VZ[[ <W"r   )r   enumrt   collections.abcr   typingr   r   r   configuration_utilsr   Enumr
   r   r   r7   r+   r/   r=   rC   rE   r   r   r   rs   r   r   r   r   <module>r      s   H   $ 1 1 6"499 "
*r8C=)*r8@#8O*r^fgopsgt^u*rZ%49%%%S	5: 567% c%>+49%+%S	5: 567+ c+ 49d3i 	+@r rj' 'T5p\\!\ sm\ eD*<$<=>	\
 d^\r   