
    qiU                        d Z ddlmZ 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 ddl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 ddlmZ  ej>                  e       Z!d Z" G d dejF                        Z$d Z%d.dZ&	 d/dejF                  dejN                  dejN                  dejN                  dejN                  dz  de(de(fdZ) G d d ejF                        Z* G d! d"ejF                        Z+ G d# d$ejF                        Z, G d% d&e      Z- G d' d(ejF                        Z.e G d) d*e             Z/d+ Z0e G d, d-e/             Z1d-d*gZ2y)0zPyTorch Pixtral model.    )Callable)OptionalN)nn   )ACT2FN)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutput)dynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringcan_return_tuplelogging)is_flash_attention_requestedmaybe_autocast   )PixtralVisionConfigc                    g }| D ]  }|j                   dd  \  }}t        j                  t        j                  |      t        j                  |      d      }t        j                  |d      j                  dd      j                  dd      \  }}||z  |z   }	|j                  |	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
             ^/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/pixtral/modeling_pixtral.pyposition_ids_in_meshgridr2   %   s    I" $BC(~~ell62ELL4GRVWTr2::2qAGG2Ny 6)QT#$ 99Y    c                        e Zd ZU dZej
                  ed<   ddef fdZe		 	 	 ddedz  de
d   dedz  d	ed
ef   fd       Z ej                         e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.
    inv_freqNconfigc                    t         |           || _        | j                  j                  d   | _        | j
                  }| j                  dk7  r/t        | j                  j                   d| j                   d       || j                  |      \  }}| j                  d|d       | j                  d|j                         d       y )	N	rope_typedefaultz7 does not support non-default RoPE, but got `rope_type=`r6   F)
persistentoriginal_inv_freq)super__init__r7   rope_parametersr9   compute_default_rope_parameters
ValueError	__class____name__register_bufferclone)selfr7   device
layer_typerope_init_fnr6   attention_scalingrC   s          r1   r?   zPixtralRotaryEmbedding.__init__>   s    44[A!%!E!E>>Y&>>**++bcgcqcqbrrst  '34;;&G##ZeD0(..2BuUr3   rH   ztorch.deviceseq_lenreturnztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}| j                  | j
                  z  }t        j                  |      }t        j                  |      }d|t        j                  d|d      j                         |z  z  z  }	t        j                  ||	ddd         j                         }
t        j                  ||	ddd         j                         }t        j                  |
dddddf   j                  d|d      |dddddf   j                  |dd      gd	      j                  d|dz        }t        j                  ||fd	      }||fS )
a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNg      ?r   r   r   r   r   )r@   getattrhidden_sizenum_attention_heads
image_size
patch_sizer   r!   floatouterr&   repeatr#   )r7   rH   rL   baser   attention_factormax_patches_per_sidehwfreqsfreqs_hfreqs_wr6   s                r1   rA   z6PixtralRotaryEmbedding.compute_default_rope_parametersN   so   & %%l3fj$/c63E3EIcIc3c  &00F4E4EELL-.LL-.tQQ 7 = = ?# EFG++ass,224++aqt!t-335994
#**1.BAFa
#**+?AF 
 '"cQh
 	 99h1r:)))r3   c                    | j                   |   }t        |j                  j                  t              r/|j                  j                  dk7  r|j                  j                  nd}t        |d      5  |}|j                         }|j                         }d d d        j                  |j                        j                  |j                        fS # 1 sw Y   AxY w)NmpscpuF)device_typeenableddtype)
r6   
isinstancerH   typestrr   cossintorg   )rG   xposition_idsr^   rd   embrk   rl   s           r1   forwardzPixtralRotaryEmbedding.forward{   s     l+'1!((--'E!((--[`J`ahhmmfkUC 	C'')C'')C	
 vvAGGv$cff177f&;;;	 	s   2#CCNN)NNN)rD   
__module____qualname____doc__r   Tensor__annotations__r   r?   staticmethodr   inttuplerV   rA   no_gradr   rq   __classcell__rC   s   @r1   r5   r5   0   s    	 llV2 V  -1+/"**#d***(** t** 
~u$	%	** **X U]]_<  <r3   r5   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&   )rn   x1x2s      r1   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   c                     |j                  |      }|j                  |      }| |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.
        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.
    )	unsqueezer   )qkrk   rl   unsqueeze_dimq_embedk_embeds          r1   apply_rotary_pos_embr      sY    $ --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   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 )Nr   r   )r   rg   )ptrainingr   r   )r   matmul	transposer   
functionalsoftmaxfloat32rm   rg   r   r   
contiguous)
r   r   r   r   r   r   r   kwargsattn_weightsattn_outputs
             r1   eager_attention_forwardr      s     <<s}}R'<=GL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|U3K''1-88:K$$r3   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                  f   dz  dedz  de	e
   d	eej                  ej                  dz  f   fd
Z xZS )PixtralAttentionzI
    Multi-headed attention compatible with ALL_ATTENTION_FUNCTIONS.
    c                    t         |           || _        |j                  | _        |j
                  | _        | j                  | j                  z  | _        d| _        | j                  dz  | _	        d| _        |j                  | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        t        j                  | j                  | j                  d      | _        y )NFg      ࿩bias)r>   r?   r7   rR   	embed_dimrS   	num_headsrP   	is_causalr   attention_dropoutr   r   Lineark_projv_projq_projo_projrG   r7   rC   s     r1   r?   zPixtralAttention.__init__   s    ++33$..8}}d*//iiUKiiUKiiUKiiUKr3   Nhidden_statesr   position_embeddingsoutput_attentionsr   rM   c                 J   |j                         \  }}}| j                  |      }	| j                  |      }
| j                  |      }|	j	                  ||| j
                  | j                        j                  dd      }	|
j	                  ||| j
                  | j                        j                  dd      }
|j	                  ||| j
                  | j                        j                  dd      }|\  }}t        |	|
||d      \  }	}
t        j                  | j                  j                  t              } || |	|
||f| j                  sdn| j                  | j                   d|\  }}|j#                  ||d      j%                         }| j'                  |      }|sd}||fS )	z#Input shape: Batch x Time x Channelr   r   r   )r           )r   r   r   N)sizer   r   r   viewr   rP   r   r   r   get_interfacer7   _attn_implementationr   r   r   r   r#   r   r   )rG   r   r   r   r   r   
batch_sizepatches_query_states
key_statesvalue_statesrk   rl   attention_interfacer   r   s                    r1   rq   zPixtralAttention.forward   s    "/!3!3!5
GQ{{=1[[/
{{=1#((Wdnndmm\ffghjkl__Z$..$--Xbbcdfgh
#((Wdnndmm\ffghjkl&S#7jRUWZjk#l j(?(M(MKK,,.E)
 %8	%
  $}}C$,,LL	%
 	%
!\ "))*grBMMOkk+. LL((r3   )NNF)rD   rs   rt   ru   r?   r   rv   rz   boolr   r   rq   r|   r}   s   @r1   r   r      s    L* /3HL).+)||+) t++) #5<<#=>E	+)
  $;+) -.+) 
u||U\\D00	1+)r3   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                     | _        y )NFr   )r>   r?   r7   rR   intermediate_sizer   r   	gate_projup_proj	down_projr   
hidden_actact_fnr   s     r1   r?   zPixtralMLP.__init__  s    !--!'!9!94#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r3   c                     | j                  | j                  | j                  |            | j                  |      z        }|S N)r   r   r   r   )rG   rn   r   s      r1   rq   zPixtralMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r3   )rD   rs   rt   r?   rq   r|   r}   s   @r1   r   r     s    0r3   r   c                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	PixtralRMSNormepsrM   Nc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z=
        PixtralRMSNorm is equivalent to T5LayerNorm
        N)r>   r?   r   	Parameterr   onesweightvariance_epsilon)rG   rR   r   rC   s      r1   r?   zPixtralRMSNorm.__init__  s1     	ll5::k#:; #r3   r   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S )Nr   r   T)keepdim)	rg   rm   r   r   powmeanrsqrtr   r   )rG   r   input_dtypevariances       r1   rq   zPixtralRMSNorm.forward!  sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r3   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)rz   r   r   r   rG   s    r1   
extra_reprzPixtralRMSNorm.extra_repr(  s*    ))*+6$2G2G1HIIr3   )gư>)
rD   rs   rt   rV   r?   r   rv   rq   r   r|   r}   s   @r1   r   r     s7    $ $$ $;U\\ ;ell ;Jr3   r   c                        e Zd Z fdZ	 	 d
dej
                  dej
                  deej
                  ej
                  f   dz  dedz  dee	   deej                     fd	Z xZS )PixtralAttentionLayerc                     t         |           t        |j                  d      | _        t        |      | _        t        |      | _        t        |j                  d      | _	        y )Nh㈵>r   )
r>   r?   r   rR   attention_normr   feed_forwardr   	attentionffn_normr   s     r1   r?   zPixtralAttentionLayer.__init__-  sP    ,V-?-?TJ&v.)&1&v'9'9tDr3   Nr   r   r   r   r   rM   c                     |}| j                  |      } | j                  d||||d|\  }}||z   }|}| j                  |      }| j                  |      }||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   )	rG   r   r   r   r   r   residualr   outputss	            r1   rq   zPixtralAttentionLayer.forward4  s    $ !++M:&4dnn '
') 3/	'

 '
#| !=0 m4))-8 =0 "&Gr3   rr   )rD   rs   rt   r?   r   rv   rz   r   r   r   FloatTensorrq   r|   r}   s   @r1   r   r   ,  s    E IM)-'||' ' #5<<#=>E	'
  $;' -.' 
u  	!'r3   r   c                        e Zd Z fdZ	 	 	 	 	 ddej
                  dz  deej
                  ej
                  f   dz  dedz  dedz  dedz  dee	   d	ee
z  fd
Z xZS )PixtralTransformerc                     t         |           || _        t        j                  j                         | _        t        |j                        D ]&  }| j                  j                  t        |             ( d| _        y )NF)r>   r?   r7   r   r   
ModuleListlayersrangenum_hidden_layersr%   r   gradient_checkpointing)rG   r7   r   rC   s      r1   r?   zPixtralTransformer.__init___  sc    hh))+v//0 	>AKK4V<=	>&+#r3   Nr   r   r   output_hidden_statesreturn_dictr   rM   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|rdnd}|rdnd}	|}
| j                  D ](  }|r||
fz   } ||
|f||d|}|d   }
|s |	|d   fz   }	* |r||
fz   }|st        d |
||	fD              S t        |
||	      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.
        Nr   )r   r   r   r   c              3   &   K   | ]	  }||  y wr   r   ).0vs     r1   	<genexpr>z-PixtralTransformer.forward.<locals>.<genexpr>  s     eqWXWdes   )last_hidden_stater   
attentions)r7   r   r   use_return_dictr   rz   r
   )rG   inputs_embedsr   r   r   r   r   r   encoder_statesall_attentionsr   encoder_layerlayer_outputss                r1   rq   zPixtralTransformer.forwardg  s   < 2C1N-TXT_T_TqTq$8$D $++JjJj 	 &1%<k$++B]B]30d%![[ 	FM#!/=2B!B) %8"3	
 M *!,M !/=3C2E!E	F   +}.>>Ne]NN$Seee+>Vd
 	
r3   )NNNNN)rD   rs   rt   r?   r   rv   rz   r   r   r   r
   rq   r|   r}   s   @r1   r   r   ^  s    , /3HL)-,0#'?
 t+?
 #5<<#=>E	?

  $;?
 #Tk?
 D[?
 -.?
 
	 ?
r3   r   c                   >    e Zd ZU eed<   dZdZdZdZdZ	dZ
dZdZdgZy)PixtralPreTrainedModelr7   modelpixel_values)imageTr   N)rD   rs   rt   r   rw   base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_supports_attention_backend_supports_flash_attn_supports_sdpa_supports_flex_attn_no_split_modulesr   r3   r1   r  r    s?    $O!&*#"&N01r3   r  c                    |j                   }|j                  }|j                  d   }t        j                  |      j
                  }t        j                  ||f|||      }t        j                  |       j                  d      }t        j                  dg| d d z         j                  d      }t        ||      D ]  \  }	}
d||	|
|	|
f<    |d d d d d d f   j                  |j                  d   ddd      }|S )Nr   )
fill_valuerg   rH   r   r   )rg   rH   r   r   finfominfulltensorcumsumzipexpand)r'   r  rg   rH   rL   d_mincausal_maskblock_end_idxblock_start_idxstartends              r1   generate_block_attention_maskr    s    LLE]]Fll1oGKK""E**gw/EW]^KLL!23::2>MllA3):3B)?#?@GGKO/=9 .
s,-E#IuSy(). dD!Q./66v||A2rRKr3   c                        e Zd ZdZ fdZd Zee	 	 	 	 ddej                  dej                  dz  de
dz  de
dz  d	e
dz  d
ee   deez  fd              Z xZS )PixtralVisionModelvision_encoderc                 z   t         |   |       || _        t        j                  |j
                  |j                  |j                  |j                  d      | _        |j                  | _        t        |j                  d      | _
        t        |      | _        t        |      | _        | j                          y )NF)in_channelsout_channelskernel_sizestrider   r   r   )r>   r?   r7   r   Conv2dnum_channelsrR   rU   
patch_convr   ln_prer   transformerr5   patch_positional_embedding	post_initr   s     r1   r?   zPixtralVisionModel.__init__  s     ))++++))$$
 !++$V%7%7TB-f5*@*H'r3   c                     | j                   S r   )r(  r   s    r1   get_input_embeddingsz'PixtralVisionModel.get_input_embeddings  s    r3   Nr  image_sizesr   r   r   r   rM   c           
         ||j                   \  }}	}
}|
|fg|z  }| j                  j                  j                  }| j                  |j	                  |            }t        ||      D cg c]1  \  }}|dd |d   | j                  z  d |d   | j                  z  f   3 }}}t        j                  |D cg c]  }|j                  d      j                   c}d      j                  d      }| j                  |      }t        || j                  j                  | j                  j                  z        }|j                  d      j	                  |j                   d      |d	<   | j#                  ||      }t%        | j                        rd }n7t'        |D cg c]!  }|j                   d
   |j                   d   z  # c}|      } | j(                  |f||||dd|S c c}}w c c}w c c}w )Nrf   .r   r   r   )r(   T)non_blockingro   r   r   )r   r   r   r   r   )r   r(  r   rg   rm   r  rU   r   r&   flattenTr   r)  r2   r7   rT   rH   r+  r   r  r*  )rG   r  r/  r   r   r   argsr   r   r   r+   r,   target_dtypepatch_embedsembedr   r'   r   ro   r   r   s                        r1   rq   zPixtralVisionModel.forward  s    +7+=+=(J65"E?+j8K --33|\'JK  #<=
t #5$q'T__457U$q'T__:T7UUV
 
 yy:K!LQ!))A,..!LRST^^_`a{{<0 0)?)?4;;CYCY)Y
 ".!7!7!:!=!=l>Q>Q`d!=!e~"==lLY'4!N:4EFqqwwr{*FN  t
) 3!5/
 
 	
3
 "M  Gs   ,6G$8"G*&G/)NNNN)rD   rs   rt   r  r?   r.  r   r   r   rv   r   r   r   rz   r
   rq   r|   r}   s   @r1   r  r    s    ("  ,0,0)-#'2
ll2
 \\D(2
 #Tk	2

  $;2
 D[2
 -.2
 
	 2
  2
r3   r  )r   )r   )3ru   collections.abcr   typingr   r   r   activationsr   modeling_flash_attention_utilsr   modeling_layersr	   modeling_outputsr
   modeling_rope_utilsr   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   r   configuration_pixtralr   
get_loggerrD   loggerr2   Moduler5   r   r   rv   rV   r   r   r   r   r   r   r  r  r  __all__r   r3   r1   <module>rH     sv    $    ! B 9 / 6 F & > > I 6 
		H	% U<RYY U<r(B %II%<<% 
% <<	%
 LL4'% % %.B)ryy B)L "JRYY J(/6 /dH
 H
V 
2_ 
2 
2  K
/ K
 K
\  !9
:r3   