
    g                     D   d 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m
Z
 ddlmZmZmZ ddlmZ dd	lmZ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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-          Z.dZ/dZ0dZ1dZ2dej3        dej3        fdZ4dej3        dej3        fdZ5dej3        dej3        fdZ6e G d de                      Z7e G d de                      Z8e G d d e                      Z9 G d! d"e
j:                  Z; G d# d$e
j:                  Z< G d% d&e
j:                  Z= G d' d(e=          Z> G d) d*e=          Z?e=e?e>d+Z@ G d, d-e
j:                  ZA G d. d/e
j:                  ZB G d0 d1e          ZCd2ZDd3ZEd4ZFd5ZG G d6 d7e
j:                  ZH G d8 d9e
j:                  ZI ed:eD           G d; d<eC                      ZJ G d= d>e
j:                  ZK ed?eD           G d@ dAeC                      ZL eeD           G dB dCeC                      ZM edDeD           G dE dFeC                      ZN edGeD           G dH dIeC                      ZO edJeD           G dK dLeC                      ZPdS )MzPyTorch CLIP model.    )	dataclass)AnyOptionalTupleUnionN)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN) _create_4d_causal_attention_mask_prepare_4d_attention_mask)BaseModelOutputBaseModelOutputWithPoolingImageClassifierOutput)PreTrainedModel)"is_torch_greater_or_equal_than_2_2)	ModelOutputadd_code_sample_docstrings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   )
CLIPConfigCLIPTextConfigCLIPVisionConfig)_flash_attention_forwardr   zopenai/clip-vit-base-patch32LABEL_0logitsreturnc                     t           j                            | t          j        t          |           | j                            S )Ndevice)r   
functionalcross_entropytorcharangelenr(   )r$   s    b/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/clip/modeling_clip.pycontrastive_lossr/   =   s3    =&&vu|CKKPVP]/^/^/^___    
similarityc                 r    t          |           }t          |                                           }||z   dz  S )Ng       @)r/   t)r1   caption_loss
image_losss      r.   	clip_lossr6   A   s4    #J//L!*,,..11J:%,,r0   tensorc                     t          j        | d          }t          j        |dd          }t          j        |d          }|S )z
    This method is equivalent to tensor.norm(p=2, dim=-1, keepdim=True) and used to make
    model `executorch` exportable. See issue https://github.com/pytorch/executorch/issues/3566
       T)dimkeepdim      ?)r+   powsum)r7   square_tensor
sum_tensornormed_tensors       r.   _get_vector_normrC   G   sB    
 Ifa((M=b$???JIj#..Mr0   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 )CLIPVisionModelOutputa  
    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__rF   r   r+   FloatTensor__annotations__rG   rH   r   rI    r0   r.   rE   rE   R   s          * 15L(5,-444+/u(///=AM8E%"3S"89:AAA:>Ju0#567>>>>>r0   rE   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 )CLIPTextModelOutputa  
    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_embedsrG   .rH   rI   )rJ   rK   rL   rM   rS   r   r+   rN   rO   rG   rH   r   rI   rP   r0   r.   rR   rR   o   s          * 04K%+,333+/u(///=AM8E%"3S"89:AAA:>Ju0#567>>>>>r0   rR   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 )
CLIPOutputa  
    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 [`CLIPTextModel`].
        image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
            The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPVisionModel`].
        text_model_output (`BaseModelOutputWithPooling`):
            The output of the [`CLIPTextModel`].
        vision_model_output (`BaseModelOutputWithPooling`):
            The output of the [`CLIPVisionModel`].
    Nlosslogits_per_imagelogits_per_textrS   rF   text_model_outputvision_model_outputr%   c                 ^     t           fd                                 D                       S )Nc              3   t   K   | ]2}|d vr|         n!t          |                                          V  3dS ))rY   rZ   N)getattrto_tuple).0kselfs     r.   	<genexpr>z&CLIPOutput.to_tuple.<locals>.<genexpr>   sc       
 
  LLLDGGRYZ^`aRbRbRkRkRmRm
 
 
 
 
 
r0   )tuplekeysra   s   `r.   r^   zCLIPOutput.to_tuple   sC     
 
 
 
YY[[
 
 
 
 
 	
r0   )rJ   rK   rL   rM   rV   r   r+   rN   rO   rW   rX   rS   rF   rY   r   rZ   r   r   r^   rP   r0   r.   rU   rU      s          ( )-D(5$
%,,,*.e'...)-OU&---%)K")))&*L%#***4818886:3:::
%* 
 
 
 
 
 
r0   rU   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 )CLIPVisionEmbeddingsconfigc                 z   t                                                       || _        |j        | _        |j        | _        |j        | _        t          j        t          j
        | j                            | _        t          j        |j        | j        | j        | j        d          | _        | j        | j        z  dz  | _        | j        dz   | _        t          j        | j        | j                  | _        |                     dt          j        | j                                      d          d           d S )NF)in_channelsout_channelskernel_sizestridebiasr9   r   position_idsr   r:   
persistent)super__init__rh   hidden_size	embed_dim
image_size
patch_sizer   	Parameterr+   randnclass_embeddingConv2dnum_channelspatch_embeddingnum_patchesnum_positions	Embeddingposition_embeddingregister_bufferr,   expandra   rh   	__class__s     r.   rt   zCLIPVisionEmbeddings.__init__   s   + + +!|EK,G,GHH!y+? 
  
  
 !Ot>1D!-1"$,t/A4>"R"R^U\$:L-M-M-T-TU\-]-]jopppppr0   
embeddingsheightwidthr%   c                    |j         d         dz
  }| j        j                            d          }|j         d         dz
  }t          j                                        s&||k    r ||k    r|                     | j                  S |ddddf         }|ddddf         }|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|	          }t	          j        ||f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.

        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   Nr:   r=   r   r9   bicubicF)sizemodealign_cornersr;   )shaper   weight	unsqueezer+   jit
is_tracingro   rx   r   reshapepermuter   r)   interpolateviewcat)ra   r   r   r   r   r   r   class_pos_embedpatch_pos_embedr;   
new_height	new_widthsqrt_num_positionss                r.   interpolate_pos_encodingz-CLIPVisionEmbeddings.interpolate_pos_encoding   s    !&q)A-!4;EEaHH*03a7 y##%% 	>+*F*F6UZ??**4+<===,QQQU3,QQQU3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y/?;CCCCr0   Fpixel_valuesc                 <   |j         \  }}}}|s<|| j        k    s|| j        k    r&t          d| d| d| j         d| j         d	          | j        j        j        }|                     |                    |                    }|                    d                              dd          }| j	        
                    |dd          }	t          j        |	|gd	          }
|r|
|                     |
||          z   }
n|
|                     | j                  z   }
|
S )
NzInput image size (*z) doesn't match model ().)dtyper9   r   r:   r   )r   rw   
ValueErrorr~   r   r   toflatten	transposer{   r   r+   r   r   r   ro   )ra   r   r   
batch_size_r   r   target_dtypepatch_embedsclass_embedsr   s              r.   forwardzCLIPVisionEmbeddings.forward   sF   '3'9$
Avu' 	Vt-F-F%SWSbJbJbuVuueuuPTP_uubfbquuu   +28++LOO,O,O,OPP#++A..88A>>+22:q"EEYl;CCC
# 	Q#d&C&CJPVX]&^&^^JJ#d&=&=d>O&P&PPJr0   F)rJ   rK   rL   r!   rt   r+   Tensorintr   rN   r   __classcell__r   s   @r.   rg   rg      s        q/ q q q q q q,'D5< 'D 'DUX 'D]b]i 'D 'D 'D 'DR E$5 Z_Zf        r0   rg   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 )
CLIPTextEmbeddingsrh   c                 V   t                                                       |j        }t          j        |j        |          | _        t          j        |j        |          | _        | 	                    dt          j        |j                                      d          d           d S )Nro   rp   Frq   )rs   rt   ru   r   r   
vocab_sizetoken_embeddingmax_position_embeddingsr   r   r+   r,   r   ra   rh   rv   r   s      r.   rt   zCLIPTextEmbeddings.__init__  s    &	!|F,=yII"$,v/My"Y"Y 	EL)GHHOOPWXXej 	 	
 	
 	
 	
 	
r0   N	input_idsro   inputs_embedsr%   c                     ||j         d         n|j         d         }|| j        d d d |f         }||                     |          }|                     |          }||z   }|S )Nr:   )r   ro   r   r   )ra   r   ro   r   
seq_lengthposition_embeddingsr   s          r.   r   zCLIPTextEmbeddings.forward  s     -6,AY_R((}GZ[]G^
,QQQ^<L  00;;M"55lCC"%88
r0   )NNN)rJ   rK   rL   r    rt   r   r+   
LongTensorrN   r   r   r   r   s   @r.   r   r     s        

~ 

 

 

 

 

 

 153759	 E,- u/0   12	
 
       r0   r   c                        e Zd ZdZ fdZdej        dedefdZ	 	 	 dd	ej        d
e	ej                 de	ej                 de	e
         deej        e	ej                 f         f
dZ xZS )CLIPAttentionz=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`: r         )rs   rt   rh   ru   rv   num_attention_heads	num_headshead_dimr   scaleattention_dropoutdropoutr   Lineark_projv_projq_projout_projr   s     r.   rt   zCLIPAttention.__init__(  s   +3$.8=4>)T^;;'dn ' 'N' ' '   ]D(
/i??i??i??	$.$.AAr0   r7   seq_lenbszc                     |                     ||| j        | j                                      dd                                          S )Nr   r9   )r   r   r   r   
contiguous)ra   r7   r   r   s       r.   _shapezCLIPAttention._shape;  s<    {{3GGQQRSUVWWbbdddr0   NFrH   attention_maskcausal_attention_maskoutput_attentionsr%   c                    |                                 \  }}}|                     |          | j        z  }|                     |                     |          d|          }	|                     |                     |          d|          }
|| j        z  d| j        f} |                     |||          j        | } |	j        | }	 |
j        | }
|	                     d          }t          j
        ||	                    dd                    }|                                 || j        z  ||fk    r2t          d|| j        z  ||f d|                                            ||                                 |d||fk    r+t          d|d||f d|                                            |                    || j        ||          |z   }|                    || j        z  ||          }||                                 |d||fk    r+t          d|d||f d|                                            |                    || j        ||          |z   }|                    || j        z  ||          }t          j                            |d          }|r=|                    || j        ||          }|                    || j        z  ||          }nd}t          j                            || j        | j        	          }t          j
        ||
          }|                                 || j        z  || j        fk    r5t          d
|| j        || j        f d|                                            |                    || j        || j                  }|                    dd          }|                    |||          }|                     |          }||fS )z#Input shape: Batch x Time x Channelr:   r   r9   z$Attention weights should be of size z	, but is Nz!Attention mask should be of size r   )ptrainingz `attn_output` should be of size )r   r   r   r   r   r   r   r   r   r+   bmmr   r   r   r)   softmaxr   r   r   r   )ra   rH   r   r   r   r   tgt_lenrv   query_states
key_statesvalue_states
proj_shapesrc_lenattn_weightsattn_weights_reshaped
attn_probsattn_outputs                    r.   r   zCLIPAttention.forward>  s0    #0"4"4"6"6Wi {{=11DJ>[[]!;!;REE
{{4;;}#=#=r3GGDN*B>
Ct{{<#>>CZP$Z_j1
(|(*5//!$$yz/C/CAq/I/IJJ3#7'"JJJ*dn8LgW^7_ * * %%''* *   !,$))++Q/III 7a'8R 7 7-22447 7   (,,S$.'7SSVkkL',,S4>-A7GTTL%""$$a'(BBB ta'8Rtt]k]p]p]r]rtt   (,,S$.'7SSVddL',,S4>-A7GTTL},,\r,BB 	)
 %1$5$5c4>7T[$\$\!055cDN6JGU\]]LL$(!]**<4<RVR_*``
i
L99#"6!OOO)CRVR_3` ) )$$&&) )  
 "&&sDNGT]SS!++Aq11!))#w	BBmmK00111r0   NNF)rJ   rK   rL   rM   rt   r+   r   r   r   r   boolr   r   r   r   s   @r.   r   r   %  s        GGB B B B B&eU\ eC ec e e e e 268<,1L2 L2|L2 !.L2  (5	L2
 $D>L2 
u|Xel33	4L2 L2 L2 L2 L2 L2 L2 L2r0   r   c                        e Zd ZdZ fdZ	 	 	 ddej        deej                 deej                 dee         d	e	ej        eej                 f         f
d
Z
 xZS )CLIPFlashAttention2aM  
    CLIPAttention flash attention module. This module inherits from `CLIPAttention` 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.
    c                 b     t                      j        |i | t                       | _        d S N)rs   rt   r   _flash_attn_uses_top_left_mask)ra   argskwargsr   s      r.   rt   zCLIPFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r0   NFrH   r   r   r   r%   c           
         d}|                                 \  }}}|                     |          }|                     |          }	|                     |          }
|                    ||| j        | j                  }|	                    ||| j        | j                  }	|
                    ||| j        | j                  }
| 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+          ||	|
||||d u| j                  }|                    ||| j                                                  }|                     |          }|sd }||fS )NF        _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+   float32is_autocast_enabledget_autocast_gpu_dtypehasattrrh   r   r   loggerwarning_oncer   r"   r   r   rv   r   r   )ra   rH   r   r   r   r   q_lenr   r   r   r   dropout_rateinput_dtyper   r   r   s                   r.   r   zCLIPFlashAttention2.forward  s    ",1133
E1{{=11[[//
{{=11
 $((UDNDMZZ__ZVV
#((UDNDMZZ'+}=t||# #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L. +47"A	
 	
 	
 "))*eT^LLWWYYmmK00  	 LL((r0   r   )rJ   rK   rL   rM   rt   r+   r   r   r   r   r   r   r   s   @r.   r   r     s         X X X X X 268<,1C) C)|C) !.C)  (5	C)
 $D>C) 
u|Xel33	4C) C) C) C) C) C) C) C)r0   r   c                        e Zd ZdZ	 	 	 d
dej        deej                 deej                 dee         deej        eej                 f         f
 fd	Z	 xZ
S )CLIPSdpaAttentionz
    SDPA attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `CLIPAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrH   r   r   r   r%   c                 J   |r?t                               d           t                                          ||||          S ||||z   }n||}n|}|                                \  }}}|                     |          }	|                     |          }
|                     |          }|	                    |d| j	        | j
                                      dd          }	|
                    |d| j	        | j
                                      dd          }
|                    |d| j	        | j
                                      dd          }t          sN|	j        j        dk    r>|<|	                                }	|
                                }
|                                }t           j        j                            |	|
||| j        r| j        nd| j                  }|                    dd          }|                    |||          }|                     |          }|d fS )	Na  CLIPModel is using CLIPSdpaAttention, 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.rH   r   r   r   r:   r   r9   cudar   )	attn_mask	dropout_pr   )r   r   rs   r   r   r   r   r   r   r   r   r   r   r(   typer   r+   r   r)   scaled_dot_product_attentionr   r   r   r   r   )ra   rH   r   r   r   r  r   r   rv   r   r   r   r   r   s                r.   r   zCLIPSdpaAttention.forward  s<     	f   77??+-&;"3	 #    %*?*K&)>>II".-II&I"/"4"4"6"6Wi{{=11[[//
{{=11#((b$.$-PPZZ[\^_``__S"dndmLLVVWXZ[\\
#((b$.$-PPZZ[\^_`` 2 	5l6I6NRX6X6X]f]r'2244L#..00J'2244L h)FF&*m<dll* G 
 
 "++Aq11!))#w	BBmmK00D  r0   r   )rJ   rK   rL   rM   r+   r   r   r   r   r   r   r   s   @r.   r  r    s          268<,1>! >!|>! !.>!  (5	>!
 $D>>! 
u|Xel33	4>! >! >! >! >! >! >! >! >! >!r0   r  )eagersdpaflash_attention_2c                   B     e Zd Z fdZdej        dej        fdZ xZS )CLIPMLPc                    t                                                       || _        t          |j                 | _        t          j        |j        |j	                  | _
        t          j        |j	        |j                  | _        d S r   )rs   rt   rh   r   
hidden_actactivation_fnr   r   ru   intermediate_sizefc1fc2r   s     r.   rt   zCLIPMLP.__init__5  sf    #F$569V/1IJJ9V5v7IJJr0   rH   r%   c                     |                      |          }|                     |          }|                     |          }|S r   )r  r  r  )ra   rH   s     r.   r   zCLIPMLP.forward<  s=    //**=99//r0   )rJ   rK   rL   rt   r+   r   r   r   r   s   @r.   r  r  4  sc        K K K K KU\ el        r0   r  c                        e Zd Zdef fdZ	 d
dej        dej        dej        dee         de	ej
                 f
d	Z xZS )CLIPEncoderLayerrh   c                 Z   t                                                       |j        | _        t	          |j                 |          | _        t          j        | j        |j	                  | _
        t          |          | _        t          j        | j        |j	                  | _        d S Neps)rs   rt   ru   rv   CLIP_ATTENTION_CLASSES_attn_implementation	self_attnr   	LayerNormlayer_norm_epslayer_norm1r  mlplayer_norm2r   s     r.   rt   zCLIPEncoderLayer.__init__D  s    +/0KLVTT<F<QRRR6??<F<QRRRr0   FrH   r   r   r   r%   c                     |}|                      |          }|                     ||||          \  }}||z   }|}|                     |          }|                     |          }||z   }|f}|r||fz  }|S )aI  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`): attention mask of size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
                `(config.encoder_attention_heads,)`.
            output_attentions (`bool`, *optional*):
                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!  )ra   rH   r   r   r   residualr   outputss           r.   r   zCLIPEncoderLayer.forwardL  s    " !((77&*nn')"7/	 '5 '
 '
#| !=0 ((77// =0 " 	'&Gr0   r   )rJ   rK   rL   r   rt   r+   r   r   r   r   rN   r   r   r   s   @r.   r  r  C  s        Sz S S S S S S -2& &|& &  %|	&
 $D>& 
u 	!& & & & & & & &r0   r  c                   ,    e Zd ZdZeZdZdZdZdZ	d Z
dS )CLIPPreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    clipTc                 d
   | j         j        }t          |t                    rT|j        j        j                            d|dz             |j        j        j                            d|dz             n t          |t                    r| j         j        }t          j                            |j        d|j        dz  |z             t          j                            |j        j        |j         j        |z             t          j                            |j        j        |j         j        |z             n[t          |t                     r| j         j        }|j        dz  d|j         j        z  dz  z  |z  }|j        dz  |z  }t          j                            |j        j        |           t          j                            |j        j        |           t          j                            |j        j        |           t          j                            |j        j        |           n_t          |t,                    r| j         j        }|j         j        dz  d|j         j        z  dz  z  |z  }d|j         j        z  dz  |z  }t          j                            |j        j        |           t          j                            |j        j        |           nt          |t4                    rt          j                            |j        j        |j        dz  | j         j        z             t          j                            |j        j        |j        dz  | j         j        z             nt          |t>                    rFt          j                            |j        j        | j         j        dz  | j         j        z             nt          |t@                    rFt          j                            |j        j        | j         j        dz  | j         j        z             n_t          |tB                    rJt          j                            |j"        j        | j         j#        j        dz  | j         j        z             t          |t          j$                  r=|j%        j        &                                 |j        j        '                    d           t          |t          j(                  r'|j%        "|j%        j        &                                 dS dS dS )	zInitialize the weightsr   g{Gz?)meanstdr   )r+  r9   g      ?N))rh   initializer_factor
isinstancer   r   r   datanormal_r   rg   r   initr{   rv   r~   initializer_ranger   num_hidden_layersr   r   r   r   r  ru   r  r  	CLIPModeltext_projectiontext_embed_dimvisual_projectionvision_embed_dimCLIPVisionModelWithProjectionCLIPTextModelWithProjectionCLIPForImageClassification
classifiervision_configr  rn   zero_fill_r   )ra   modulefactorin_proj_stdout_proj_stdfc_stds         r.   _init_weightsz!CLIPPreTrainedModel._init_weights  s   /f011 -	").66CVd]6SSS%,199sQU9VVVV 455 *	[3FGOOF2&BRTXBX[aBaObbbGOOF29v}?^ag?gOhhhGOOF5<&-BadjBjOkkkk.. %	[3F!+T1q6=;Z7Z_c6cdgmmK",d2f<LGOOFM0kOBBBGOOFM0kOBBBGOOFM0kOBBBGOOFO2OEEEE(( 	[3F!=4d:FMDc@chl?lmpvvK&-33<vEFGOOFJ-6O:::GOOFJ-;O????	** 	GOO&-)4/$+2PP     GOO(/+T1DK4RR       =>> 	GOO(/K+T1DK4RR       ;<< 		GOO&-K+T1DK4RR       :;; 	GOO!(K-94?$+B``    
 fbl++ 	*K""$$$M$$S)))fbi(( 	%V[-DK""$$$$$	% 	%-D-Dr0   N)rJ   rK   rL   rM   r   config_classbase_model_prefixsupports_gradient_checkpointing_supports_sdpa_supports_flash_attn_2rD  rP   r0   r.   r'  r'  u  sK         
 L&*#N!6% 6% 6% 6% 6%r0   r'  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 ([`CLIPConfig`]): 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 `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 `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j                 dee	         dee	         d	ee	         d
e
eef         fdZ xZS )CLIPEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`CLIPEncoderLayer`].

    Args:
        config: CLIPConfig
    rh   c                     t                                                       | _        t          j        fdt          j                  D                       | _        d| _        d S )Nc                 .    g | ]}t                    S rP   )r  )r_   r   rh   s     r.   
<listcomp>z(CLIPEncoder.__init__.<locals>.<listcomp>.  s"    $g$g$g!%5f%=%=$g$g$gr0   F)	rs   rt   rh   r   
ModuleListranger2  layersgradient_checkpointingr   s    `r.   rt   zCLIPEncoder.__init__+  s`    m$g$g$g$guVMeGfGf$g$g$ghh&+###r0   Nr   r   r   output_hidden_statesreturn_dictr%   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|rdnd}|rdnd}|}	t	          | j                  D ]_\  }
}|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 )a  
        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)
            causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Causal mask for the text model. 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.
        NrP   )r   r   r   c              3      K   | ]}||V  	d S r   rP   )r_   vs     r.   rb   z&CLIPEncoder.forward.<locals>.<genexpr>}  s(      eeqWXWdWdWdWdWdeer0   )rG   rH   rI   )rh   r   rS  use_return_dict	enumeraterQ  rR  r   _gradient_checkpointing_func__call__rc   r   )ra   r   r   r   r   rS  rT  encoder_statesall_attentionsrH   idxencoder_layerlayer_outputss                r.   r   zCLIPEncoder.forward1  s   L 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]3=0:d%"+DK"8"8 	F 	FC# C!/=2B!B* t}  $ A A!*!")%! ! !.!")&7	! ! ! *!,M  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+>Vd
 
 
 	
r0   NNNNN)rJ   rK   rL   rM   r   rt   r   r+   r   r   r   r   r   r   r   r   s   @r.   rK  rK  "  s         ,z , , , , , , 268<,0/3&*O
 O
 !.O
  (5	O

 $D>O
 'tnO
 d^O
 
uo%	&O
 O
 O
 O
 O
 O
 O
 O
r0   rK  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 )CLIPTextTransformerrh   c                 ,   t                                                       || _        |j        }t	          |          | _        t          |          | _        t          j	        ||j
                  | _        |j        | _        |j        dk    | _        d S )Nr  r  )rs   rt   rh   ru   r   r   rK  encoderr   r  r  final_layer_normeos_token_idr  _use_flash_attention_2r   s      r.   rt   zCLIPTextTransformer.__init__  s    &	,V44"6** "YF<Q R R R #/ '-&AEX&X###r0   output_typerE  Nr   r   ro   r   rS  rT  r%   c                 8   ||n| j         j        }||n| j         j        }||n| j         j        }|t	          d          |                                }|                    d|d                   }|                     ||          }t          ||j	        |j
                  }	|| j        st          ||j	                  }|                     |||	|||          }
|
d         }|                     |          }| j        dk    rg|t!          j        |j        d         |j
                  |                    t           j        |j
        	                              d
          f         }n|t!          j        |j        d         |j
                  |                    t           j        |j
        	          | j        k                                                        d
          f         }|s||f|
dd         z   S t-          |||
j        |
j                  S )
        Returns:

        NzYou have to specify input_idsr:   )r   ro   r'   )r   r   r   r   rS  rT  r   r9   )r   r(   r   r   rG   pooler_outputrH   rI   )rh   r   rS  rX  r   r   r   r   r   r   r(   rh  r   re  rf  rg  r+   r,   r   r   r   argmaxr   rH   rI   )ra   r   r   ro   r   rS  rT  input_shaperH   r   encoder_outputsrG   pooled_outputs                r.   r   zCLIPTextTransformer.forward  sP    2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]<===nn&&NN2{277	),WW !A,]5I!
 !
 !

 %d.I%7H[\\N,,')"7/!5# ' 
 
 ,A. 112CDD!! ..4Q7@Q@XYYY595F5MNNUUZ\U]]_MM ..4Q7@Q@XYYY EI6G6NOOSWSddB!M  	L%}58KKK)/')7&1	
 
 
 	
r0   NNNNNN)rJ   rK   rL   r    rt   r   CLIP_TEXT_INPUTS_DOCSTRINGr   r   r   r+   r   r   r   r   r   r   r   s   @r.   rc  rc    s0       Y~ Y Y Y Y Y Y +*+EFF+ETbccc -115/3,0/3&*P
 P
EL)P
 !.P
 u|,	P

 $D>P
 'tnP
 d^P
 
u00	1P
 P
 P
 dc GFP
 P
 P
 P
 P
r0   rc  z?The text model from CLIP without any head or projection on top.c                   <    e Zd ZeZddg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 )CLIPTextModelr   r  rh   c                     t                                          |           t          |          | _        |                                  d S r   )rs   rt   rc  
text_model	post_initr   s     r.   rt   zCLIPTextModel.__init__  s@       -f55r0   r%   c                 $    | j         j        j        S r   rx  r   r   re   s    r.   get_input_embeddingsz"CLIPTextModel.get_input_embeddings      )99r0   c                 (    || j         j        _        d S r   r{  ra   values     r.   set_input_embeddingsz"CLIPTextModel.set_input_embeddings      5:"222r0   ri  Nr   r   ro   r   rS  rT  c                 X    ||n| j         j        }|                     ||||||          S )aK  
        Returns:

        Examples:

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

        >>> model = CLIPTextModel.from_pretrained("openai/clip-vit-base-patch32")
        >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, 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   ro   r   rS  rT  )rh   rX  rx  )ra   r   r   ro   r   rS  rT  s          r.   r   zCLIPTextModel.forward  sD    8 &1%<kk$+B])%/!5#  
 
 	
r0   rs  )rJ   rK   rL   r    rE  _no_split_modulesrt   r   Moduler|  r  r   rt  r   r   r   r+   r   r   r   r   r   r   r   s   @r.   rv  rv    sX       
 "L-/AB~      :bi : : : :; ; ; +*+EFF+ETbccc -115/3,0/3&*#
 #
EL)#
 !.#
 u|,	#

 $D>#
 'tn#
 d^#
 
u00	1#
 #
 #
 dc GF#
 #
 #
 #
 #
r0   rv  c                        e Zd Zdef fdZ ee           eee          	 	 	 	 	 dde	e
j                 de	e         de	e         d	e	e         d
e	e         deeef         fd                        Z xZS )CLIPVisionTransformerrh   c                 4   t                                                       || _        |j        }t	          |          | _        t          j        ||j                  | _	        t          |          | _        t          j        ||j                  | _        d S r  )rs   rt   rh   ru   rg   r   r   r  r  pre_layrnormrK  re  post_layernormr   s      r.   rt   zCLIPVisionTransformer.__init__%  s    &	.v66L8MNNN"6** l9&:OPPPr0   ri  NFr   r   rS  rT  r   r%   c                    ||n| j         j        }||n| j         j        }||n| j         j        }|t	          d          |                     ||          }|                     |          }|                     ||||          }|d         }|dddddf         }	|                     |	          }	|s||	f|dd         z   S t          ||	|j
        |j                  S )rl  Nz You have to specify pixel_values)r   )r   r   rS  rT  r   r   rm  )rh   r   rS  rX  r   r   r  re  r  r   rH   rI   )
ra   r   r   rS  rT  r   rH   rq  rG   rr  s
             r.   r   zCLIPVisionTransformer.forward/  s/    2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]?@@@Oghh))-88,,'/!5#	 ' 
 
 ,A.)!!!Q'2++M:: 	L%}58KKK)/')7&1	
 
 
 	
r0   )NNNNF)rJ   rK   rL   r!   rt   r   CLIP_VISION_INPUTS_DOCSTRINGr   r   r   r+   rN   r   r   r   r   r   r   s   @r.   r  r  $  s       Q/ Q Q Q Q Q Q +*+GHH+ETdeee 59,0/3&*38+
 +
u01+
 $D>+
 'tn	+

 d^+
 #+4.+
 
u00	1+
 +
 +
 fe IH+
 +
 +
 +
 +
r0   r  zAThe vision model from CLIP without any head or projection on top.c                       e Zd ZeZdZdgZdef fdZdej	        fdZ
 ee           eee          	 	 	 	 	 ddeej                 d
ee         dee         dedee         deeef         fd                        Z xZS )CLIPVisionModelr   r  rh   c                     t                                          |           t          |          | _        |                                  d S r   )rs   rt   r  vision_modelry  r   s     r.   rt   zCLIPVisionModel.__init__h  sA       1&99r0   r%   c                 $    | j         j        j        S r   r  r   r~   re   s    r.   r|  z$CLIPVisionModel.get_input_embeddingsn       +;;r0   ri  NFr   rS  r   rT  c                 V    ||n| j         j        }|                     |||||          S )a  
        Returns:

        Examples:

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

        >>> model = CLIPVisionModel.from_pretrained("openai/clip-vit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")

        >>> 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 CLS states
        ```N)r   r   rS  rT  r   )rh   rX  r  )ra   r   r   rS  r   rT  s         r.   r   zCLIPVisionModel.forwardq  sD    @ &1%<kk$+B]  %/!5#%= ! 
 
 	
r0   NNNFN)rJ   rK   rL   r!   rE  main_input_namer  rt   r   r  r|  r   r  r   r   r   r+   rN   r   r   r   r   r   r   s   @r.   r  r  _  s2       
 $L$O+,/      <bi < < < < +*+GHH+ETdeee 59,0/3).&*&
 &
u01&
 $D>&
 'tn	&

 #'&
 d^&
 
u00	1&
 &
 &
 fe IH&
 &
 &
 &
 &
r0   r  c                       e Zd ZeZg d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d
e	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d
e	e         deeef         fd                        Z xZS )r3  )r   r  rg   rh   c                 l   t                                          |           t          |j        t                    s%t          dt          |j                   d          t          |j        t                    s%t          dt          |j                   d          |j        }|j        }|j	        | _	        |j
        | _        |j
        | _        t                              |          }|j        | _        t                               |          }|j        | _        t%          j        | j        | j	        d          | _        t%          j        | j        | j	        d          | _        t%          j        t/          j        | j        j                            | _        |                                  d S )NzKconfig.text_config is expected to be of type CLIPTextConfig but is of type r   zOconfig.vision_config is expected to be of type CLIPVisionConfig but is of type Frn   )rs   rt   r-  text_configr    	TypeErrorr  r<  r!   projection_dimru   r5  r7  rv  _from_configrx  r  r  r   r   r6  r4  ry   r+   r7   rh   logit_scale_init_valuelogit_scalery  )ra   rh   r  r<  rx  r  r   s         r.   rt   zCLIPModel.__init__  s      &,n== 	0+,,0 0 0  
 &.0@AA 	2-..2 2 2  
 (,$3)5 - 9"//<<
$/&33MBB(5!#4+@$BU\a!b!b!b!y)<d>QX]^^^<T[5W(X(XYY 	r0   Nr   r   ro   r   rS  rT  r%   c                     ||n| j         j        }||n| j         j        }||n| j         j        }|                     ||||||          }|d         }|                     |          }	|	S )a  
        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 [`CLIPTextModel`].

        Examples:

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

        >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
        >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
        >>> text_features = model.get_text_features(**inputs)
        ```Nr  r   )rh   r   rS  rX  rx  r4  )
ra   r   r   ro   r   rS  rT  text_outputsrr  text_featuress
             r.   get_text_featureszCLIPModel.get_text_features  s    6 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B])%/!5# ' 
 
 %Q,,];;r0   Fr   r   c                     ||n| j         j        }||n| j         j        }||n| j         j        }|                     |||||          }|d         }|                     |          }|S )aD  
        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 [`CLIPVisionModel`].

        Examples:

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

        >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")

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

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

        >>> image_features = model.get_image_features(**inputs)
        ```Nr   r   rS  r   rT  r   )rh   r   rS  rX  r  r6  )	ra   r   r   rS  r   rT  vision_outputsrr  image_featuress	            r.   get_image_featureszCLIPModel.get_image_features  s    @ 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]**%/!5%=# + 
 
 'q)//>>r0   ri  return_lossc
           	         ||n| j         j        }||n| j         j        }|	|	n| j         j        }	|                     |||||	          }
|                     ||||||	          }|
d         }|                     |          }|d         }|                     |          }|t          |          z  }|t          |          z  }| j	        
                                }t          j        ||                                                    |j                            |                    |j                  z  }|                                }d}|rt!          |          }|	s||||||
f}||f|z   n|S t#          |||||||
          S )a  
        Returns:

        Examples:

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

        >>> model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")

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

        >>> inputs = processor(
        ...     text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
        ... )

        >>> outputs = model(**inputs)
        >>> logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
        >>> probs = logits_per_image.softmax(dim=1)  # we can take the softmax to get the label probabilities
        ```Nr  r  r   )rV   rW   rX   rS   rF   rY   rZ   )rh   r   rS  rX  r  rx  r6  r4  rC   r  expr+   matmulr3   r   r(   r6   rU   )ra   r   r   r   ro   r  r   rS  r   rT  r  r  rF   rS   r  rX   rW   rV   outputs                      r.   r   zCLIPModel.forward&  s   N 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]**%/!5%=# + 
 
 )%/!5# ' 
 
 &a(--l;;"1o**;77 $&6|&D&DD!$4[$A$AA &**,,,{LNN4D4D4G4GHZ4[4[\\_j_m_m`
 `
 
 +,,.. 	._--D 	F&lT`bpqF)-)9TGf$$vE-+#%* .
 
 
 	
r0   rs  r  )	NNNNNNNFN)rJ   rK   rL   r   rE  r  rt   r   rt  r   r+   r   r   rN   r  r  r  CLIP_INPUTS_DOCSTRINGr   rU   r   r   r   r   r   r   s   @r.   r3  r3    s       LZZZ!z ! ! ! ! ! !F +*+EFF -115/3,0/3&*, ,EL), !., u|,	,
 $D>, 'tn, d^, 
	, , , GF,\ +*+GHH 59,0/3).&*0 0u010 $D>0 'tn	0
 #'0 d^0 
	0 0 0 IH0d +*+@AA:JOOO 15481537&*,0/3).&*]
 ]
E,-]
 u01]
 !.	]

 u/0]
 d^]
 $D>]
 'tn]
 #']
 d^]
 
uj 	!]
 ]
 ]
 PO BA]
 ]
 ]
 ]
 ]
r0   r3  zf
    CLIP Text Model with a projection layer on top (a linear layer on top of the pooled output).
    c                   <    e Zd ZeZddg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 )r9  r   r  rh   c                    t                                          |           t                              ||j                  }|j        | _        t          j        |j        |j	        d          | _
        |                                  d S N)attn_implementationFr  )rs   rt   rv  r  r  rx  r   r   ru   r  r4  ry  )ra   rh   rx  r   s      r.   rt   z$CLIPTextModelWithProjection.__init__  sx       "//FLg/hh
$/!y);V=RY^___ 	r0   r%   c                 $    | j         j        j        S r   r{  re   s    r.   r|  z0CLIPTextModelWithProjection.get_input_embeddings  r}  r0   c                 (    || j         j        _        d S r   r{  r  s     r.   r  z0CLIPTextModelWithProjection.set_input_embeddings  r  r0   ri  Nr   r   ro   r   rS  rT  c                 6   ||n| j         j        }|                     ||||||          }|d         }|                     |          }	|s.|	|d         f|dd         z   }
t	          d |
D                       S t          |	|j        |j        |j                  S )a  
        Returns:

        Examples:

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

        >>> model = CLIPTextModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
        >>> tokenizer = AutoTokenizer.from_pretrained("openai/clip-vit-base-patch32")

        >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> text_embeds = outputs.text_embeds
        ```Nr  r   r   r9   c              3      K   | ]}||V  	d S r   rP   r_   r  s     r.   rb   z6CLIPTextModelWithProjection.forward.<locals>.<genexpr>  '      LLF9K9K9K9K9KLLr0   )rS   rG   rH   rI   )	rh   rX  rx  r4  rc   rR   rG   rH   rI   )ra   r   r   ro   r   rS  rT  r  rr  rS   r%  s              r.   r   z#CLIPTextModelWithProjection.forward  s    6 &1%<kk$+B])%/!5# ' 
 
 %Q**=99 	M"LO4|ABB7GGGLLgLLLLLL"#*<&4#.	
 
 
 	
r0   rs  )rJ   rK   rL   r    rE  r  rt   r   r  r|  r  r   rt  r   rR   r   r+   r   r   r   r   r   r   r   s   @r.   r9  r9    sW        "L-/AB	~ 	 	 	 	 	 	:bi : : : :; ; ; +*+EFF+>^\\\ -115/3,0/3&*1
 1
EL)1
 !.1
 u|,	1

 $D>1
 'tn1
 d^1
 
u))	*1
 1
 1
 ]\ GF1
 1
 1
 1
 1
r0   r9  zh
    CLIP Vision Model with a projection layer on top (a linear layer on top of the pooled output).
    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j                 d	ee         d
ee         dedee         deeef         fd                        Z xZS )r8  r   rh   c                    t                                          |           t                              ||j                  }|j        | _        t          j        |j        |j	        d          | _
        |                                  d S r  )rs   rt   r  r  r  r  r   r   ru   r  r6  ry  ra   rh   r  r   s      r.   rt   z&CLIPVisionModelWithProjection.__init__  sz       &33FPVPk3ll(5!#6+=v?T[`!a!a!a 	r0   r%   c                 $    | j         j        j        S r   r  re   s    r.   r|  z2CLIPVisionModelWithProjection.get_input_embeddings  r  r0   ri  NFr   rS  r   rT  c                 4   ||n| j         j        }|                     |||||          }|d         }|                     |          }|s.||d         f|dd         z   }	t	          d |	D                       S t          ||j        |j        |j                  S )a  
        Returns:

        Examples:

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

        >>> model = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-base-patch32")
        >>> processor = AutoProcessor.from_pretrained("openai/clip-vit-base-patch32")

        >>> 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)
        >>> image_embeds = outputs.image_embeds
        ```Nr  r   r   r9   c              3      K   | ]}||V  	d S r   rP   r  s     r.   rb   z8CLIPVisionModelWithProjection.forward.<locals>.<genexpr>!  r  r0   )rF   rG   rH   rI   )	rh   rX  r  r6  rc   rE   rG   rH   rI   )
ra   r   r   rS  r   rT  r  rr  rF   r%  s
             r.   r   z%CLIPVisionModelWithProjection.forward  s    > &1%<kk$+B]**%/!5%=# + 
 
 'q)--m<< 	M#^A%67.:LLGLLgLLLLLL$%,>(6%0	
 
 
 	
r0   r  )rJ   rK   rL   r!   rE  r  rt   r   r  r|  r   r  r   rE   r   r+   rN   r   r   r   r   r   r   s   @r.   r8  r8    s)        $L$O	/ 	 	 	 	 	 	<bi < < < < +*+GHH+@O_``` 59,0/3).&*4
 4
u014
 $D>4
 'tn	4

 #'4
 d^4
 
u++	,4
 4
 4
 a` IH4
 4
 4
 4
 4
r0   r8  z
    CLIP 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
ee          	 	 	 	 	 d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 )r:  r   rh   r%   Nc                 n   t                                          |           |j        | _        t                              |j                  }|j        | _        |j        dk    r$t          j        |j        j	        |j                  nt          j
                    | _        |                                  d S )Nr   )rs   rt   
num_labelsr  r  r<  r  r   r   ru   Identityr;  ry  r  s      r.   rt   z#CLIPForImageClassification.__init__5  s        +&33F4HII(5 OUN_bcNcNcBIf*68IJJJikitiviv 	
 	r0   )
checkpointrj  rE  expected_outputlabelsr   rS  rT  c                 x   ||n| j         j        }||n| j         j        }||n| j         j        }|                     ||||          }|d         }t          j        |ddddddf         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 )a  
        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).
        N)r   rS  rT  r   r   r   
regressionsingle_label_classificationmulti_label_classificationr:   r9   )rV   r$   rH   rI   )rh   r   rS  rX  r  r+   r*  r;  r   r(   problem_typer  r   longr   r   squeezer
   r   r	   r   rH   rI   )ra   r   r  r   rS  rT  r%  sequence_outputr$   rV   loss_fctr  s               r.   r   z"CLIPForImageClassification.forwardD  sq   * 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]##/!5#	 $ 
 
 "!*  *_QQQAAAX%>AFFF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$!/)	
 
 
 	
r0   ra  )rJ   rK   rL   r  r   rt   r   r  r   _IMAGE_CLASS_CHECKPOINTr   _CONFIG_FOR_DOC_IMAGE_CLASS_EXPECTED_OUTPUTr   r+   r   r   r   rc   r   r   r   s   @r.   r:  r:  +  s/        %Oz d       +*+@AA*)$4	   04)-,0/3&*D
 D
u|,D
 &D
 $D>	D

 'tnD
 d^D
 
u++	,D
 D
 D
  BAD
 D
 D
 D
 D
r0   r:  )QrM   dataclassesr   typingr   r   r   r   r+   torch.utils.checkpointr   torch.nnr	   r
   r   activationsr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   r   r   r   r   configuration_clipr   r    r!   modeling_flash_attention_utilsr"   
get_loggerrJ   r   r  _CHECKPOINT_FOR_DOCr  r  r   r/   r6   rC   rE   rR   rU   r  rg   r   r   r   r  r  r  r  r'  CLIP_START_DOCSTRINGrt  r  r  rK  rc  rv  r  r  r3  r9  r8  r:  rP   r0   r.   <module>r     sO     ! ! ! ! ! ! . . . . . . . . . . . .            A A A A A A A A A A ! ! ! ! ! ! d d d d d d d d b b b b b b b b b b - - - - - - ? ? ? ? ? ?
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 M L L L L L L L L L  KJJJJJJ 
	H	%	% 4  9 ( 
`U\ `el ` ` ` `-%, -5< - - - -U\ el     ? ? ? ? ?K ? ? ?8 ? ? ? ? ?+ ? ? ?8 !
 !
 !
 !
 !
 !
 !
 !
HP P P P P29 P P Pf       Be2 e2 e2 e2 e2BI e2 e2 e2PT) T) T) T) T)- T) T) T)nF! F! F! F! F! F! F! F!T ,      bi   / / / / /ry / / /dB% B% B% B% B%/ B% B% B%J  @  "% P^
 ^
 ^
 ^
 ^
") ^
 ^
 ^
Ba
 a
 a
 a
 a
") a
 a
 a
H I 6
 6
 6
 6
 6
' 6
 6
	 6
r8
 8
 8
 8
 8
BI 8
 8
 8
v K 6
 6
 6
 6
 6
) 6
 6
	 6
r *++h
 h
 h
 h
 h
# h
 h
 ,+h
V  	 I
 I
 I
 I
 I
"5 I
 I
 I
X  	 H
 H
 H
 H
 H
$7 H
 H
 H
V   ]
 ]
 ]
 ]
 ]
!4 ]
 ]
 ]
 ]
 ]
r0   