
    ^j?=                        d dl mZ d dl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 ddlmZmZmZmZmZmZ ddlm Z  ddl!m"Z"m#Z#  ejH                  e%      Z& ed      e G d de                    Z' G d de      Z( G d de"      Z) G d de      Z* G d de      Z+ G d de      Z, G d de      Z-e G d d e             Z. G d! d"e      Z/g d#Z0y)$    )CallableN)strict   )initialization)PreTrainedConfig)BaseModelOutputBaseModelOutputWithPooling)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringlogging   )CLIPMLPCLIPAttentionCLIPEncoderCLIPEncoderLayerCLIPVisionEmbeddingsCLIPVisionModel)eager_attention_forward)VisionRotaryEmbeddingapply_rotary_pos_emb_visionz&DeepGlint-AI/mlcd-vit-bigG-patch14-336)
checkpointc                      e Zd ZU dZdZ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d<   dZeed<   dZeee   z  eeef   z  ed<   dZeee   z  eeef   z  ed<   dZeed<   dZeed<   dZeez  ed<   dZeed<   dZeed<   y)MLCDVisionConfigav  
    num_key_value_groups (`int`, *optional*, defaults to 1):
        Number of key-value groups used in Attention.

    Example:

    ```python
    >>> from transformers import MLCDVisionConfig, MLCDVisionModel

    >>> # Initializing a MLCDVisionConfig with DeepGlint-AI/mlcd-vit-bigG-patch14-336 style configuration
    >>> configuration = MLCDVisionConfig()

    >>> # Initializing a MLCDVisionModel (with random weights) from the DeepGlint-AI/mlcd-vit-bigG-patch14-336 style configuration
    >>> model = MLCDVisionModel(configuration)

    >>> # Accessing the model configuration
    >>> configuration = model.config
    ```mlcd_vision_modelvision_configi  hidden_sizei    intermediate_size0   num_hidden_layers   num_attention_heads   num_key_value_groupsr   num_channelsiP  
image_size   
patch_sizegelu
hidden_actgh㈵>layer_norm_eps        attention_dropoutg{Gz?initializer_range      ?initializer_factorN)__name__
__module____qualname____doc__
model_typebase_config_keyr   int__annotations__r    r"   r$   r&   r'   r(   listtupler*   r,   strr-   floatr/   r0   r2        p/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/mlcd/modular_mlcd.pyr   r   )   s    & %J%OK!s!s!! !#!L#47Jd3i%S/1746Jd3i%S/16J NE %(us{(#u# ##r@   r   c                       e Zd Zy)MLCDMLPNr3   r4   r5   r?   r@   rA   rC   rC   Q       r@   rC   c                       e Zd Zy)MLCDRotaryEmbeddingNrD   r?   r@   rA   rG   rG   U   rE   r@   rG   c                   \     e Zd Zdef fdZdej                  dej                  fdZ xZ	S )MLCDVisionEmbeddingsconfigc                 (    t         |   |       | `y N)super__init__position_embeddingselfrJ   	__class__s     rA   rN   zMLCDVisionEmbeddings.__init__Z   s     #r@   pixel_valuesreturnc                 T   |j                   d   }| j                  j                  j                  }| j                  |j	                  |            }|j                  d      j                  dd      }| j                  j                  |dd      }t        j                  ||gd      }|S )Nr   dtyper   r%   dim)shapepatch_embeddingweightrW   toflatten	transposeclass_embeddingexpandtorchcat)rQ   rS   
batch_sizetarget_dtypepatch_embedsclass_embeds
embeddingss          rA   forwardzMLCDVisionEmbeddings.forward^   s    !''*
++2288++LOO,O,OP#++A.88A>++22:q"EYYl;C
r@   )
r3   r4   r5   r   rN   rc   FloatTensorTensorrj   __classcell__rR   s   @rA   rI   rI   Y   s-    $/ $
E$5$5 
%,, 
r@   rI   c                        e Zd ZdZdef fdZ	 ddej                  deej                  ej                  f   dej                  dz  de	e
   d	eej                  ej                  dz  f   f
d
Z xZS )MLCDAttentionzMulti-headed attention with RoPE. Refer to papers:
    - Attention is all you need:
        https://huggingface.co/papers/1706.03762
    - RoFormer: Enhanced Transformer with Rotary Position Embedding:
        https://huggingface.co/papers/2104.09864
    rJ   c                 T    t         |   |       |j                  | _        d| _        y )NF)rM   rN   r&   	is_causalrP   s     rA   rN   zMLCDAttention.__init__s   s%     $*$?$?!r@   Nhidden_statesposition_embeddingsattention_maskkwargsrT   c                    |j                   d d \  }}| j                  |      j                  ||| j                  | j                  f      }| j                  |      j                  ||| j                  | j                  f      }| j                  |      j                  ||| j                  | j                  f      }	|d   j                  d      j                         }
|d   j                  d      j                         }t        |||
|      \  }}|j                  dddd      j                         }|j                  dddd      j                         }|	j                  dddd      j                         }	t        j                  | j                  j                  t               } || |||	|f| j"                  sdn| j$                  | j&                  | j(                  d|\  }}|j                  dddd      j                         }|j+                  ||d      }| j-                  |      }|j                  ddd      j                         }||fS )NrX   r   r%   r   r   r.   )dropoutscalingrr   )r[   q_projreshape	num_headshead_dimk_projv_proj	unsqueezer>   r   permute
contiguousr
   get_interfacerJ   _attn_implementationr   trainingrx   scalerr   viewout_proj)rQ   rs   rt   ru   rv   re   
seq_lengthquery_states
key_statesvalue_statescossinattention_interfaceattn_outputattn_weightss                  rA   rj   zMLCDAttention.forwardx   s;    "/!4!4Sb!9
J {{=199:zSWSaSacgcpcp:qr[[/77ZQUQ_Q_aeanan8op
{{=199:zSWSaSacgcpcp:qr "!$..q1779!!$..q1779#>|ZY\^a#b j $++Aq!Q7BBD''1a3>>@
#++Aq!Q7BBD(?(M(MKK,,.E)
 %8
%
  $}}C$,,JJnn
%
 
%
!\ "))!Q15@@B!&&z:rBmmK0!))!Q2==?L((r@   rL   )r3   r4   r5   r6   r   rN   rc   rl   r<   r   r   rj   rm   rn   s   @rA   rp   rp   k   s    /  /3	,)||,) #5<<#=>,) t+	,)
 +,,) 
u||U\\D00	1,)r@   rp   c                        e Zd Zdef fdZ	 d
dej                  deej                  ej                  f   dej                  dz  dee	   deej                     f
d	Z xZS )MLCDEncoderLayerrJ   c                 D    t         |   |       t        |      | _        y rL   )rM   rN   rp   	self_attnrP   s     rA   rN   zMLCDEncoderLayer.__init__   s     &v.r@   Nrs   rt   ru   rv   rT   c                     |}| j                  |      } | j                  d|||d|\  }}||z   }|}| j                  |      }| j                  |      }||z   }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`):
                Input to the layer of shape `(batch, seq_len, embed_dim)`.
                Represents the hidden states from the previous layer or the input embeddings.
            position_embeddings (`tuple[torch.Tensor, torch.Tensor]`):
                A tuple of two tensors, each of shape `(batch, seq_len, embed_dim)`.
                Represents absolute positional embeddings for the query and key in the attention mechanism.
            attention_mask (`torch.FloatTensor`):
                Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
        )rs   rt   ru   r?   )layer_norm1r   layer_norm2mlp)rQ   rs   rt   ru   rv   residual_s          rA   rj   zMLCDEncoderLayer.forward   s    $ !((7)4>> 
' 3)
 	
q !=0 ((7/ =0r@   rL   )r3   r4   r5   r   rN   rc   rl   r<   r   r   rk   rj   rm   rn   s   @rA   r   r      sz    // / /3	"||" #5<<#=>" t+	"
 +," 
u  	!"r@   r   c                        e Zd ZdZdef fdZ	 ddej                  deej                  ej                  f   dej                  dz  de
e   d	eez  f
d
Z xZS )MLCDEncoderz
    Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
    [`MLCDEncoderLayer`].

    Args:
        config: MLCDVisionConfig
    rJ   c                 $    t         |   |       y)z3Overwrite dummy `MLCDConfig` to `MLCDVisionConfig`.N)rM   rN   rP   s     rA   rN   zMLCDEncoder.__init__   s     r@   Ninputs_embedsrt   ru   rv   rT   c                 V    |}| j                   D ]  } ||||fi |} 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.
            position_embeddings (`tuple[torch.Tensor, torch.Tensor]`):
                A tuple of two tensors, each of shape `(batch, seq_len, embed_dim)`.
                Represents absolute positional embeddings for the query and key in the attention mechanism.
            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)
        )last_hidden_state)layersr   )rQ   r   rt   ru   rv   rs   encoder_layers          rA   rj   zMLCDEncoder.forward   sK    , &![[ 	M)# 	M	 +
 	
r@   rL   )r3   r4   r5   r6   r   rN   rc   rk   r<   rl   r   r   r   rj   rm   rn   s   @rA   r   r      s{    !/ ! /3	!
((!
 #5<<#=>!
 t+	!

 +,!
 
	 !
r@   r   c                   ~     e Zd ZU eed<   dZdgZdZdZdZ	dZ
dZdZeedZ ej"                          fd       Z xZS )MLCDPreTrainedModelrJ   vision_modelr   TF)rs   
attentionsc                    t         |   |       | j                  j                  }t	        |t
              r| j                  j                  }t        j                  |j                  d|j                  dz  |z         t        j                  |j                  j                  |j                  j                  |z         t        j                  |j                  t        j                   |j                  j"                  d         j%                  d             y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                  |j0                  j                  |       yt	        |t2              r| j                  j                  }|j                  j4                  dz  d|j                  j(                  z  dz  z  |z  }d|j                  j4                  z  dz  |z  }t        j                  |j6                  j                  |       t        j                  |j8                  j                  |       yt	        |t:              ro| j                  j                  }|j                  j4                  |j                  j<                  z  dz  dz  |z  }t        j                  |j>                  d|       yt	        |t@              rod|jB                  t        j                   d	|jD                  dt        jF                  
      |jD                  z  z  z  }t        j                  |jH                  |       yy)zInitialize the weightsr.   g      )meanstd)r   rX   )r%   rX   r   r1   r   rV   N)%rM   _init_weightsrJ   r2   
isinstancerI   initnormal_ra   	embed_dimr\   r]   r0   copy_position_idsrc   aranger[   rb   rp   r"   rz   r~   r   r   rC   r   fc1fc2MLCDVisionModelr$   class_pos_embrG   thetarZ   r>   inv_freq)	rQ   modulefactorin_proj_stdout_proj_stdfc_stdpos_emb_stdr   rR   s	           rA   r   z!MLCDPreTrainedModel._init_weights  s    	f%//f23[[33FLL//cv?O?OQU?UX^?^_LL//66FMM<[<[^d<deJJv**ELL9L9L9R9RSU9V,W,^,^_f,gh.[[33F!++T1q6==;Z;Z7Z_c6cdgmmK",,d2f<LLL--;?LL--;?LL--;?LL//\B([[33F!==44d:FMMDcDc@chl?lmpvvK&--333<vEFLL**7LL**<0[[33F!==448Y8YY]^^cggjppKLL--C[I 34fllu||Avzz1TYT_T_/`cicmcm/mnoHJJv1 5r@   )r3   r4   r5   r   r:   base_model_prefix_no_split_modulessupports_gradient_checkpointingaccepts_loss_kwargs_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backendr   rp   _can_record_outputsrc   no_gradr   rm   rn   s   @rA   r   r     se    &+,&*#N"&)#
 U]]_2 2r@   r   c                   b     e Zd Zdef fdZ	 ddej                  dz  dee   de	e
z  fdZ xZS )	r   rJ   c                    t         |   |       t        |j                  |j                  z  dz        | _        t        j                  t        j                  d|j                  |j                  z  dz              | _
        y )Nr   r%   )rM   rN   rG   r   r$   vision_rotary_embeddingnn	Parameterrc   randnr   rP   s     rA   rN   zMLCDVisionModel.__init__4  sh     ':6;M;MQWQkQk;kop;p'q$\\%++a9K9KvOiOi9imn9n*opr@   NrS   rv   rT   c                    |t        d      |j                  d   | j                  j                  z  }|j                  d   | j                  j                  z  }t	        j
                  ||j                        j                  d      j                  d|      }t	        j
                  ||j                        j                  d      j                  |d      }t	        j                  |j                         |j                         gd      }| j                  |      }t	        j                  | j                  |gd      }t	        j                  ||fd      }	|	j                         |	j                         f}
| j!                  |      }| j#                  |      } | j$                  d||
d	|}|d   }|dddddf   }| j'                  |      }t)        ||
      S )a  
        Example:

        ```python
        >>> import httpx
        >>> from io import BytesIO
        >>> from PIL import Image
        >>> from transformers import AutoProcessor, MLCDVisionModel
        >>> model = MLCDVisionModel.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448")
        >>> processor = AutoProcessor.from_pretrained("DeepGlint-AI/mlcd-vit-bigG-patch14-448")

        >>> 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")

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

        >>> features = outputs.last_hidden_state
        >>> print(f"Extracted features shape: {features.shape}")
        >>> print(f"Number of attention layers: {len(outputs.attentions)}")
        >>> print(f"Attention shape: {outputs.attentions[0].shape}")
        ```Nz You have to specify pixel_valuesrX   )devicer%   r   rY   )r   rt   )r   pooler_outputr?   )
ValueErrorr[   rJ   r*   rc   r   r   r   rb   stackr_   r   rd   r   r   r   ri   pre_layrnormencoderpost_layernormr	   )rQ   rS   rv   num_patches_heightnum_patches_widthhpos_idswpos_idspos_idsrotary_pos_embembrt   rs   encoder_outputsr   pooled_outputs                  rA   rj   zMLCDVisionModel.forward9  s   : ?@@)//3t{{7M7MM(..r2dkk6L6LLLL+L4G4GHRRSTU\\]_ars 	 LL*<3F3FGQQRST[[\nprs 	 ++x//183C3C3EFBO55g>D$6$6#GQOii8bA"wwy#'')45))-8&$,, 
' 3
 
 ,A.)!Q'2++M:)/'
 	
r@   rL   )r3   r4   r5   r   rN   rc   rk   r   r   r<   r	   rj   rm   rn   s   @rA   r   r   3  sO    q/ q 26>
''$.>
 +,>
 
+	+	>
r@   r   )r   r   r   )1collections.abcr   rc   torch.nnr   huggingface_hub.dataclassesr    r   r   configuration_utilsr   modeling_outputsr   r	   modeling_utilsr
   r   processing_utilsr   utilsr   r   r   clip.modeling_clipr   r   r   r   r   r   llama.modeling_llamar   qwen2_vl.modeling_qwen2_vlr   r   
get_loggerr3   loggerr   rC   rG   rI   rp   r   r   r   r   __all__r?   r@   rA   <module>r      s    %   . & 3 K F & @ @  ; [ 
		H	% CD#$' #$  E#$L	g 		/ 	/ $9)M 9)x'' 'T.
+ .
b -2/ -2 -2`D
o D
Nr@   