
    ^jN                     X   d Z ddl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 ddlmZ ddlmZmZmZ ddlmZ ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ ddl0m1Z1  ed      e G d de+                    Z2 ed      e G d de*                    Z3 ed      e G d de)                    Z4 G d de/      Z5 G d  d!e'      Z6 G d" d#e&      Z7 G d$ d%ejp                        Z9 G d& d'e#      Z: G d( d)e-      Z; G d* d+e      Z< G d, d-e.      Z= G d. d/ejp                        Z>e G d0 d1e             Z? ed23       G d4 d5e?             Z@ ed63       G d7 d8e?             ZAe G d9 d:e"             ZBg d;ZCy)<z%Pytorch implementation of AIMv2 Model    N)strict)nn   )initialization)PreTrainedConfig)create_causal_mask)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPooling)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuple)merge_with_config_defaults)capture_outputs   )	CLIPModelCLIPTextEmbeddings_get_vector_norm)LlamaMLPLlamaRMSNorm)SiglipConfigSiglipTextConfigSiglipVisionConfig)SiglipAttentionSiglipEncoderSiglipOutput)&build_2d_sinusoidal_position_embeddingz!apple/aimv2-large-patch14-224-lit)
checkpointc                       e Zd ZU dZdZeed<   dZeed<   dZeed<   dZ	eed	<   d
Z
eee   z  eeef   z  ed<   dZeed<   dZeez  ed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<    e       Zy)Aimv2VisionConfiga  
    use_head (`str`, *optional*, defaults to `True`):
        Whether to use Attention Pooling Head or Not.
    is_native (`str`, *optional*, defaults to `False`):
        Whether to use ckpt trained for image native resolution or not.

    Example:

    ```python
    >>> from transformers import SiglipVisionConfig, SiglipVisionModel

    >>> # Initializing a Aimv2VisionConfig with apple/aimv2-large-patch14-224 style configuration
    >>> configuration = Aimv2VisionConfig()

    >>> # Initializing a Aimv2VisionModel (with random weights) from the apple/aimv2-large-patch14-224 style configuration
    >>> model = Aimv2VisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```i   hidden_sizei   intermediate_size   num_hidden_layers   num_attention_heads   
patch_sizeh㈵>rms_norm_eps        attention_dropoutFqkv_biasmlp_biassilu
hidden_act{Gz?initializer_rangeTuse_head	is_nativeN)__name__
__module____qualname____doc__r#   int__annotations__r$   r&   r(   r*   listtupler,   floatr.   r/   boolr0   r2   strr4   r5   r6   AttributeErrorlayer_norm_eps     r/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/aimv2/modular_aimv2.pyr"   r"   )   s    * K!s!s  46Jd3i%S/16L%%(us{(HdHdJ#u#HdIt#%NrE   r"   c                       e Zd ZU dZeed<   dZeed<   dZeed<   dZeed<   d	Z	eed
<   dZ
eed<   dZeed<   dZeed<   dZeed<   dZeed<   dZeed<    e       Z e       Z e       Z e       Zd Zy)Aimv2TextConfigi   
vocab_sizei   r#   i   r$      r&      r(   M   max_position_embeddingsr1   r2   r+   r,   Fr/   r0   r3   r4   c                 .    t        j                  di | y )NrD   )r   __post_init__)selfkwargss     rF   rO   zAimv2TextConfig.__post_init__e   s    &&00rE   N)r7   r8   r9   rI   r;   r<   r#   r$   r&   r(   rM   r2   rA   r,   r?   r/   r@   r0   r4   rB   bos_token_idpad_token_idrC   projection_sizerO   rD   rE   rF   rH   rH   R   s     JK!s!s  #%S%JL%HdHd#u#!#L!#L#%N$&O1rE   rH   c                   <    e Zd ZU dZdZeed<   dZeed<   dZ	eed<   y)	Aimv2Configa  
    max_logit_scale (`float`, *optional*, defaults to `100.0`):
        The maximum logit scale to use

    Example:

    ```python
    >>> from transformers import Aimv2Config, Aimv2Model

    >>> # Initializing a Aimv2Config with apple/aimv2-large-patch14-224-lit style configuration
    >>> configuration = Aimv2Config()

    >>> # Initializing a Aimv2Model (with random weights) from the apple/aimv2-large-patch14-224-lit style configuration
    >>> model = Aimv2Model(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config

    >>> # We can also initialize a Aimv2Config from a Aimv2TextConfig and a Aimv2VisionConfig
    >>> from transformers import Aimv2TextConfig, Aimv2VisionConfig

    >>> # Initializing a AIMv2Text and AIMv2Vision configuration
    >>> config_text = Aimv2TextConfig()
    >>> config_vision = Aimv2VisionConfig()

    >>> config = Aimv2Config(text_config=config_text, vision_config=config_vision)
    ```i   projection_dimg/L
F@logit_scale_init_valueg      Y@max_logit_scaleN)
r7   r8   r9   r:   rW   r;   r<   rX   r?   rY   rD   rE   rF   rV   rV   i   s(    8 NC$*E*"OU"rE   rV   c                       e Zd Zy)Aimv2OutputNr7   r8   r9   rD   rE   rF   r[   r[          rE   r[   c                       e Zd Zy)Aimv2RMSNormNr\   rD   rE   rF   r_   r_      r]   rE   r_   c                       e Zd Zy)Aimv2MLPNr\   rD   rE   rF   ra   ra      r]   rE   ra   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Aimv2VisionEmbeddingsconfigc                 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strider   position_ids   F)
persistent)super__init__rd   r*   r   Conv2dnum_channelsr#   patch_embedr_   r,   rms_norm
image_sizer6   	Embeddingposition_embeddingregister_buffertorcharangeexpand)rP   rd   num_patches	__class__s      rF   rn   zAimv2VisionEmbeddings.__init__   s     ++99!3!3ARAR[a[l[l
 %V%7%79L9LM((F,=,==!C{{$$&(ll;@R@R&SD#^U\\+-F-M-Mg-VchirE   pixel_valuesreturnc                 X   |j                         \  }}}}| j                  |      j                  d      j                  dd      }| j	                  |      }| j
                  j                  rt        || j                  z  || j                  z  | j
                  j                  |j                  |j                        }|j                  d   dz  }t        j                  |d|d f   |dd |f   gd      }|j                  d      }n| j!                  | j"                        }||z   }|S )Nr   rj   )heightwidth	embed_dimdevicedtyperk   .dimr   )sizerq   flatten	transposerr   rd   r6   r   r*   r#   r   r   shaperw   cat	unsqueezeru   rh   )rP   r|   _r   r   hidden_states	pos_embedhalfs           rF   forwardzAimv2VisionEmbeddings.forward   s   *//11fe((6>>qAKKAqQm4;;  >0t.++11$++#))I ??2&!+D		9S$%Z#8)C$J:O"PVXYI!++A.I//0A0ABI%	1rE   	r7   r8   r9   r"   rn   rw   Tensorr   __classcell__r{   s   @rF   rc   rc      s-    j0 jELL U\\ rE   rc   c                       e Zd Zy)Aimv2TextEmbeddingsNr\   rD   rE   rF   r   r      r]   rE   r   c                        e Zd Z fdZ xZS )Aimv2Attentionc                    t         |   |       t        j                  | j                  | j                  |j
                        | _        t        j                  | j                  | j                  |j
                        | _        t        j                  | j                  | j                  |j
                        | _        t        j                  | j                  | j                  |j
                        | _	        y )Nbias)
rm   rn   r   Linearr   r/   k_projv_projq_projout_projrP   rd   r{   s     rF   rn   zAimv2Attention.__init__   s     iiV__UiiV__UiiV__U		$..$..vWrE   )r7   r8   r9   rn   r   r   s   @rF   r   r      s    X XrE   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 )
Aimv2EncoderLayerrd   c                     t         |           t        |      | _        t	        |      | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        y N)rm   rn   r   	attentionra   ffnr_   r#   r,   	rms_norm1	rms_norm2r   s     rF   rn   zAimv2EncoderLayer.__init__   sZ    '/F#%f&8&8&:M:MN%f&8&8&:M:MNrE   Nr   attention_maskrQ   r}   c                     | j                  |      } | j                  d||d|\  }}||z   }| j                  |      }| j                  |      }||z   }|S )N)r   r   rD   )r   r   r   r   )rP   r   r   rQ   norm_hidden_statesattn_outputr   
mlp_outputs           rF   r   zAimv2EncoderLayer.forward   sl     "^^M:'r6HYgrkqrQ%3!^^M:XX01
%
2rE   r   )r7   r8   r9   r"   rn   rw   r   r   r   r   r   r   s   @rF   r   r      sY    O0 O /3|| t+ +,	
 
rE   r   c                       e Zd Zy)Aimv2EncoderNr\   rD   rE   rF   r   r      r]   rE   r   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )Aimv2AttentionPoolingHeadrd   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   rj   T)rm   rn   r#   r(   	num_headsr   r   r/   r   r   	Parameterrw   zeros	cls_tokenoutput_projr   s     rF   rn   z"Aimv2AttentionPoolingHead.__init__   s    !--33ii 0 0$2B2BYii 0 0$2B2BYekk!Q8H8H&IJ99T%5%5t7G7GdSrE   r   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 )Nrk   rj   r   r   r   r   )r   r   ry   r   reshaper   r   permuteFscaled_dot_product_attentionr   meanr   )rP   r   
batch_sizeseq_len
hidden_dimr   keyvaluequeryr   outputs              rF   r   z!Aimv2AttentionPoolingHead.forward   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&-!!+.rE   r   r   s   @rF   r   r      s-    	T0 	TU\\ ell rE   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.
    rd   aimv2)imageT)r   r   rc   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-   )r   stdrk   ri   )rm   _init_weightshasattr
isinstancer   r   r   init	constant_mathlogr   normal_r   rd   r4   rc   copy_rh   rw   rx   r   ry   r   )rP   moduler{   s     rF   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 5rE   )r7   r8   r9   r:   rV   r<   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_sdpa_supports_flash_attn_supports_flex_attnrw   no_gradr   r   r   s   @rF   r   r     sY    
 !&*# NU]]_
i 
irE   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 ed      ed	ee   defd
                     Z xZS )Aimv2VisionModelrd   r|   r   
attentionsc                 6   t         |   |       || _        t        |      | _        t        |      | _        t        |j                  |j                        | _
        |j                  | _        | j                  rt        |      | _        | j                          y r   )rm   rn   rd   rc   
embeddingsr   encoderr_   r#   r,   rr   r5   r   head	post_initr   s     rF   rn   zAimv2VisionModel.__init__=  sq     /7#F+$V%7%79L9LM==1&9DIrE   r}   c                 .    | j                   j                  S r   )r   rq   rP   s    rF   get_input_embeddingsz%Aimv2VisionModel.get_input_embeddingsK  s    ***rE   Ftie_last_hidden_statesrQ   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
        ```inputs_embedsNlast_hidden_statepooler_outputrD   )r   r   r   rr   r5   r   r   )rP   r|   rQ   r   encoder_outputsr   r   s          rF   r   zAimv2VisionModel.forwardN  sz    < 5+74<< ,
',
,

 ,== MM*;<8<		"344)/'
 	
rE   )r7   r8   r9   r"   r<   main_input_namer   r   _can_record_outputsrn   r   Moduler   r   r   r   r   r   r   r   r   r   s   @rF   r   r   0  s~     $O*$
0 +bii +  E2*
 +,*
 
$	*
  3  *
rE   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 ed	      e	 ddej"                  d
z  dee   defd                     Z xZS )Aimv2TextModel	input_idsr   rd   c                     t         |   |       || _        t        |      | _        t        |      | _        t        |j                  |j                        | _
        |j                  | _        | j                          y r   )rm   rn   rd   r   r   r   r   r_   r#   r,   rr   eos_token_idr   r   s     rF   rn   zAimv2TextModel.__init__  sa     -f5#F+$V%7%79L9LM"//rE   r}   c                 .    | j                   j                  S r   r   token_embeddingr   s    rF   r   z#Aimv2TextModel.get_input_embeddings  s    ...rE   c                 &    || j                   _        y r   r   )rP   r   s     rF   set_input_embeddingsz#Aimv2TextModel.set_input_embeddings  s    */'rE   Fr   Nr   rQ   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 )
N)r   r   r   rk   )rd   r   rh   r   past_key_values)r   r   )r   r   r   rD   )r   r   rw   rx   longr   r   ry   r   rd   r   r   rr   tor;   r   argmaxr   )rP   r   r   rQ   r   r   r   r   rh   r   r   pooled_outputs               rF   r   zAimv2TextModel.forward  sK    	2!.!4!4
GQ||G5::mFZFZ[#--a077
BG%/{{+)- $N '$,, 
')
 
 ,== MM*;< *LL*003<M<T<TU\\		2C2J2J\KtO`O``eegnnsunvx

 */'
 	
rE   r   )r7   r8   r9   r   r   r   r   rH   rn   r   r   r   r   r   r   r   rw   r   r   r   r   r   r   r   s   @rF   r   r   ~  s     "O +$
	 	/bii /0  E2 /3&
 t+&
 +,	&

 
$&
  3  &
rE   r   c                       e Zd ZdZde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y)
Aimv2ModelTrd   c                    t        j                  | |       |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   rn   rW   vision_configr#   vision_embed_dimtext_configtext_embed_dimr   _from_configvision_modelr   
text_modelr   r   visual_projectiontext_projectionr   rw   tensorrd   rX   r   r   r   rY   max_log_logit_scaler   )rP   rd   s     rF   rn   zAimv2Model.__init__  s     v.$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 rE   Nr   r|   r   rQ   r}   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-   )logits_per_imagelogits_per_texttext_embedsimage_embedstext_model_outputvision_model_outputrD   )r  r  r   r  r  r   r   clampr  expr  r   tr[   )rP   r   r|   r   rQ   vision_outputstext_outputsr  r  r   r  r  s               rF   r   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*,,.-+#%* .
 	
rE   )NNN)r7   r8   r9   r   rV   rn   r   r   rw   
LongTensorFloatTensorr   r   r   r[   r   rD   rE   rF   r  r    s    { $  .215.2	?
##d*?
 ''$.?
 t+	?

 +,?
 
?
  ?
rE   r  )rV   r"   rH   r   r  r   r   )Dr:   r   rw   torch.nn.functionalr   
functionalr   huggingface_hub.dataclassesr    r   r   configuration_utilsr   masking_utilsr   modeling_layersr	   modeling_outputsr
   r   modeling_utilsr   processing_utilsr   utilsr   r   r   utils.genericr   utils.output_capturingr   clip.modeling_clipr   r   r   llama.modeling_llamar   r   siglip.configuration_siglipr   r   r   siglip.modeling_siglipr   r   r   vit_mae.modeling_vit_maer   r"   rH   rV   r[   r_   ra   r   rc   r   r   r   r   r   r   r   r   r  __all__rD   rE   rF   <module>r6     s   ,     .  & 3 / 9 K - & I I 7 5 P P 9 \ \ Q Q M >?$&* $&  @$&N >?1& 1  @1* >?#, #  @#D	, 		< 		x 	%BII %P	, 	X_ X2 2	= 			 D i? i iD 
F
+ F

F
R 
B
) B

B
J V
 V
 V
rrE   