
    gU                        d 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
 ddlmZ ddlmZ dd	lmZmZmZ d
dlmZ  ej        e          Zd Z G d dej                  Zd Zd#dZ G d dej                  Z G d dej                  Z G d dej                  Z G d dej                  Z  G d dej                  Z!dZ" G d de
          Z#dZ$d Z% ed e"           G d! d"e#                      Z&dS )$zPyTorch Pixtral model.    )ListOptionalTupleUnionN)nn   )PreTrainedModel)ACT2FN)BaseModelOutput)add_start_docstrings%add_start_docstrings_to_model_forwardlogging   )PixtralVisionConfigc                    g }| D ]}|j         dd          \  }}t          j        t          j        |          t          j        |          d          }t          j        |d                              dd                              dd          \  }}||z  |z   }	|                    |	d d df                    t          j        |          S )Nij)indexingdim   r   )	shapetorchmeshgridarangestackreshapechunkappendcat)
patch_embeds_list	max_width	positionspatchheightwidthmeshh_gridv_grididss
             h/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/pixtral/modeling_pixtral.pyposition_ids_in_meshgridr-   %   s    I" $ $BCC(~el622EL4G4GRVWWWTr222::2qAAGG2NNy 6)QQQT####9Y    c                   X     e Zd ZdZ fdZ ej                    d             Zd Z xZ	S )PixtralRotaryEmbeddinga  
    The key with pixtral embedding is just that you have a frequency for each pixel positions.
    If you have height x width pixels (or embedding pixels), then the frequency used for ROPE
    is given by indexing the pre_computed frequency on the width and height.

    What you output is of dimension (batch, height * width, dim) with dim the embed dim.

    This simply means that for each image hidden state, you are going to add
    a corresponding positional embedding, based on its index in the grid.
    c                    t                                                       d| _        |j        | _        |j        | _        |j        |j        z  }d| j        t          j
        d| j        d                                          | j        z  z  z  }t          j
        ||j                  }t          j
        ||j                  }t          j        ||d d d                                                   }t          j        ||dd d                                                   }t          j        |d d d d d f                             d|d          |d d d d d f                             |dd          gd                              d| j        dz            }	|                     d	t          j        |	|	fd          d
           d S )Ndefaultg      ?r   r   devicer   r   r   inv_freqF
persistent)super__init__	rope_typehead_dimr   
rope_thetabase
image_size
patch_sizer   r   floatr4   outerr!   repeatr   register_buffer)selfconfigr4   max_patches_per_sidefreqshwfreqs_hfreqs_wr5   	__class__s             r,   r9   zPixtralRotaryEmbedding.__init__<   s   "?%	%0F4EEtyU\!TXq%A%A%G%G%I%IDH%TUVL-elCCCL-elCCC+asss,,2244+aqt!t--335594
#**1.BAFFaaa
#**+?AFF 
 
 
 '"dh!m
$
$ 	 	ZHh3GR)P)P)P]bcccccr.   c                    d| j         v r|                     ||j                   | j        |         }|j        j        }t          |t                    r|dk    r|nd}t          j        |d          5  |}|	                                }|
                                }d d d            n# 1 swxY w Y   |                    |j                  |                    |j                  fS )Ndynamicr3   mpscpuF)device_typeenabled)dtype)r:   _dynamic_frequency_updater4   r5   type
isinstancestrr   autocastcossintorS   )rD   xposition_idsrG   rQ   embrY   rZ   s           r,   forwardzPixtralRotaryEmbedding.forwardU   s   &&**<*III l+ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	C''))C''))C	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 vvAGv$$cff17f&;&;;;s   4+B++B/2B/c                 ^   t          j        |          dz   }|| j        k    rB | j        | j        |fd|i| j        \  }| _        |                     d|d           || _        || j        k     r;| j        | j        k    r-|                     d| j	        d           | j        | _        dS dS dS )a  
        dynamic RoPE layers should recompute `inv_freq` in the following situations:
        1 - growing beyond the cached sequence length (allow scaling)
        2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
        r   seq_lenr5   Fr6   N)
r   maxmax_seq_len_cachedrope_init_fnrE   rope_kwargsattention_scalingrC   original_max_seq_lenoriginal_inv_freq)rD   r]   r4   ra   r5   s        r,   rT   z0PixtralRotaryEmbedding._dynamic_frequency_updatef   s     )L))A-T,,,/@t/@V0 0-408<8H0 0,Hd,   X% HHH&-D#T...43JTMf3f3f  T-CPU VVV&*&?D### /.3f3fr.   )
__name__
__module____qualname____doc__r9   r   no_gradr_   rT   __classcell__rL   s   @r,   r0   r0   0   s        	 	d d d d d2 U]__< < _< @ @ @ @ @ @ @r.   r0   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr   r   r   )r   r   r!   )r\   x1x2s      r,   rotate_halfrs   z   s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r.   c                     |                     |          }|                     |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezers   )qkrY   rZ   r]   unsqueeze_dimq_embedk_embeds           r,   apply_rotary_pos_embr{      sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GG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 )PixtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperc                    t                                                       || _        |j        | _        |j        | _        | j        | j        z  | _        | j        dz  | _        |j	        | _
        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _        d S )Ng      Fbias)r8   r9   rE   hidden_size	embed_dimnum_attention_heads	num_headsr;   scaleattention_dropoutdropoutr   Lineark_projv_projq_projo_projrD   rE   rL   s     r,   r9   zPixtralAttention.__init__   s    +3$.8]D(
/iUKKKiUKKKiUKKKiUKKKr.   NFhidden_statesattention_maskposition_embeddingsoutput_attentionsreturnc                 V   |                                 \  }}}|                     |          }|                     |          }	|                     |          }
|                    ||| j        | j                                      dd          }|	                    ||| j        | j                                      dd          }	|
                    ||| j        | j                                      dd          }
|\  }}t          ||	||d          \  }}	t          j
        ||	                    dd                    | j        z  }|||z   }t          j                            |dt          j                                      |j                  }t          j                            || j        | j        	          }t          j
        ||
          }|                    dd                                          }|                    ||d          }|                     |          }||fS )
z#Input shape: Batch x Time x Channelr   r   r   )rx   r   Nr   )r   rS   )ptraining)sizer   r   r   viewr   r;   	transposer{   r   matmulr   r   
functionalsoftmaxfloat32r[   rS   r   r   
contiguousr   r   )rD   r   r   r   r   
batch_sizepatches_query_states
key_statesvalue_statesrY   rZ   attn_weightsattn_outputs                  r,   r_   zPixtralAttention.forward   s    "/!3!3!5!5
GQ{{=11[[//
{{=11#((Wdndm\\ffghjkll__Z$.$-XXbbcdfghh
#((Wdndm\\ffghjkll&S#7jRUWZjk#l#l#l j|L*2F2Fq!2L2LMMPTPZZ%'.8L },,\r,WWZZ[g[mnn},,\T\TXTa,bbl<>>!++Aq11<<>>!))*grBBkk+..L((r.   )NNF)ri   rj   rk   rl   r9   r   Tensorr   boolr   r_   rn   ro   s   @r,   r}   r}      s        GGL L L L L$ 266:,1%) %)|%) !.%) &el3	%)
 $D>%) 
u|Xel33	4%) %) %) %) %) %) %) %)r.   r}   c                   $     e Zd Z fdZd Z xZS )
PixtralMLPc                    t                                                       |j        | _        |j        | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t	          j        | j        | j        d          | _        t          |j
                 | _        d S )NFr   )r8   r9   r   intermediate_sizer   r   	gate_projup_proj	down_projr
   
hidden_actact_fnr   s     r,   r9   zPixtralMLP.__init__   s    !-!'!94#3T5KRWXXXy!143IPUVVV4#94;KRWXXXV./r.   c                     |                      |                     |                     |                    |                     |          z            S N)r   r   r   r   )rD   hidden_states     r,   r_   zPixtralMLP.forward   s>    ~~dkk$..*F*FGG$,,WcJdJddeeer.   )ri   rj   rk   r9   r_   rn   ro   s   @r,   r   r      sN        0 0 0 0 0f f f f f f fr.   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )PixtralRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z=
        PixtralRMSNorm is equivalent to T5LayerNorm
        N)r8   r9   r   	Parameterr   onesweightvariance_epsilon)rD   r   epsrL   s      r,   r9   zPixtralRMSNorm.__init__   sD     	l5:k#:#:;; #r.   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr   r   T)keepdim)	rS   r[   r   r   powmeanrsqrtr   r   )rD   r   input_dtypevariances       r,   r_   zPixtralRMSNorm.forward   s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r.   c                 H    t          | j        j                   d| j         S )Nz, eps=)tupler   r   r   )rD   s    r,   
extra_reprzPixtralRMSNorm.extra_repr   s&    )**II$2GIIIr.   )r   )ri   rj   rk   r9   r_   r   rn   ro   s   @r,   r   r      sb        $ $ $ $ $ $; ; ;J J J J J J Jr.   r   c                        e Zd Z fdZ	 	 d
dej        dej        deej                 dee         deej	                 f
d	Z
 xZS )PixtralAttentionLayerc                    t                                                       t          |j        d          | _        t          |          | _        t          |          | _        t          |j        d          | _	        d S )Nh㈵>r   )
r8   r9   r   r   attention_normr   feed_forwardr}   	attentionffn_normr   s     r,   r9   zPixtralAttentionLayer.__init__   sk    ,V-?TJJJ&v..)&11&v'9tDDDr.   NFr   r   r   r   r   c                     |}|                      |          }|                     ||||          \  }}||z   }|}|                     |          }|                     |          }||z   }|f}|r||fz  }|S )a=  
        Args:
            hidden_states (`torch.FloatTensor`):
                Input to the layer of shape `(batch, seq_len, embed_dim)`.
            attention_mask (`torch.FloatTensor`):
                Attention mask of shape `(batch, 1, q_len, k_v_seq_len)` where padding elements are indicated by very large negative values.
            output_attentions (`bool`, *optional*, defaults to `False`):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
        )r   r   r   r   )r   r   r   r   )rD   r   r   r   r   residualr   outputss           r,   r_   zPixtralAttentionLayer.forward  s    " !++M::&*nn') 3/	 '5 '
 '
#| !=0 m44))-88 =0 " 	'&Gr.   NF)ri   rj   rk   r9   r   r   r   r   r   FloatTensorr_   rn   ro   s   @r,   r   r      s        E E E E E 7;,1% %|% % &el3	%
 $D>% 
u 	!% % % % % % % %r.   r   c                        e Zd Z 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 )PixtralTransformerc                 &   t                                                       || _        t          j                                        | _        t          |j                  D ])}| j        	                    t          |                     *d| _        d S r   )r8   r9   rE   r   r   
ModuleListlayersrangenum_hidden_layersr    r   gradient_checkpointing)rD   rE   r   rL   s      r,   r9   zPixtralTransformer.__init__,  s    h))++v/00 	> 	>AK4V<<====&+###r.   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}|}	| 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          |	|	g|          S )av  
        Args:
            inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
                Embeddings which serve as input to the Transformer.
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

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

                [What are attention masks?](../glossary#attention-mask)
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
                for more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        N )r   r   r   r   c              3      K   | ]}||V  	d S r   r   ).0vs     r,   	<genexpr>z-PixtralTransformer.forward.<locals>.<genexpr>w  s(      eeqWXWdWdWdWdWdeer.   )last_hidden_stater   
attentions)rE   r   r   use_return_dictr   r   r   _gradient_checkpointing_func__call__r   r   )rD   inputs_embedsr   r   r   r   r   encoder_statesall_attentionsr   encoder_layerlayer_outputss               r,   r_   zPixtralTransformer.forward4  s   : 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B]3=0:d%![ 	F 	FM# C!/=2B!B* t}  $ A A!*!"'%! ! !.!"(;&7	! ! ! *!,M  F!/=3C2E!E 	?+}.>>N 	fee]NN$Seeeeee+M?We
 
 
 	
r.   )NNNNN)ri   rj   rk   r9   r   r   r   r   r   r   r   r_   rn   ro   s   @r,   r   r   +  s        , , , , , 266:,0/3&*F
 F
 !.F
 &el3	F

 $D>F
 'tnF
 d^F
 
uo%	&F
 F
 F
 F
 F
 F
 F
 F
r.   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 ([`PixtralVisionConfig`]):
            Model configuration class with all the parameters of the vision encoder. 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.
c                   .    e Zd ZeZdZdZdgZdZdZ	d Z
dS )PixtralPreTrainedModelmodelTPixtralVisionAttentionpast_key_valuesc                 (   t          | j        d          r| j        j        n| j        j        j        }t	          |t
          j        t
          j        f          rJ|j        j	        
                    d|           |j         |j        j	                                         d S d S t	          |t
          j                  rS|j        j	        
                    d|           |j        -|j        j	        |j                                                  d S d S d S )Ninitializer_rangeg        )r   std)hasattrrE   r   text_configrV   r   r   Conv2dr   datanormal_r   zero_	Embeddingpadding_idx)rD   moduler   s      r,   _init_weightsz$PixtralPreTrainedModel._init_weights  s    t{$788;DK))(: 	 fry")455 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r.   N)ri   rj   rk   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_cache_classr   r   r.   r,   r   r     sI        &L&*#12"3 ? ? ? ? ?r.   r   a  
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`AutoImageProcessor.__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.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
c                    |j         }|j        }|j        d         }t          j        |          j        }t          j        ||f|||          }t          j        |                               d          }t          j        dg| d d         z                                 d          }t          ||          D ]\  }	}
d||	|
|	|
f<   |d d d d d d f         
                    |j        d         ddd          }|S )Nr   )
fill_valuerS   r4   r   r   )rS   r4   r   r   finfominfulltensorcumsumzipexpand)r"   r  rS   r4   ra   d_mincausal_maskblock_end_idxblock_start_idxstartends              r,   generate_block_attention_maskr    s	   LE]Fl1oGK"E*gw/EW]^^^KL!233::2>>MlA3):3B3)?#?@@GGKKO/=99 . .
s,-E#IuSy())dD!!!QQQ./66v|A2rRRKr.   z^The bare Pixtral vision encoder outputting raw hidden-states without any specific head on top.c                        e Zd ZdZ fdZ ee          	 	 	 ddeej	                 de
e         de
e         de
e         d	eeef         f
d
            Z xZS )PixtralVisionModelvision_encoderc                 P   t                                          |           || _        t          j        |j        |j        |j        |j        d          | _        t          |j        d          | _
        t          |          | _        t          || j                  | _        d S )NF)in_channelsout_channelskernel_sizestrider   r   r   r3   )r8   r9   rE   r   r   num_channelsr   r?   
patch_convr   ln_prer   transformerr0   r4   patch_positional_embeddingr   s     r,   r9   zPixtralVisionModel.__init__  s       )++)$
 
 
 %V%7TBBB-f55*@PTP[*\*\*\'''r.   FNpixel_valuesr   r   r   r   c                      fd|D             }t          j        d |D             d          }                     |          }t          | j        j         j        j        z                                 j                  }	 	                    ||	          }
t          d |D             |          }                     |||
          S )z
        Returns:
            pixel_values: tensor of token features for
                all tokens of all images of shape (N_toks, D)
        c                     g | ]B}                     |                    d                               j                            CS )r   )r   ru   r[   rS   )r   imgrD   s     r,   
<listcomp>z.PixtralVisionModel.forward.<locals>.<listcomp>  sB    fffRUT__S]]1-=-=-@-@-L-LMMfffr.   c                 b    g | ],}|                     d                               dd d          -S )r   r   r   )flattenpermuter   r   s     r,   r(  z.PixtralVisionModel.forward.<locals>.<listcomp>  s4    ![![![A!))A,,"6"6q!Q"?"?![![![r.   r   r   )r#   c                 D    g | ]}|j         d          |j         d         z  S )r   r   )r   r,  s     r,   r(  z.PixtralVisionModel.forward.<locals>.<listcomp>  s)    BBB1QWR[172;&BBBr.   )r   r!   r!  r-   rE   r>   r?   r[   r4   r#  r  r"  )rD   r$  r   r   r   argskwargsr"   patch_embedsr]   position_embeddingr   s   `           r,   r_   zPixtralVisionModel.forward  s      gfffYefff y![![IZ![![![abccc{{<00 0)?4;CY)Y
 
 

"T[// 	 "<<\<XX6BB0ABBBL
 
 n>PQQQr.   )FNN)ri   rj   rk   r  r9   r   PIXTRAL_INPUTS_DOCSTRINGr   r   r   r   r   r   r   r   r_   rn   ro   s   @r,   r  r    s        
 )] ] ] ] ] +*+CDD 05,0&*R R5<(R 'tnR $D>	R
 d^R 
uo%	&R R R EDR R R R Rr.   r  )Nr   )'rl   typingr   r   r   r   r   torch.utils.checkpointr    r	   activationsr
   modeling_outputsr   utilsr   r   r   configuration_pixtralr   
get_loggerri   loggerr-   Moduler0   rs   r{   r}   r   r   r   r   PIXTRAL_START_DOCSTRINGr   r2  r  r  r   r.   r,   <module>r>     s     / / / / / / / / / / / /                  ! ! ! ! ! ! / / / / / /         
 7 6 6 6 6 6 
	H	%	%     F@ F@ F@ F@ F@RY F@ F@ F@T( ( (   67) 7) 7) 7) 7)ry 7) 7) 7)vf f f f f f f fJ J J J JRY J J J(- - - - -BI - - -`O
 O
 O
 O
 O
 O
 O
 O
d "? ? ? ? ?_ ? ? ?2      d 0R 0R 0R 0R 0R/ 0R 0R	 0R 0R 0Rr.   