
    gA                       d Z ddlZddlZddlmZ ddlmZmZmZm	Z	 ddl
ZddlZddlZddlmZ ddlmZmZmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZ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(m)Z)m*Z*m+Z+  e#            rddl,m-Z-  e%j.        e/          Z0dZ1dZ2d Z3	 dRdej4        de5de5de5de5dej4        fdZ6dSd!Z7d" Z8d# Z9e G d$ d%e                       Z:e G d& d'e                       Z;e G d( d)e                       Z< G d* d+ej=                  Z> G d, d-ej=                  Z? G d. d/ej=                  Z@ G d0 d1e@          ZA G d2 d3e@          ZBe@eAeBd4ZC G d5 d6ej=                  ZD G d7 d8ej=                  ZE G d9 d:e          ZFd;ZGd<ZHd=ZId>ZJ G d? d@ej=                  ZK G dA dBej=                  ZL e!dCeG           G dD dEeF                      ZM G dF dGej=                  ZN G dH dIej=                  ZO e!dJeG           G dK dLeF                      ZP e!eG           G dM dNeF                      ZQ e!dOeG           G dP dQeF                      ZRdS )TzPyTorch Siglip model.    N)	dataclass)AnyOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss)_calculate_fan_in_and_fan_out   )ACT2FN)_prepare_4d_attention_mask)BaseModelOutputBaseModelOutputWithPoolingImageClassifierOutput)PreTrainedModel)ModelOutputadd_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings	torch_int   )SiglipConfigSiglipTextConfigSiglipVisionConfig)_flash_attention_forwardr   zgoogle/siglip-base-patch16-224c                    d }||d|z  z
  k     s||d|z  z   k    rt          j        dd            |||z
  |z            } |||z
  |z            }|                     d|z  dz
  d|z  dz
             |                                  |                     |t          j        d          z             |                     |           |                     ||           d S )Nc                 `    dt          j        | t          j        d          z            z   dz  S )N      ?       @)matherfsqrt)xs    f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/siglip/modeling_siglip.pynorm_cdfz _trunc_normal_.<locals>.norm_cdf<   s)    dhq49S>>1222c99       zjmean is more than 2 std from [a, b] in nn.init.trunc_normal_. The distribution of values may be incorrect.)
stacklevelr   r$   )minmax)	warningswarnuniform_erfinv_mul_r%   r'   add_clamp_)tensormeanstdabr*   lus           r)   _trunc_normal_r>   9   s   : : : 	q1s7{q1s7{ 2 2;	
 	
 	
 	
 	!d(c!""A!d(c!""A OOAEAIq1uqy))) NN KKdinn$%%%
KK MMaQMr+           r#          r$   r7   r8   r9   r:   r;   returnc                     t          j                    5  t          | dd||           |                     |                              |           ddd           dS # 1 swxY w Y   dS )an  Fills the input Tensor with values drawn from a truncated
    normal distribution. The values are effectively drawn from the
    normal distribution :math:`\mathcal{N}(	ext{mean}, 	ext{std}^2)`
    with values outside :math:`[a, b]` redrawn until they are within
    the bounds. The method used for generating the random values works
    best when :math:`a \leq 	ext{mean} \leq b`.

    NOTE: this 'tf' variant behaves closer to Tensorflow / JAX impl where the
    bounds [a, b] are applied when sampling the normal distribution with mean=0, std=1.0
    and the result is subsequently scaled and shifted by the mean and std args.

    Args:
        tensor: an n-dimensional `torch.Tensor`
        mean: the mean of the normal distribution
        std: the standard deviation of the normal distribution
        a: the minimum cutoff value
        b: the maximum cutoff value
    r   r#   N)torchno_gradr>   r4   r5   )r7   r8   r9   r:   r;   s        r)   trunc_normal_tf_rE   ]   s    * 
 $ $vq#q!,,,Cd###$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $s   <AA!$A!fan_innormalc                 l   t          |           \  }}|dk    r|}n|dk    r|}n|dk    r||z   dz  }||z  }|dk    r(t          | t          j        |          dz             d S |dk    rVt	          j                    5  |                     t          j        |                     d d d            d S # 1 swxY w Y   d S |d	k    r\t          j        d
|z            }t	          j                    5  |                     | |           d d d            d S # 1 swxY w Y   d S t          d|           )NrF   fan_outfan_avgr,   truncated_normalg۶%?r9   rG   uniformr   zinvalid distribution )	r   rE   r%   r'   rC   rD   normal_r2   
ValueError)	r7   scalemodedistributionrF   rI   denomvariancebounds	            r)   variance_scaling_rV   w   s   3F;;OFGx						'!Q&u}H)))TYx%8%8;N%NOOOOOO		!	!]__ 	4 	4NNty22N333	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4 	4		"	"	!h,'']__ 	+ 	+OOUFE***	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ ???@@@s$   ?)B55B9<B92DDDc                 *    t          | dd           d S )NrF   rK   rQ   rR   rV   r7   s    r)   lecun_normal_r[      s    f8:LMMMMMMr+   c                 *    t          | dd           d S )NrF   rG   rX   rY   rZ   s    r)   default_flax_embed_initr]      s    f8(CCCCCCr+   c                       e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
eeej        df                  ed<   dZeeej        df                  ed<   dS )SiglipVisionModelOutputa  
    Base class for vision model's outputs that also contains image embeddings of the pooling of the last hidden states.

    Args:
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
            The image embeddings obtained by applying the projection layer to the pooler_output.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Nimage_embedslast_hidden_state.hidden_states
attentions)__name__
__module____qualname____doc__r`   r   rC   FloatTensor__annotations__ra   rb   r   rc    r+   r)   r_   r_      s          * 15L(5,-444+/u(///=AM8E%"3S"89:AAA:>Ju0#567>>>>>r+   r_   c                       e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
eeej        df                  ed<   dZeeej        df                  ed<   dS )SiglipTextModelOutputa  
    Base class for text model's outputs that also contains a pooling of the last hidden states.

    Args:
        text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim)` *optional* returned when model is initialized with `with_projection=True`):
            The text embeddings obtained by applying the projection layer to the pooler_output.
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
    Ntext_embedsra   .rb   rc   )rd   re   rf   rg   rm   r   rC   rh   ri   ra   rb   r   rc   rj   r+   r)   rl   rl      s          * 04K%+,333+/u(///=AM8E%"3S"89:AAA:>Ju0#567>>>>>r+   rl   c                       e Zd ZU dZdZeej                 ed<   dZ	ej        ed<   dZ
ej        ed<   dZej        ed<   dZej        ed<   dZeed<   dZeed	<   d
ee         fdZdS )SiglipOutputa  
    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
            Contrastive loss for image-text similarity.
        logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
            The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
            similarity scores.
        logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
            The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
            similarity scores.
        text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The text embeddings obtained by applying the projection layer to the pooled output of [`SiglipTextModel`].
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The image embeddings obtained by applying the projection layer to the pooled output of [`SiglipVisionModel`].
        text_model_output (`BaseModelOutputWithPooling`):
            The output of the [`SiglipTextModel`].
        vision_model_output (`BaseModelOutputWithPooling`):
            The output of the [`SiglipVisionModel`].
    Nlosslogits_per_imagelogits_per_textrm   r`   text_model_outputvision_model_outputrA   c                 ^     t           fd                                 D                       S )Nc              3   t   K   | ]2}|d vr|         n!t          |                                          V  3dS ))rs   rt   N)getattrto_tuple).0kselfs     r)   	<genexpr>z(SiglipOutput.to_tuple.<locals>.<genexpr>   sc       
 
  LLLDGGRYZ^`aRbRbRkRkRmRm
 
 
 
 
 
r+   )tuplekeysr{   s   `r)   rx   zSiglipOutput.to_tuple   sC     
 
 
 
YY[[
 
 
 
 
 	
r+   )rd   re   rf   rg   rp   r   rC   rh   ri   rq   rr   rm   r`   rs   r   rt   r   r   rx   rj   r+   r)   ro   ro      s          ( )-D(5$
%,,,*.e'...)-OU&---%)K")))&*L%#***4818886:3:::
%* 
 
 
 
 
 
r+   ro   c                   v     e Zd Zdef fdZdej        dededej        fdZdd	ej	        dej        fd
Z
 xZS )SiglipVisionEmbeddingsconfigc                    t                                                       || _        |j        | _        |j        | _        |j        | _        t          j        |j	        | j        | j        | j        d          | _
        | j        | j        z  dz  | _        | j        | _        t          j        | j        | j                  | _        |                     dt!          j        | j                                      d          d           d S )Nvalid)in_channelsout_channelskernel_sizestridepaddingr,   position_idsr   F
persistent)super__init__r   hidden_size	embed_dim
image_size
patch_sizer   Conv2dnum_channelspatch_embeddingnum_patchesnum_positions	Embeddingposition_embeddingregister_bufferrC   arangeexpandr{   r   	__class__s     r)   r   zSiglipVisionEmbeddings.__init__   s    + + +!y+? 
  
  
 !Ot>1D!-"$,t/A4>"R"R^U\$:L-M-M-T-TU\-]-]jopppppr+   
embeddingsheightwidthrA   c                 ~   |j         d         }| j        j        j         d         }t          j                                        s&||k    r ||k    r|                     | j                  S | j        j                            d          }|j         d         }|| j        z  }|| j        z  }	t          |dz            }
|
                    d|
|
|          }|                    dddd          }t          j                            |||	fdd	          }|                    dddd                              dd|          }|S )
a  
        This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
        images. This method is also adapted to support torch.jit tracing and no class embeddings.

        Adapted from:
        - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
        - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
        r   r   r   g      ?r   r,   bicubicF)sizerQ   align_corners)shaper   weightrC   jit
is_tracingr   	unsqueezer   r   reshapepermuter   
functionalinterpolateview)r{   r   r   r   r   r   patch_pos_embeddim
new_height	new_widthsqrt_num_positionss              r)   interpolate_pos_encodingz/SiglipVisionEmbeddings.interpolate_pos_encoding  sL    !&q)/6<Q? y##%% 	>+*F*F6UZ??**4+<===18BB1EEr"t.
T_,	&}c'9::)11!5GI[]`aa)11!Q1==-33i(	 4 
 
 *11!Q1==BB1b#NNr+   Fpixel_valuesc                    |j         \  }}}}|                     |          }|                    d                              dd          }|r||                     |||          z   }n||                     | j                  z   }|S )Nr,   r   )r   r   flatten	transposer   r   r   )r{   r   r   _r   r   patch_embedsr   s           r)   forwardzSiglipVisionEmbeddings.forward5  s    *01fe++L99!))!,,66q!<<
# 	Q#d&C&CJPVX]&^&^^JJ#d&=&=d>O&P&PPJr+   F)rd   re   rf   r   r   rC   Tensorintr   rh   r   __classcell__r   s   @r)   r   r      s        q1 q q q q q q($5< $ $UX $]b]i $ $ $ $L	 	E$5 	Z_Zf 	 	 	 	 	 	 	 	r+   r   c            	            e Zd Zdef fdZ	 	 	 d	deej                 deej                 deej                 dej	        fdZ
 xZS )
SiglipTextEmbeddingsr   c                 V   t                                                       |j        }t          j        |j        |          | _        t          j        |j        |          | _        | 	                    dt          j        |j                                      d          d           d S )Nr   r   Fr   )r   r   r   r   r   
vocab_sizetoken_embeddingmax_position_embeddingsr   r   rC   r   r   r{   r   r   r   s      r)   r   zSiglipTextEmbeddings.__init__C  s    &	!|F,=yII"$,v/My"Y"Y 	EL)GHHOOPWXXej 	 	
 	
 	
 	
 	
r+   N	input_idsr   inputs_embedsrA   c                     ||j         d         n|j         d         }|| j        d d d |f         }||                     |          }|                     |          }||z   }|S )Nr   )r   r   r   r   )r{   r   r   r   
seq_lengthposition_embeddingsr   s          r)   r   zSiglipTextEmbeddings.forwardO  s     -6,AY_R((}GZ[]G^
,QQQ^<L  00;;M"55lCC"%88
r+   )NNN)rd   re   rf   r   r   r   rC   
LongTensorrh   r   r   r   r   s   @r)   r   r   B  s        

/ 

 

 

 

 

 

 153759	 E,- u/0   12	
 
       r+   r   c                        e Zd ZdZ fdZ	 	 d
dej        deej                 dee         de	ej        eej                 f         fd	Z
 xZS )SiglipAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                 t   t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        | j        | j        z  | j        k    r t          d| j         d| j         d          | j        dz  | _	        |j
        | _        t          j        | j        | j                  | _        t          j        | j        | j                  | _        t          j        | j        | j                  | _        t          j        | j        | j                  | _        d S )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).      )r   r   r   r   r   num_attention_heads	num_headshead_dimrO   rP   attention_dropoutdropoutr   Lineark_projv_projq_projout_projr   s     r)   r   zSiglipAttention.__init__g  s   +3$.8=4>)T^;;'dn ' 'N' ' '   ]D(
/i??i??i??	$.$.AAr+   NFrb   attention_maskoutput_attentionsrA   c                 (   |                                 \  }}}|                     |          }|                     |          }|                     |          }	|                    ||| j        | j                                      dd          }|                    ||| j        | j                                      dd          }|	                    ||| j        | j                                      dd          }	|j        d         }
t          j
        ||                    dd                    | j        z  }|                                 || j        ||
fk    r0t          d|| j        ||
f d|                                            |L|                                 |d||
fk    r+t          d|d||
f d|                                            ||z   }t          j                            |d	t          j        
                              |j                  }t          j                            || j        | j                  }t          j
        ||	          }|                                 || j        || j        fk    r5t          d|| j        || j        f d|                                            |                    dd                                          }|                    ||| j                  }|                     |          }||fS )z#Input shape: Batch x Time x Channelr   r,   r   r   z$Attention weights should be of size z	, but is Nz!Attention mask should be of size r   )r   dtype)ptrainingz `attn_output` should be of size )r   r   r   r   r   r   r   r   r   rC   matmulrP   rO   r   r   softmaxfloat32tor   r   r   
contiguousr   r   r   )r{   rb   r   r   
batch_sizeq_lenr   query_states
key_statesvalue_statesk_v_seq_lenattn_weightsattn_outputs                r)   r   zSiglipAttention.forwardz  s     -1133
E1{{=11[[//
{{=11#((UDNDMZZddefhijj__ZVV``abdeff
#((UDNDMZZddefhijj &r*|L*2F2Fq!2L2LMMPTPZZ:t~uk"RRR*
DNTY[f7g * * %%''* *  
 %""$$Q{(KKK }Q{8[}}ftfyfyf{f{}}   (.8L },,\r,WWZZ[g[mnn},,\T\TXTa,bbl<>>*dneT]!SSS)JPUW[Wd3e ) )$$&&) )  
 "++Aq11<<>>!))*eT^LLmmK00L((r+   NF)rd   re   rf   rg   r   rC   r   r   boolr   r   r   r   s   @r)   r   r   c  s        GGB B B B B, 26,1	2) 2)|2) !.2) $D>	2)
 
u|Xel33	42) 2) 2) 2) 2) 2) 2) 2)r+   r   c                        e Zd ZdZdZ fdZ	 	 d
dej        deej	                 de
deej        eej                 eeej                          f         fd	Z xZS )SiglipFlashAttention2aQ  
    SiglipAttention flash attention module. This module inherits from `SiglipAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    Fc                 b     t                      j        |i | t                       | _        d S N)r   r   r   _flash_attn_uses_top_left_mask)r{   argskwargsr   s      r)   r   zSiglipFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r+   Nrb   r   r   rA   c           
         d}|                                 \  }}}|                     |          }|                     |          }|                     |          }	|                    ||| j        | j                                      dd          }|                    ||| j        | j                                      dd          }|	                    ||| j        | j                                      dd          }	|                    dd          }|                    dd          }|	                    dd          }	| j        r| j	        nd}
|j
        }|t          j        k    rt          j                    rt          j                    }n3t          | j        d          r| j        j        }n| j        j        j
        }t&                              d| d           |                    |          }|                    |          }|	                    |          }	t-          |||	|||
| j        | j                  }|                    ||| j                                                  }|                     |          }|sd }||fS )	NFr   r,   r?   _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .)r   	is_causaluse_top_left_mask)r   r   r   r   r   r   r   r   r   r   r   rC   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r   r   loggerwarning_oncer   r    r   r   r   r   r   r   )r{   rb   r   r   r   r   r   r   r   r   dropout_rateinput_dtypetarget_dtyper   r   s                  r)   r   zSiglipFlashAttention2.forward  s    ",1133
E1{{=11[[//
{{=11
 $((UDNDMZZddefhijj__ZVV``abdeff
#((UDNDMZZddefhijj $--a33))!Q//
#--a33'+}=t||# #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L. n"A	
 	
 	
 "))*eT^LLWWYYmmK00  	 LL((r+   r   )rd   re   rf   rg   r   r   rC   r   r   r   r   r   r   r   r   s   @r)   r   r     s          IX X X X X 6:"'	H) H)|H) !!12H)  	H)
 
u|Xel3XeEL>Q5RR	SH) H) H) H) H) H) H) H)r+   r   c                        e Zd ZdZdZ	 	 d	dej        deej                 dee         de	ej        eej                 f         f fdZ
 xZS )
SiglipSdpaAttentionz
    Siglip attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `SiglipAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    FNrb   r   r   rA   c                 ^   |r>t                               d           t                                          |||          S |                                \  }}}|                     |          }|                     |          }|                     |          }	|                    ||| j	        | j
                                      dd          }|                    ||| j	        | j
                                      dd          }|	                    ||| j	        | j
                                      dd          }	|j        j        dk    r>|<|                                }|                                }|	                                }	| j        r|dk    rdnd}
t           j        j                            |||	|| j        r| j        nd|
	          }|                    dd                                          }|                    ||| j                  }|                     |          }|d fS )
Na  SiglipModel is using SiglipSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.rb   r   r   r   r,   cudaTFr?   )	attn_mask	dropout_pr   )r  r  r   r   r   r   r   r   r   r   r   r   devicetyper   r   rC   r   r   scaled_dot_product_attentionr   r   r   r   )r{   rb   r   r   r   r   r   r   r   r   r   r   r   s               r)   r   zSiglipSdpaAttention.forward  s)     
	[   77??+-"3 #     -1133
E1{{=11[[//
{{=11#((UDNDMZZddefhijj__ZVV``abdeff
#((UDNDMZZddefhijj #v--.2L'2244L#..00J'2244L !NCuqyyDDe	h)FF$&*m<dll G 
 
 "++Aq11<<>>!&&z5$.IImmK00D  r+   r   )rd   re   rf   rg   r   rC   r   r   r   r   r   r   r   s   @r)   r
  r
    s          I 26,1	5! 5!|5! !.5! $D>	5!
 
u|Xel33	45! 5! 5! 5! 5! 5! 5! 5! 5! 5!r+   r
  )eagerflash_attention_2sdpac                   B     e Zd Z fdZdej        dej        fdZ xZS )	SiglipMLPc                    t                                                       || _        t          |j                 | _        t          j        |j        |j	                  | _
        t          j        |j	        |j                  | _        d S r   )r   r   r   r   
hidden_actactivation_fnr   r   r   intermediate_sizefc1fc2r   s     r)   r   zSiglipMLP.__init__X  sf    #F$569V/1IJJ9V5v7IJJr+   rb   rA   c                     |                      |          }|                     |          }|                     |          }|S r   )r  r  r  )r{   rb   s     r)   r   zSiglipMLP.forward_  s=    //**=99//r+   )rd   re   rf   r   rC   r   r   r   r   s   @r)   r  r  W  sc        K K K K KU\ el        r+   r  c            
       v     e Zd Zdef fdZ	 d	dej        dej        dee         de	ej
                 fdZ xZS )
SiglipEncoderLayerr   c                 \   t                                                       |j        | _        t	          |j                 |          | _        t          j        | j        |j	                  | _
        t          |          | _        t          j        | j        |j	                  | _        d S )N)r   eps)r   r   r   r   SIGLIP_ATTENTION_CLASSES_attn_implementation	self_attnr   	LayerNormlayer_norm_epslayer_norm1r  mlplayer_norm2r   s     r)   r   zSiglipEncoderLayer.__init__g  s    +1&2MNV\]]]<F<QRRRV$$<F<QRRRr+   Frb   r   r   rA   c                     |}|                      |          }|                     |||          \  }}||z   }|}|                     |          }|                     |          }||z   }|f}|r||fz  }|S )a=  
        Args:
            hidden_states (`torch.FloatTensor`):
                Input to the layer of shape `(batch, seq_len, embed_dim)`.
            attention_mask (`torch.FloatTensor`):
                Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*, defaults to `False`):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        r  )r)  r&  r+  r*  )r{   rb   r   r   residualr   outputss          r)   r   zSiglipEncoderLayer.forwardp  s      !((77&*nn')/ '5 '
 '
#|
 !=0 ((77// =0 " 	'&Gr+   r   )rd   re   rf   r   r   rC   r   r   r   r   rh   r   r   r   s   @r)   r   r   f  s        S| S S S S S S -2	$ $|$ $ $D>	$
 
u 	!$ $ $ $ $ $ $ $r+   r   c                   4    e Zd ZdZeZdZdZg dZdZ	dZ
d ZdS )SiglipPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    siglipT)r   r   r   r   #SiglipMultiheadAttentionPoolingHeadc                 2
   t          |t                    ryt          | j        t                    r| j        j        j        n| j        j        }t          j                            |j	        j
        dt          j        |          z             dS t          |t          j                  rt          |j
                   dS t          |t                    rJt          j                            |j        j
                   t          j                            |j        j
                   t          j                            |j        j
                   t          j                            |j        j
                   t          j                            |j        j                   t          j                            |j        j                   t          j                            |j        j                   t          j                            |j        j                   dS t          |t.                    rt          j                            |j        j
                   t          j                            |j        j
                   t          j                            |j        j        d           t          j                            |j        j        d           dS t          |t4                    rt          j                            |j        j                   t          j                            |j        j        j                   t          j                            |j        j        j                   dS t          |t@                    retC          j"        tC          j#        d                    }|j$        j        %                    |           |j&        j        '                                 dS t          |tP                    rLt          j                            |j)        j
        | j        j        j        dz  | j        j*        z             dS t          |t          j+        t          j,        f          rCt[          |j
                   |j        &t          j                            |j                   dS dS t          |t          j.                  r?|j        j        '                                 |j
        j        %                    d           dS dS )zInitialize the weightsr   rL   gư>r#   r   N)/
isinstancer   r   r   vision_configr   r   initrN   r   r   npr'   r   r]   r   xavier_uniform_r   r   r   r   zeros_biasr  r  r  r2  probedata	attentionin_proj_weightin_proj_biasSiglipModelrC   logr7   logit_scalefill_
logit_biaszero_SiglipForImageClassification
classifierinitializer_factorr   r   r[   r'  )r{   moduler   logit_scale_inits       r)   _init_weightsz#SiglipPreTrainedModel._init_weights  s   f455 *	* dk<88-)55[, 
 GOOF5<!bgennBTOUUUUU-- #	*#FM2222200 !	*G##FM$8999G##FM$8999G##FM$8999G##FO$:;;;GNN6=-...GNN6=-...GNN6=-...GNN6?/00000	** 	*G##FJ$5666G##FJ$5666GOOFJOO666GOOFJOO66666 CDD 	*G##FL$5666G##F$4$C$HIIIGNN6+8=>>>>>,, 	*$yc):):;;#))*:;;;"((***** <== 	*GOO!(K-94?$+B``       BI 677 	*&-((({&v{+++++ '&-- 	*K""$$$M$$S)))))	* 	*r+   N)rd   re   rf   rg   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_supports_flash_attn_2_supports_sdparK  rj   r+   r)   r0  r0    s_         
  L &*#   "N,* ,* ,* ,* ,*r+   r0  a?  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)

    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.

    Parameters:
        config ([`SiglipConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
            Whether to interpolate the pre-trained position encodings.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.max_position_embeddings - 1]`.

            [What are position IDs?](../glossary#position-ids)
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
            [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
        return_loss (`bool`, *optional*):
            Whether or not to return the contrastive loss.
        output_attentions (`bool`, *optional*):
            Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
            tensors for more detail.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        interpolate_pos_encoding (`bool`, *optional*, defaults to `False`):
            Whether to interpolate the pre-trained position encodings.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                        e Zd ZdZdef fdZ	 	 	 	 ddeej                 dee	         dee	         dee	         d	e
eef         f
d
Z xZS )SiglipEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`SiglipEncoderLayer`].

    Args:
        config: SiglipConfig
    r   c                     t                                                       | _        t          j        fdt          j                  D                       | _        d| _        d S )Nc                 .    g | ]}t                    S rj   )r   )ry   r   r   s     r)   
<listcomp>z*SiglipEncoder.__init__.<locals>.<listcomp>O  s"    $i$i$iA%7%?%?$i$i$ir+   F)	r   r   r   r   
ModuleListrangenum_hidden_layerslayersgradient_checkpointingr   s    `r)   r   zSiglipEncoder.__init__L  s`    m$i$i$i$ivOgIhIh$i$i$ijj&+###r+   Nr   r   output_hidden_statesreturn_dictrA   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|rdnd}|rdnd}|}| j        D ]Z}	|r||fz   }| j        r%| j        r|                     |	j        |||          }
n |	|||          }
|
d         }|r||
d         fz   }[|r||fz   }|st          d |||fD                       S t          |||          S )ad  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
                This is useful if you want more control over how to convert `input_ids` indices into associated vectors
                than the model's internal embedding lookup matrix.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        Nrj   )r   r   r   c              3      K   | ]}||V  	d S r   rj   )ry   vs     r)   r|   z(SiglipEncoder.forward.<locals>.<genexpr>  s(      eeqWXWdWdWdWdWdeer+   )ra   rb   rc   )r   r   r\  use_return_dictrZ  r[  r   _gradient_checkpointing_func__call__r}   r   )r{   r   r   r   r\  r]  encoder_statesall_attentionsrb   encoder_layerlayer_outputss              r)   r   zSiglipEncoder.forwardS  sx   < 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]3=0:d%![ 	F 	FM# C!/=2B!B* t}  $ A A!*!"%	! ! !.!"&7! ! ! *!,M  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r+   )NNNN)rd   re   rf   rg   r   r   r   rC   r   r   r   r   r   r   r   r   s   @r)   rS  rS  C  s         ,| , , , , , , 26,0/3&*E
 E
 !.E
 $D>	E

 'tnE
 d^E
 
uo%	&E
 E
 E
 E
 E
 E
 E
 E
r+   rS  c                       e Zd Zdef fdZ ee           eee          	 	 	 	 	 	 dde	e
j                 de	e
j                 de	e
j                 de	e         d	e	e         d
e	e         deeef         fd                        Z xZS )SiglipTextTransformerr   c                 H   t                                                       || _        |j        }t	          |          | _        t          |          | _        t          j	        ||j
                  | _        t          j        ||          | _        |j        dk    | _        d S )Nr"  r  )r   r   r   r   r   r   rS  encoderr   r'  r(  final_layer_normr   headr%  _use_flash_attention_2r   s      r)   r   zSiglipTextTransformer.__init__  s    &	.v66$V,, "YF<Q R R RIi33	&,&AEX&X###r+   output_typerL  Nr   r   r   r   r\  r]  rA   c                 `   ||n| j         j        }||n| j         j        }||n| j         j        }|t	          d          |                                }|                    d|d                   }|                     ||          }|| j        st          ||j
                  }|                     |||||          }	|	d         }
|                     |
          }
|
dddddf         }|                     |          }|s|
|f|	dd         z   S t          |
||	j        |	j                  S )	
        Returns:

        NzYou have to specify input_idsr   )r   r   )r   r   r   r\  r]  r   r   ra   pooler_outputrb   rc   )r   r   r\  ra  rO   r   r   r   rn  r   r   rk  rl  rm  r   rb   rc   )r{   r   r   r   r   r\  r]  input_shaperb   encoder_outputsra   pooled_outputs               r)   r   zSiglipTextTransformer.forward  s{    2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]<===nn&&NN2{277	),WW %d.I%7H[\\N,,')/!5# ' 
 
 ,A. 112CDD *!!!R(3		-00 	L%}58KKK)/')7&1	
 
 
 	
r+   NNNNNN)rd   re   rf   r   r   r   SIGLIP_TEXT_INPUTS_DOCSTRINGr   r   r   rC   r   r   r   r   r   r   r   s   @r)   ri  ri    s!       	Y/ 	Y 	Y 	Y 	Y 	Y 	Y +*+GHH+ETdeee -115/3,0/3&*8
 8
EL)8
 !.8
 u|,	8

 $D>8
 'tn8
 d^8
 
u00	18
 8
 8
 fe IH8
 8
 8
 8
 8
r+   ri  zAThe text model from SigLIP without any head or projection on top.c                   4    e Zd ZeZdef fdZdej        fdZd Z	 e
e           eee          	 	 	 	 	 	 ddeej                 d	eej                 d
eej                 dee         dee         dee         deeef         fd                        Z xZS )SiglipTextModelr   c                     t                                          |           t          |          | _        |                                  d S r   )r   r   ri  
text_model	post_initr   s     r)   r   zSiglipTextModel.__init__  s@       /77r+   rA   c                 $    | j         j        j        S r   r}  r   r   r   s    r)   get_input_embeddingsz$SiglipTextModel.get_input_embeddings  s    )99r+   c                 (    || j         j        _        d S r   r  )r{   values     r)   set_input_embeddingsz$SiglipTextModel.set_input_embeddings  s    5:"222r+   ro  Nr   r   r   r   r\  r]  c                 X    ||n| j         j        }|                     ||||||          S )a  
        Returns:

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, SiglipTextModel

        >>> model = SiglipTextModel.from_pretrained("google/siglip-base-patch16-224")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")

        >>> # important: make sure to set padding="max_length" as that's how the model was trained
        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled (EOS token) states
        ```Nr   r   r   r   r\  r]  )r   ra  r}  )r{   r   r   r   r   r\  r]  s          r)   r   zSiglipTextModel.forward  sD    : &1%<kk$+B])%/!5#  
 
 	
r+   rx  )rd   re   rf   r   rL  r   r   Moduler  r  r   ry  r   r   r   rC   r   r   r   r   r   r   r   s   @r)   r{  r{    sM       
 $L/      :bi : : : :; ; ; +*+GHH+ETdeee -115/3,0/3&*$
 $
EL)$
 !.$
 u|,	$

 $D>$
 'tn$
 d^$
 
u00	1$
 $
 $
 fe IH$
 $
 $
 $
 $
r+   r{  c                        e Zd Zdef fdZ ee           eee          	 	 	 	 dde	e
         de	e
         de	e
         d	e	e
         d
eeef         f
d                        Z xZS )SiglipVisionTransformerr   c                 j   t                                                       || _        |j        }t	          |          | _        t          |          | _        t          j	        ||j
                  | _        t          |d          sdn|j        | _        | j        rt          |          | _        d S d S )Nr"  vision_use_headT)r   r   r   r   r   r   rS  rk  r   r'  r(  post_layernormr  r  use_headr2  rm  r   s      r)   r   z SiglipVisionTransformer.__init__!  s    &	088$V,, l9&:OPPP$+F4E$F$FbFLb= 	D;FCCDIII	D 	Dr+   ro  NFr   r\  r]  r   rA   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|                     ||          }|                     ||||          }|d         }|                     |          }| j        r|                     |          nd}	|s||	f|dd         z   S t          ||	|j
        |j                  S )rr  N)r   )r   r   r\  r]  r   r   rs  )r   r   r\  ra  r   rk  r  r  rm  r   rb   rc   )
r{   r   r   r\  r]  r   rb   rv  ra   rt  s
             r)   r   zSiglipVisionTransformer.forward-  s    2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]Oghh,,'/!5#	 ' 
 
 ,A. //0ABB8<O		"34444 	L%}58KKK)/')7&1	
 
 
 	
r+   NNNF)rd   re   rf   r   r   r   SIGLIP_VISION_INPUTS_DOCSTRINGr   r   r   r   r   r   r   r   r   s   @r)   r  r     s        
D1 
D 
D 
D 
D 
D 
D +*+IJJ+ETfggg -1/3&*38'
 '
 $D>'
 'tn	'

 d^'
 #+4.'
 
u00	1'
 '
 '
 hg KJ'
 '
 '
 '
 '
r+   r  c                   .     e Zd ZdZdef fdZd Z xZS )r2  zMultihead Attention Pooling.r   c                    t                                                       t          j        t	          j        dd|j                            | _        t          j                            |j        |j	        d          | _
        t          j        |j        |j                  | _        t          |          | _        d S )Nr   T)batch_firstr"  )r   r   r   	ParameterrC   randnr   r;  MultiheadAttentionr   r=  r'  r(  	layernormr  r*  r   s     r)   r   z,SiglipMultiheadAttentionPoolingHead.__init__\  s    \%+aF4F"G"GHH
44V5GIcqu4vvf&8f>STTTV$$r+   c                    |j         d         }| j                            |dd          }|                     |||          d         }|}|                     |          }||                     |          z   }|d d df         S )Nr   r   )r   r;  repeatr=  r  r*  )r{   hidden_stater   r;  r-  s        r)   r   z+SiglipMultiheadAttentionPoolingHead.forwardd  s    !'*

!!*a33~~e\<HHK~~l33$((<"8"88AAAqD!!r+   )rd   re   rf   rg   r   r   r   r   r   s   @r)   r2  r2  Y  sZ        &&%1 % % % % % %
" 
" 
" 
" 
" 
" 
"r+   r2  zCThe vision model from SigLIP without any head or projection on top.c                        e Zd ZeZdZdef fdZdej        fdZ	 e
e           eee          	 	 	 	 dd	ee         d
ee         dee         dedeeef         f
d                        Z xZS )SiglipVisionModelr   r   c                     t                                          |           t          |          | _        |                                  d S r   )r   r   r  vision_modelr~  r   s     r)   r   zSiglipVisionModel.__init__y  sC       3F;; 	r+   rA   c                 $    | j         j        j        S r   )r  r   r   r   s    r)   r  z&SiglipVisionModel.get_input_embeddings  s     +;;r+   ro  NFr   r\  r]  r   c                 V    ||n| j         j        }|                     |||||          S )a  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, SiglipVisionModel

        >>> model = SiglipVisionModel.from_pretrained("google/siglip-base-patch16-224")
        >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled features
        ```Nr   r   r\  r]  r   )r   ra  r  )r{   r   r   r\  r]  r   s         r)   r   zSiglipVisionModel.forward  sD    @ &1%<kk$+B]  %/!5#%= ! 
 
 	
r+   r  )rd   re   rf   r   rL  main_input_namer   r   r  r  r   r  r   r   r   r   r   r   r   r   r   s   @r)   r  r  q  s       
 &L$O1      <bi < < < < +*+IJJ+ETfggg -1/3&*).&
 &
 $D>&
 'tn	&

 d^&
 #'&
 
u00	1&
 &
 &
 hg KJ&
 &
 &
 &
 &
r+   r  c                       e Zd ZeZdef fdZ ee          	 	 	 	 	 	 ddee	j
                 dee	j
                 dee	j
                 dee         dee         d	ee         d
e	j        fd            Z ee          	 	 	 	 	 ddee	j                 dee         dee         d	ee         ded
e	j        fd            Z ee           eee          	 	 	 	 	 	 	 	 	 ddee	j                 dee	j                 dee	j
                 dee	j                 dee         dee         dee         d	ee         ded
eeef         fd                        Z xZS )r@  r   c                    t                                          |           t          |j        t                    s%t          dt          |j                   d          t          |j        t                    s%t          dt          |j                   d          |j        }|j        }t          
                    |          }t          
                    |          }|j        | _        |j        | _        t          j        t!          j        d                    | _        t          j        t!          j        d                    | _        |                                  d S )NzMconfig.text_config is expected to be of type SiglipTextConfig but is of type r   zQconfig.vision_config is expected to be of type SiglipVisionConfig but is of type r   )r   r   r4  text_configr   	TypeErrorr  r5  r   r{  _from_configr  r}  r  r   r  rC   r  rB  rD  r~  )r{   r   r  r5  r}  r  r   s         r)   r   zSiglipModel.__init__  sM      &,.>?? 	0+,,0 0 0  
 &.0BCC 	2-..2 2 2  
 (, %11+>>
(55mDD %/(5<A77,u{1~~66 	r+   Nr   r   r   r   r\  r]  rA   c                     ||n| j         j        }||n| j         j        }||n| j         j        }|                     ||||||          }|d         }|S )aJ  
        Returns:
            text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
            applying the projection layer to the pooled output of [`SiglipTextModel`].

        Examples:

        ```python
        >>> from transformers import AutoTokenizer, AutoModel
        >>> import torch

        >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
        >>> tokenizer = AutoTokenizer.from_pretrained("google/siglip-base-patch16-224")

        >>> # important: make sure to set padding="max_length" as that's how the model was trained
        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding="max_length", return_tensors="pt")
        >>> with torch.no_grad():
        ...     text_features = model.get_text_features(**inputs)
        ```Nr  r   )r   r   r\  ra  r}  )	r{   r   r   r   r   r\  r]  text_outputsrw  s	            r)   get_text_featureszSiglipModel.get_text_features  s    < 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B])%/!5# ' 
 
 %Qr+   Fr   r   c                     ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||          }|d         }|S )a  
        Returns:
            image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
            applying the projection layer to the pooled output of [`SiglipVisionModel`].

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, AutoModel
        >>> import torch

        >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
        >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> inputs = processor(images=image, return_tensors="pt")

        >>> with torch.no_grad():
        ...     image_features = model.get_image_features(**inputs)
        ```Nr  r   )r   r   r\  ra  r  )r{   r   r   r\  r]  r   vision_outputsrw  s           r)   get_image_featureszSiglipModel.get_image_features  s    D 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]**%/!5#%= + 
 
 'q)r+   ro  return_lossc
           	         ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||	          }
|                     ||||||          }|
d         }|d         }||                    ddd          z  }||                    ddd          z  }t          j        ||	                                
                    |j                            | j                                        z  | j        z   }|	                                }d}|rt          j        |                    d	          |j        
          }t          j        |           d|z  z   }t          j        j                            ||z            }t          j        |d           }|                                }|s||||||
f}||f|z   n|S t/          |||||||
          S )a_  
        Returns:

        Examples:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, AutoModel
        >>> import torch

        >>> model = AutoModel.from_pretrained("google/siglip-base-patch16-224")
        >>> processor = AutoProcessor.from_pretrained("google/siglip-base-patch16-224")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> texts = ["a photo of 2 cats", "a photo of 2 dogs"]
        >>> # important: we pass `padding=max_length` since the model was trained with this
        >>> inputs = processor(text=texts, images=image, padding="max_length", return_tensors="pt")

        >>> with torch.no_grad():
        ...     outputs = model(**inputs)

        >>> logits_per_image = outputs.logits_per_image
        >>> probs = torch.sigmoid(logits_per_image) # these are the probabilities
        >>> print(f"{probs[0][0]:.1%} that image 0 is '{texts[0]}'")
        31.9% that image 0 is 'a photo of 2 cats'
        ```Nr  r  r   r,   r   T)r   r   keepdimr   )r  r   )rp   rq   rr   rm   r`   rs   rt   )r   r   r\  ra  r  r}  normrC   r   tr   r  rB  exprD  eyer   	ones_liker   r   
logsigmoidsumr8   ro   )r{   r   r   r   r   r  r   r\  r]  r   r  r  r`   rm   rr   rq   rp   r  m1_diag1logliknlloutputs                         r)   r   zSiglipModel.forward8  sG   X 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]**%/!5#%= + 
 
 )%/!5# ' 
 
 &a("1o $l&7&7!T&7&R&RR!K$4$4qb$$4$O$OO Llnn&6&6&9&9+:L&M&MNNQUQaQeQeQgQggo 	 +,,.. 	)O0033O<RSSSC8881s7BHX(33H4NOOF9V,,,,C88::D 	F&lT`bpqF)-)9TGf$$vE-+#%* .
 
 
 	
r+   rx  )NNNNF)	NNNNNNNNF)rd   re   rf   r   rL  r   r   ry  r   rC   r   r   rh   r  r  r  SIGLIP_INPUTS_DOCSTRINGr   ro   r   r   r   r   r   r   s   @r)   r@  r@    s       L|      @ +*+GHH -115/3,0/3&*. .EL). !.. u|,	.
 $D>. 'tn. d^. 
	. . . IH.` +*+IJJ 59,0/3&*).1 1u011 $D>1 'tn	1
 d^1 #'1 
	1 1 1 KJ1f +*+BCC<lSSS 15481537&*,0/3&*).d
 d
E,-d
 u01d
 !.	d

 u/0d
 d^d
 $D>d
 'tnd
 d^d
 #'d
 
ul"	#d
 d
 d
 TS DCd
 d
 d
 d
 d
r+   r@  z
    SigLIP vision encoder with an image classification head on top (a linear layer on top of the pooled final hidden states of
    the patch tokens) e.g. for ImageNet.
    c                       e Zd ZdZdeddf fdZ ee           ee	e
          	 	 	 	 	 	 ddeej                 deej                 d	ee         d
ee         dee         dedeee	f         fd                        Z xZS )rF  r   r   rA   Nc                 n   t                                          |           |j        | _        t                              |j                  }|j        | _        |j        dk    r$t          j        |j        j	        |j                  nt          j
                    | _        |                                  d S )Nr   )r   r   
num_labelsr  r  r5  r  r   r   r   IdentityrG  r~  )r{   r   r  r   s      r)   r   z%SiglipForImageClassification.__init__  s        + )55f6JKK(5 OUN_bcNcNcBIf*68IJJJikitiviv 	
 	r+   ro  Flabelsr   r\  r]  r   c                 \   ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||          }|d         }t          j        |d          }|                     |          }	d}
|t|                    |	j	                  }| j         j
        f| j        dk    rd| j         _
        nN| j        dk    r7|j        t
          j        k    s|j        t
          j        k    rd| j         _
        nd| j         _
        | j         j
        dk    rWt                      }| j        dk    r1 ||	                                |                                          }
n ||	|          }
n| j         j
        dk    rGt#                      } ||	                    d	| j                  |                    d	                    }
n*| j         j
        dk    rt'                      } ||	|          }
|s|	f|d
d         z   }|
|
f|z   n|S t)          |
|	|j        |j                  S )a6  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).

        Returns:

        Examples:

        ```python
        >>> from transformers import AutoImageProcessor, SiglipForImageClassification
        >>> import torch
        >>> from PIL import Image
        >>> import requests

        >>> torch.manual_seed(3)  # doctest: +IGNORE_RESULT
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

        >>> # note: we are loading a `SiglipModel` from the hub here,
        >>> # so the head will be randomly initialized, hence the predictions will be random if seed is not set above.
        >>> image_processor = AutoImageProcessor.from_pretrained("google/siglip-base-patch16-224")
        >>> model = SiglipForImageClassification.from_pretrained("google/siglip-base-patch16-224")

        >>> inputs = image_processor(images=image, return_tensors="pt")
        >>> outputs = model(**inputs)
        >>> logits = outputs.logits
        >>> # model predicts one of the two classes
        >>> predicted_class_idx = logits.argmax(-1).item()
        >>> print("Predicted class:", model.config.id2label[predicted_class_idx])
        Predicted class: LABEL_1
        ```N)r   r\  r]  r   r   r   r  
regressionsingle_label_classificationmulti_label_classificationr   r,   )rp   logitsrb   rc   )r   r   r\  ra  r  rC   r8   rG  r   r  problem_typer  r   longr   r   squeezer
   r   r	   r   rb   rc   )r{   r   r  r   r\  r]  r   r.  sequence_outputr  rp   loss_fctr  s                r)   r   z$SiglipForImageClassification.forward  s^   X 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]##/!5#%= $ 
 
 "!*  *_!<<<11YYv}--F{'/?a''/;DK,,_q((flej.H.HFL\a\eLeLe/LDK,,/KDK,{'<77"99?a''#8FNN$4$4fnn6F6FGGDD#8FF33DD)-JJJ+--xB @ @&++b//RR)-III,..x// 	FY,F)-)9TGf$$vE$!/)	
 
 
 	
r+   )NNNNNF)rd   re   rf   r  r   r   r   r  r   r   _CONFIG_FOR_DOCr   rC   r   r   r   r}   r   r   r   s   @r)   rF  rF    s/        %O|       $ +*+BCC+@___ 04)-,0/3&*).a
 a
u|,a
 &a
 $D>	a

 'tna
 d^a
 #'a
 
u++	,a
 a
 a
 `_ DCa
 a
 a
 a
 a
r+   rF  )r?   r#   r@   r$   )r#   rF   rG   )Srg   r%   r0   dataclassesr   typingr   r   r   r   numpyr7  rC   torch.utils.checkpointr   torch.nnr	   r
   r   torch.nn.initr   activationsr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_utilsr   utilsr   r   r   r   r   r   r   r   configuration_siglipr   r   r   modeling_flash_attention_utilsr    
get_loggerrd   r  r  _CHECKPOINT_FOR_DOCr>   r   floatrE   rV   r[   r]   r_   rl   ro   r  r   r   r   r   r
  r$  r  r   r0  SIGLIP_START_DOCSTRINGry  r  r  rS  ri  r{  r  r2  r  r@  rF  rj   r+   r)   <module>r     s       ! ! ! ! ! ! . . . . . . . . . . . .                A A A A A A A A A A 7 7 7 7 7 7 ! ! ! ! ! ! B B B B B B b b b b b b b b b b - - - - - -	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 U T T T T T T T T T  KJJJJJJ 
	H	%	% !6 !  !  ! J \_$ $L$ %$27$BG$SX$
\$ $ $ $4A A A A2N N ND D D ? ? ? ? ?k ? ? ?8 ? ? ? ? ?K ? ? ?8 !
 !
 !
 !
 !
; !
 !
 !
HD D D D DRY D D DP    29   BI) I) I) I) I)bi I) I) I)X[) [) [) [) [)O [) [) [)|?! ?! ?! ?! ?!/ ?! ?! ?!F .      	   . . . . . . . .b@* @* @* @* @*O @* @* @*F   @" "% RU
 U
 U
 U
 U
BI U
 U
 U
pF
 F
 F
 F
 F
BI F
 F
 F
R K 5
 5
 5
 5
 5
+ 5
 5
	 5
p6
 6
 6
 6
 6
bi 6
 6
 6
r" " " " "") " " "0 M 7
 7
 7
 7
 7
- 7
 7
	 7
t ,--n
 n
 n
 n
 n
' n
 n
 .-n
b   x
 x
 x
 x
 x
#8 x
 x
 x
 x
 x
r+   