
    iq                        d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlm	c m
Z d dlm	Z	 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZmZ ddlmZ ddlm Z m!Z!m"Z"m#Z# ddl$m%Z% ddl&m'Z'm(Z(m)Z) ee" G d de                     Z* ed       G d de	jV                               Z, G d de	jV                        Z- G d de	jV                        Z. G d de	jV                        Z/	 d=de	jV                  dej`                  d ej`                  d!ej`                  d"ej`                  dz  d#e1d$e1fd%Z2 G d& d'e	jV                        Z3 G d( d)e      Z4 G d* d+e	jV                        Z5 G d, d-e	jV                        Z6e" G d. d/e             Z7 e"d01       G d2 d3e7             Z8 e"d41       G d5 d6e7             Z9d7ej`                  d8ej`                  fd9Z:e" G d: d;e7             Z;g d<Z<y)>    N)Callable)	dataclass)Any)nn   )initialization)ACT2FN)use_kernel_forward_from_hub)create_causal_mask)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPooling)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tuple)check_model_inputs   )Aimv2ConfigAimv2TextConfigAimv2VisionConfigc                      e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	ej                  dz  ed<   dZ
ej                  dz  ed<   dZej                  dz  ed<   dZeed<   dZeed	<   d
ee   fdZy)Aimv2Outputa  
    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 [`Aimv2TextModel`].
    image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
        The image embeddings obtained by applying the projection layer to the pooled output of [`Aimv2VisionModel`].
    text_model_output (`BaseModelOutputWithPooling`):
        The output of the [`Aimv2TextModel`].
    vision_model_output (`BaseModelOutputWithPooling`):
        The output of the [`Aimv2VisionModel`].
    Nlosslogits_per_imagelogits_per_texttext_embedsimage_embedstext_model_outputvision_model_outputreturnc                 H     t         fd j                         D              S )Nc              3   d   K   | ]'  }|d vr|   nt        |      j                          ) yw))r"   r#   N)getattrto_tuple).0kselfs     r/home/obispo/Crisostomo_bridge/mision_env/lib/python3.12/site-packages/transformers/models/aimv2/modeling_aimv2.py	<genexpr>z'Aimv2Output.to_tuple.<locals>.<genexpr>K   s=      
  LLDGRYZ^`aRbRkRkRmm
s   -0)tuplekeysr+   s   `r,   r(   zAimv2Output.to_tupleJ   s#     
YY[
 
 	
    )__name__
__module____qualname____doc__r   torchFloatTensor__annotations__r   r   r    r!   r"   r   r#   r.   r   r(    r1   r,   r   r   ,   s    & &*D%

d
")15e''$.504OU&&-4,0K""T)0-1L%##d*148186:3:
%* 
r1   r   RMSNormc                   ,     e Zd Zd fd	Zd Zd Z xZS )Aimv2RMSNormc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z;
        Aimv2RMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr6   onesweightvariance_epsilon)r+   hidden_sizeeps	__class__s      r,   r?   zAimv2RMSNorm.__init__S   s1     	ll5::k#:; #r1   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )N   T)keepdim)	dtypetor6   float32powmeanrsqrtrC   rB   )r+   hidden_statesinput_dtypevariances       r,   forwardzAimv2RMSNorm.forward[   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r1   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)r.   rB   shaperC   r0   s    r,   
extra_reprzAimv2RMSNorm.extra_reprb   s*    ))*+6$2G2G1HIIr1   )gư>)r2   r3   r4   r?   rT   rW   __classcell__rF   s   @r,   r<   r<   Q   s    $;Jr1   r<   c                   $     e Zd Z fdZd Z xZS )Aimv2MLPc                    t         |           || _        |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  | j                  | j                  |j                        | _
        t        |j                     | _        y )Nbias)r>   r?   configrD   intermediate_sizer   Linearmlp_bias	gate_projup_proj	down_projr	   
hidden_actact_fnr+   r_   rF   s     r,   r?   zAimv2MLP.__init__g   s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r1   c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)re   rg   rc   rd   )r+   xre   s      r,   rT   zAimv2MLP.forwardq   s6    NN4;;t~~a/@#ADLLQRO#ST	r1   )r2   r3   r4   r?   rT   rX   rY   s   @r,   r[   r[   f   s    0r1   r[   c                        e Zd Zdef fdZedddej                  fdej                  fd       Z	dej                  dej                  fd	Z
 xZS )
Aimv2VisionEmbeddingsr_   c                 B   t         |           || _        |j                  | _        t	        j
                  |j                  |j                  |j                  |j                        | _        t        |j                  |j                        | _        |j                  |j                  z  dz  }| j                  j                  s%t	        j                  ||j                        | _        | j!                  dt#        j$                  |      j'                  d      d       y )N)kernel_sizestriderH   position_idsr   rI   F
persistent)r>   r?   r_   
patch_sizer   Conv2dnum_channelsrD   patch_embedr<   rms_norm_epsrms_norm
image_size	is_native	Embeddingposition_embeddingregister_bufferr6   arangeexpand)r+   r_   num_patchesrF   s      r,   r?   zAimv2VisionEmbeddings.__init__w   s     ++99!3!3ARAR[a[l[l
 %V%7%79L9LM((F,=,==!C{{$$&(ll;@R@R&SD#^U\\+-F-M-Mg-Vchir1      g     @cpur$   c                 :   t        j                  t        |      ||      }t        j                  t        |       ||      }t        j                  ||d      \  }}|dz  }t        j                  |||      |z  }	d||	z  z  }	|j	                         d   |	d d d f   z  }
|j	                         d   |	d d d f   z  }t        j
                  |
j                         |
j                         |j                         |j                         gd      d d d d d f   S )	NrK   devicexy)indexing   g      ?).Nr   dim)r6   r   intmeshgridflattenconcatsincos)heightwidth	embed_dimtemperaturer   rK   grid_wgrid_hpos_dimomegaout_hout_ws               r,   "build_2d_sincos_position_embeddingz8Aimv2VisionEmbeddings.build_2d_sincos_position_embedding   s     c%jfEc&kvFFq.WE&AGK{E)* +eD!Gn< +eD!Gn<||UYY[%))+uyy{EIIKPVWXY]_`bcYcddr1   pixel_valuesc                    |j                         \  }}}}| j                  |      j                  d      j                  dd      }| j	                  |      }| j
                  j                  rY| j                  || j                  z  || j                  z  | j
                  j                  |j                  |j                        }n| j                  | j                        }||z   }|S )NrH   r   )r   r   rK   )sizerx   r   	transposerz   r_   r|   r   ru   rD   r   rK   r~   rq   )r+   r   _r   r   rQ   	pos_embeds          r,   rT   zAimv2VisionEmbeddings.forward   s    *//11fe((6>>qAKKAqQm4;;  ??$//)(++11$++#)) @ I //0A0ABI%	1r1   )r2   r3   r4   r   r?   staticmethodr6   rM   Tensorr   rT   rX   rY   s   @r,   rm   rm   v   s]    j0 j !$'%u}}e	e e ELL U\\ r1   rm   c            	            e Zd Zdef fdZ	 	 	 d	dej                  dz  dej                  dz  dej                  dz  dej                  fdZ	 xZ
S )
Aimv2TextEmbeddingsr_   c                 N   t         |           |j                  }t        j                  |j
                  |      | _        t        j                  |j                  |      | _        | j                  dt        j                  |j                        j                  d      d       y )Nrq   rr   Frs   )r>   r?   rD   r   r}   
vocab_sizetoken_embeddingmax_position_embeddingsr~   r   r6   r   r   )r+   r_   r   rF   s      r,   r?   zAimv2TextEmbeddings.__init__   s    &&	!||F,=,=yI"$,,v/M/My"Y 	ELL)G)GHOOPWXej 	 	
r1   N	input_idsrq   inputs_embedsr$   c                 8   ||j                   d   n|j                   d   }| j                  j                  j                   d   }||kD  rt        d| d|       || j                  d d d |f   }|| j                  |      }| j                  |      }||z   }|S )NrI   r   zRSequence length must be less than max_position_embeddings (got `sequence length`: z and max_position_embeddings: )rV   r~   rB   
ValueErrorrq   r   )r+   r   rq   r   
seq_lengthmax_position_embeddingposition_embeddings
embeddingss           r,   rT   zAimv2TextEmbeddings.forward   s     -6,AY__R(}GZGZ[]G^
!%!8!8!?!?!E!Ea!H..d,<=S<TV 
 ,,Q^<L  00;M"55lC"%88
r1   NNN)r2   r3   r4   r   r?   r6   
LongTensorr7   r   rT   rX   rY   s   @r,   r   r      sj    

 

 .20426	##d* &&- ((4/	
 
r1   r   modulequerykeyvalueattention_maskscalingdropoutc                    t        j                  ||j                  dd            |z  }|||z   }t        j                  j                  |dt         j                        j                  |j                        }t        j                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )NrI   r   )r   rK   )ptrainingr   rH   )r6   matmulr   r   
functionalsoftmaxrM   rL   rK   r   r   
contiguous)
r   r   r   r   r   r   r   kwargsattn_weightsattn_outputs
             r,   eager_attention_forwardr      s     <<s}}R'<=GL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r1   c            
            e Zd ZdZ fdZ	 ddej                  dej                  dz  deej                  ej                  dz  f   fdZ xZ	S )	Aimv2Attentionz=Multi-headed attention from 'Attention Is All You Need' paperc                 x   t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        | j                  | j                  z  | j                  k7  r&t        d| j                   d| j                   d      | j                  dz  | _	        |j                  | _        d| _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _        y )Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).g      Fr]   )r>   r?   r_   rD   r   num_attention_heads	num_headshead_dimr   scaleattention_dropoutr   	is_causalr   ra   qkv_biask_projv_projq_projout_projrh   s     r,   r?   zAimv2Attention.__init__   s2   ++33$..8==4>>)T^^;MdnnM] ^NN#2'  ]]D(
//iiV__UiiV__UiiV__U		$..$..vWr1   NrQ   r   r$   c           
         |j                   \  }}}| j                  |      }| j                  |      }| j                  |      }	|j	                  ||| j
                  | j                        j                  dd      }|j	                  ||| j
                  | j                        j                  dd      }|	j	                  ||| j
                  | j                        j                  dd      }	t        j                  | j                  j                  t              }
 |
| |||	|| j                  | j                  | j                  sdn| j                         \  }}|j#                  |||      j%                         }| j'                  |      }||fS )z#Input shape: Batch x Time x Channelr   rH           )r   r   r   )rV   r   r   r   viewr   r   r   r   get_interfacer_   _attn_implementationr   r   r   r   r   reshaper   r   )r+   rQ   r   r   
batch_sizer   r   queriesr/   valuesattention_interfacer   r   s                r,   rT   zAimv2Attention.forward   sW    -:,?,?)
J	++m,{{=)]+,,z:t~~t}}U__`acdeyyZOYYZ[]^_ZT^^T]]S]]^_abc(?(M(MKK,,.E)
 %8nnJJ#}}C$,,	%
!\ "))*j)LWWYmmK0L((r1   rj   )
r2   r3   r4   r5   r?   r6   r   r.   rT   rX   rY   s   @r,   r   r      sV    GX, /3$)||$) t+$)
 
u||U\\D00	1$)r1   r   c            	            e Zd Zdef fdZ	 d	dej                  dej                  dz  dee   dej                  fdZ	 xZ
S )
Aimv2EncoderLayerr_   c                     t         |           t        |      | _        t	        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y rj   )r>   r?   r   	attentionr[   ffnr<   rD   ry   	rms_norm1	rms_norm2rh   s     r,   r?   zAimv2EncoderLayer.__init__'  sZ    '/F#%f&8&8&:M:MN%f&8&8&:M:MNr1   NrQ   r   r   r$   c                     | j                  |      } | j                  d||d|\  }}||z   }| j                  |      }| j                  |      }||z   }|S )N)rQ   r   r9   )r   r   r   r   )r+   rQ   r   r   norm_hidden_statesr   r   
mlp_outputs           r,   rT   zAimv2EncoderLayer.forward.  sl     "^^M:'r6HYgrkqrQ%3!^^M:XX01
%
2r1   rj   )r2   r3   r4   r   r?   r6   r   r   r   rT   rX   rY   s   @r,   r   r   &  sY    O0 O /3|| t+ +,	
 
r1   r   c                   j     e Zd ZdZdef fdZe	 d	dej                  dz  de	e
   defd       Z xZS )
Aimv2Encoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`Aimv2EncoderLayer`].

    Args:
        config: Aimv2Config
    r_   c                     t         |           || _        t        j                  t        |j                        D cg c]  }t        |       c}      | _        d| _	        y c c}w )NF)
r>   r?   r_   r   
ModuleListrangenum_hidden_layersr   layersgradient_checkpointing)r+   r_   r   rF   s      r,   r?   zAimv2Encoder.__init__H  sO    mmfNfNfHg$h1%6v%>$hi&+# %is   A#Nr   r   r$   c                 T    |}| j                   D ]  } |||fi |} t        |      S )N)last_hidden_state)r   r   )r+   r   r   r   rQ   encoder_layers         r,   rT   zAimv2Encoder.forwardO  sC     &![[ 	M) M	 ??r1   rj   )r2   r3   r4   r5   r   r?   r   r6   r   r   r   r   rT   rX   rY   s   @r,   r   r   ?  s_    ,{ ,  /3@ t+@ +,	@
 
@ @r1   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Aimv2AttentionPoolingHeadr_   c                 &   t         |           |j                  | _        |j                  | _        t        j                  | j                  | j                  |j                        | _        t        j                  | j                  | j                  |j                        | _	        t        j                  t        j                  dd| j                              | _        t        j                  | j                  | j                  d      | _        y )Nr]   r   T)r>   r?   rD   r   r   r   ra   r   r   r   r@   r6   zeros	cls_tokenoutput_projrh   s     r,   r?   z"Aimv2AttentionPoolingHead.__init__b  s    !--33ii 0 0$2B2BYii 0 0$2B2BYekk!Q8H8H&IJ99T%5%5t7G7GdSr1   rQ   r$   c                    |j                   \  }}}| j                  j                  |dd      }| j                  |      j	                  ||| j
                  || j
                  z        }| j                  |      j	                  ||| j
                  || j
                  z        }|j	                  |d| j
                  || j
                  z        }|j                  dddd      }|j                  dddd      }|j                  dddd      }t        j                  |||      }	|	j                  dd      j	                  |d|      }	|	j                  d      }	| j                  |	      }
|
S )NrI   r   r   rH   r   r   )rV   r   r   r   r   r   r   permuteFscaled_dot_product_attentionr   rO   r   )r+   rQ   r   seq_len
hidden_dimr   r   r   r   r   outputs              r,   rT   z!Aimv2AttentionPoolingHead.forwardm  sH   *7*=*='
GZNN))*b"=	kk-(00WdnnV`dhdrdrVrsM*22:wXbfjftftXtu!!*at~~A]^kk!Q1%aAq)aAq)44UCG!++Aq199*aT!&&1&-!!+.r1   )	r2   r3   r4   r   r?   r6   r   rT   rX   rY   s   @r,   r   r   a  s-    	T0 	TU\\ ell r1   r   c                   v     e Zd ZU dZeed<   dZdZdZg dZ	dZ
dZdZ ej                          fd       Z xZS )Aimv2PreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models. The model is only intended for inference and doesn't support finetuning.
    r_   aimv2)imageT)r   r   rm   r   c                 $   t         |   |       t        |d      rYt        |j                  t
        j                        r4t        j                  |j                  t        j                  d             y y t        |t              r7t        j                  |j                  d| j                  j                         y t        |t               rZt        j"                  |j$                  t'        j(                  |j$                  j*                  d         j-                  d             y t        |t.              rZt        j"                  |j$                  t'        j(                  |j$                  j*                  d         j-                  d             y y )Nlogit_scaleg$I$I,@r   )rO   stdrI   rr   )r>   _init_weightshasattr
isinstancer  r   r@   init	constant_mathlogr   normal_r   r_   initializer_rangerm   copy_rq   r6   r   rV   r   r   )r+   r   rF   s     r,   r
  z"Aimv2PreTrainedModel._init_weights  s   f%6=)&,,bll;v11488H3EF < 9:LL))9V9VW 56JJv**ELL9L9L9R9RSU9V,W,^,^_f,gh 34JJv**ELL9L9L9R9RSU9V,W,^,^_f,gh 5r1   )r2   r3   r4   r5   r   r8   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attnr6   no_gradr
  rX   rY   s   @r,   r  r    sY    
 !&*# NU]]_
i 
ir1   r  zL
    The Vision model from AIMv2 without any head or projection on top.
    )custom_introc                        e Zd ZU eed<   dZeedZdef fdZ	de
j                  fdZ ed      ed	ee   defd
              Z xZS )Aimv2VisionModelr_   r   rQ   
attentionsc                 6   t         |   |       || _        t        |      | _        t        |      | _        t        |j                  |j                        | _
        |j                  | _        | j                  rt        |      | _        | j                          y rj   )r>   r?   r_   rm   r   r   encoderr<   rD   ry   rz   use_headr   head	post_initrh   s     r,   r?   zAimv2VisionModel.__init__  sq     /7#F+$V%7%79L9LM==1&9DIr1   r$   c                 .    | j                   j                  S rj   )r   rx   r0   s    r,   get_input_embeddingsz%Aimv2VisionModel.get_input_embeddings  s    ***r1   Ftie_last_hidden_statesr   c                     | j                  |      } | j                  dd|i|}|j                  }| j                  |      }| j                  r| j                  |      nd}t        ||      S )a3  
        Examples:

        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, Siglip2VisionModel

        >>> model = Aimv2VisionModel.from_pretrained("apple/aimv2-large-patch14-native")
        >>> processor = AutoProcessor.from_pretrained("apple/aimv2-large-patch14-native")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

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

        >>> outputs = model(**inputs)
        >>> last_hidden_state = outputs.last_hidden_state
        >>> pooled_output = outputs.pooler_output  # pooled features
        ```r   Nr   pooler_outputr9   )r   r"  r   rz   r#  r$  r   )r+   r   r   rQ   encoder_outputsr   r,  s          r,   rT   zAimv2VisionModel.forward  sz    : 5+74<< ,
',
,

 ,== MM*;<8<		"344)/'
 	
r1   )r2   r3   r4   r   r8   main_input_namer   r   _can_record_outputsr?   r   Moduler'  r   r   r   r   r   rT   rX   rY   s   @r,   r  r    sv     $O*$
0 +bii + u5*
 +,*
 
$	*
  6*
r1   r  zJ
    The text model from AIMv2 without any head or projection on top.
    c            	            e Zd ZdZeedZdef fdZde	j                  fdZd Z ed	      e	 ddej                   d
z  dee   defd              Z xZS )Aimv2TextModelr   r  r_   c                     t         |   |       || _        t        |      | _        t        |      | _        t        |j                  |j                        | _
        |j                  | _        | j                          y rj   )r>   r?   r_   r   r   r   r"  r<   rD   ry   rz   eos_token_idr%  rh   s     r,   r?   zAimv2TextModel.__init__   sa     -f5#F+$V%7%79L9LM"//r1   r$   c                 .    | j                   j                  S rj   r   r   r0   s    r,   r'  z#Aimv2TextModel.get_input_embeddings  s    ...r1   c                 &    || j                   _        y rj   r6  )r+   r   s     r,   set_input_embeddingsz#Aimv2TextModel.set_input_embeddings  s    */'r1   Fr(  Nr   r   c                    | j                  |      }|j                  \  }}}t        j                  |t        j                  |j
                        }|j                  d      j                  |d      }	|t        | j                  ||	||d       } | j                  d	||d|}
|
j                  }| j                  |      }|t        j                  |j                  d   |j
                        |j                  t        j                  |j
                        | j                  k(  j                         j!                  d      f   }t#        ||      S )
Nr   r   rI   )r_   input_embedsrq   r   cache_positionpast_key_values)r   r   )r   r   r+  r9   )r   rV   r6   r   longr   	unsqueezer   r   r_   r"  r   rz   rL   r   r4  argmaxr   )r+   r   r   r   rQ   r   r   r   r;  rq   r-  r   pooled_outputs                r,   rT   zAimv2TextModel.forward  sN    	2!.!4!4
GQgUZZH\H\]%//299*bI%/{{*)-- $N '$,, 
')
 
 ,== MM*;< *LL*003<M<T<TU\\		2C2J2J\KtO`O``eegnnsunvx

 */'
 	
r1   rj   )r2   r3   r4   r.  r   r   r/  r   r?   r   r0  r'  r8  r   r   r6   r   r   r   r   rT   rX   rY   s   @r,   r2  r2    s     "O +$
	 	/bii /0 u5 /3'
 t+'
 +,	'

 
$'
  6'
r1   r2  tensorr$   c                     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
    rH   rI   T)r   rJ   g      ?)r6   rN   sum)rA  square_tensor
sum_tensornormed_tensors       r,   _get_vector_normrG  =  s<    
 IIfa(M=b$?JIIj#.Mr1   c                       e Zd ZU eed<   g dZdZdef fdZee		 	 dde
j                  de
j                  dz  de
j                  dz  d	ee   d
eez  f
d              Zee		 dde
j"                  ded	ee   d
eez  fd              Ze	e	 	 	 dde
j(                  dz  de
j"                  dz  de
j                  dz  d	ee   d
ef
d              Z xZS )
Aimv2Modelr_   )r   r   rm   Tc                    t         |   |       |j                  | _        |j                  j                  | _        |j                  j                  | _        t        j                  |j                        | _
        t        j                  |j                        | _        t        j                  | j
                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j"                  t%        j&                  | j(                  j*                              | _        t/        j0                  |j2                        | _        | j7                          y )NFr]   )r>   r?   projection_dimvision_configrD   vision_embed_dimtext_configtext_embed_dimr  _from_configvision_modelr2  
text_modelr   ra   visual_projectiontext_projectionr@   r6   rA  r_   logit_scale_init_valuer  r  r  max_logit_scalemax_log_logit_scaler%  rh   s     r,   r?   zAimv2Model.__init__N  s     $33 & 4 4 @ @$00<<,99&:N:NO(55f6H6HI!#4+@+@$BUBU\a!b!yy)<)<d>Q>QX]^<<T[[5W5W(XY#'88F,B,B#C r1   Nr   r   rq   r   r$   c                 x     | j                   d|||dd|}|j                  }| j                  |      |_        |S )a
  
        Examples:

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

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

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

        >>> with torch.inference_mode():
        ...     text_features = model.get_text_features(**inputs)
        ```T)r   r   rq   return_dictr9   )rR  r,  rT  )r+   r   r   rq   r   text_outputsr@  s          r,   get_text_featureszAimv2Model.get_text_features`  sV    0 4C4?? 4
)%	4

 4
 %22%)%9%9-%H"r1   r   interpolate_pos_encodingc                 v     | j                   d||dd|}|j                  }| j                  |      |_        |S )a  
        Examples:

        ```python
        >>> import torch
        >>> from transformers import AutoProcessor, Aimv2Model
        >>> from transformers.image_utils import load_image

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

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = load_image(url)

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

        >>> with torch.inference_mode():
        ...     image_features = model.get_image_features(**inputs)
        ```T)r   r\  rY  r9   )rQ  r,  rS  )r+   r   r\  r   vision_outputsr@  s         r,   get_image_featureszAimv2Model.get_image_features  sU    6 6GT5F5F 6
%%=6
 	6
 '44'+'='=m'L$r1   c                     | j                   dd|i|} | j                  d||d|}|j                  }| j                  |      }|j                  }| j	                  |      }|t        |      z  }|t        |      z  }| j                  j                  d| j                        j                         j                  |j                        }	|	|z  |j                         z  }
|
j                         }t        ||
||||      S )a  
        Examples:

        ```python
        >>> from PIL import Image
        >>> import httpx
        >>> from io import BytesIO
        >>> from transformers import AutoProcessor, Aimv2Model

        >>> model = Aimv2Model.from_pretrained("apple/aimv2-large-patch14-224-lit")
        >>> processor = AutoProcessor.from_pretrained("apple/aimv2-large-patch14-224-lit")

        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> with httpx.stream("GET", url) as response:
        ...     image = Image.open(BytesIO(response.read()))

        >>> 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
        ```r   )r   r   r   )r   r   r    r!   r"   r#   r9   )rQ  rR  r,  rS  rT  rG  r  clamprW  exprL   r   tr   )r+   r   r   r   r   r^  rZ  r!   r    r  r   r   s               r,   rT   zAimv2Model.forward  s'   B 6GT5F5F 6
%6
6

 4C4?? 4
)4
 4
 &33--l;"00**;7 $&6|&DD!$4[$AA&&,,S$2J2JKOOQTTU`UgUgh&48HH*,,.-+#%* .
 	
r1   )NN)Fr   )r2   r3   r4   r   r8   r  r  r?   r   r   r6   r   r   r   r.   r   r[  r7   boolr_  r   r   rT   rX   rY   s   @r,   rI  rI  H  sn   ]{ $  /3,0	 <<  t+  llT)	 
 +,  
+	+    D  */"''" #'" +,	"
 
+	+"  "H  .215.2	?
##d*?
 ''$.?
 t+	?

 +,?
 
?
  ?
r1   rI  )r  rI  r  r2  )r   )=r  collections.abcr   dataclassesr   typingr   r6   torch.nn.functionalr   r   r    r   r  activationsr	   integrationsr
   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   configuration_aimv2r   r   r   r   r0  r<   r[   rm   r   r   floatr   r   r   r   r   r  r  r2  rG  rI  __all__r9   r1   r,   <module>rv     s   ,  $ !      & ! 7 / 9 K F & V V / P P  
+  
   
F Y'J299 J (J(ryy  1BII 1h%")) %^ %II%<<% 
% <<	%
 LL4'% % %.:)RYY :)z2 2@299 @D		 D i? i iD 
E
+ E

E
P 
B
) B

B
JU\\ ell  b
% b
 b
J Wr1   