o
    Zh8m                     @   s  d dl mZ d dlmZmZmZ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mZ ddlmZ ddlmZ ddlmZmZmZmZ ddlmZ ddlm Z  edG dd dej!Z"G dd dej!Z#G dd dej!Z$eG dd deZ%eG dd deZ&eG dd deZ'edd G d!d" d"e'Z(G d#d$ d$eeZ)ed%d G d&d' d'e'eZ*g d(Z+dS ))    )	dataclass)ListOptionalTupleUnionN)nn   )ACT2FN)GenerationMixin)use_kernel_forward_from_hub)FlashAttentionKwargs)BaseModelOutputWithPastModelOutput)PreTrainedModel)Unpack)
LossKwargsauto_docstringcan_return_tupleis_torchdynamo_compiling   )	AutoModel   )Mistral3ConfigZRMSNormc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	Mistral3RMSNormư>c                    s&   t    tt|| _|| _dS )z>
        Mistral3RMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	ParametertorchZonesweightvariance_epsilon)selfhidden_sizeeps	__class__ ]/var/www/auris/lib/python3.10/site-packages/transformers/models/mistral3/modeling_mistral3.pyr   /   s   

zMistral3RMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr   T)Zkeepdim)	dtypetor   Zfloat32powmeanZrsqrtr    r   )r!   hidden_statesZinput_dtypeZvariancer&   r&   r'   forward7   s
   zMistral3RMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler   shaper    r!   r&   r&   r'   
extra_repr>   s   zMistral3RMSNorm.extra_repr)r   )__name__
__module____qualname__r   r.   r2   __classcell__r&   r&   r$   r'   r   -   s    r   c                       sB   e Zd ZdZdef fddZdejdejdejfdd	Z  Z	S )
Mistral3PatchMergerz<
    Learned merging of spatial_merge_size ** 2 patches
    configc                    sL   t    || _|jj}|j| _| jjj| _tj|| jd  |dd| _	d S )Nr   Fbias)
r   r   r8   vision_configr"   spatial_merge_size
patch_sizer   Linearmerging_layer)r!   r8   r"   r$   r&   r'   r   G   s   
 zMistral3PatchMerger.__init__image_featuresimage_sizesreturnc                    s    fdd|D }dd |D }|j d }g }t||D ]7\}}|| \}}	|||	|dddd}
tjjj	|
 j
 j
d}|| j
d  d }|| qtj|dd	} |}|S )
Nc                    s(   g | ]}|d   j  |d  j  fqS )r   r   )r=   ).0Z
image_sizer1   r&   r'   
<listcomp>Q   s    z/Mistral3PatchMerger.forward.<locals>.<listcomp>c                 S   s   g | ]\}}|| qS r&   r&   )rC   hwr&   r&   r'   rD   U   s    r(   r   r   r   )Zkernel_sizeZstridedim)r0   	enumeratesplitviewZpermute	unsqueezer   r   Z
functionalZunfoldr<   tappendcatr?   )r!   r@   rA   Ztokens_per_imagedZpermuted_tensorZimage_indexZimage_tokensrE   rF   Z
image_gridgridr&   r1   r'   r.   P   s"   



zMistral3PatchMerger.forward)
r3   r4   r5   __doc__r   r   r   Tensorr.   r6   r&   r&   r$   r'   r7   B   s    $	r7   c                       s8   e Zd Zdef fddZdejdejfddZ  ZS )Mistral3MultiModalProjectorr8   c                    s   t    t|jj|jjd| _t|| _	t
|jtrdnt|j}tj|jj| |jj|jd| _t|j | _tj|jj|jj|jd| _d S )N)r#   r   r9   )r   r   r   r;   r"   text_configZrms_norm_epsnormr7   patch_merger
isinstancevision_feature_layerintlenr   r>   Zmultimodal_projector_biaslinear_1r	   Zprojector_hidden_actactlinear_2)r!   r8   Znum_feature_layersr$   r&   r'   r   i   s   


z$Mistral3MultiModalProjector.__init__r@   rA   c                 C   s8   |  |}| ||}| |}| |}| |}|S N)rV   rW   r\   r]   r^   )r!   r@   rA   r-   r&   r&   r'   r.   y   s   



z#Mistral3MultiModalProjector.forward)	r3   r4   r5   r   r   r   rS   r.   r6   r&   r&   r$   r'   rT   h   s    rT   c                   @   s   e Zd ZU dZdZeej ed< dZ	eej ed< dZ
eeej  ed< dZeeej  ed< dZeeej  ed< dZeej ed< dS )	Mistral3CausalLMOutputWithPasta  
    Base class for Mistral3 causal language model (or autoregressive) outputs.

    Args:
        loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided):
            Language modeling loss (for next-token prediction).
        logits (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`):
            Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nlosslogitspast_key_valuesr-   
attentionsimage_hidden_states)r3   r4   r5   rR   ra   r   r   FloatTensor__annotations__rb   rc   r   r-   r   rd   re   r&   r&   r&   r'   r`      s   
 r`   c                   @   s$   e Zd ZU dZdZeej ed< dS )Mistral3ModelOutputWithPasta  
    Base class for Mistral3 outputs, with hidden states and attentions.

    Args:
        last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
            Sequence of hidden-states at the output of the last layer of the model.
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`)

            Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see
            `past_key_values` input) to speed up sequential decoding.
        hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
            Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
            one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.

            Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
        attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
            Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
            sequence_length)`.

            Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
            heads.
        image_hidden_states (`torch.FloatTensor`, *optional*):
            A `torch.FloatTensor` of size `(batch_size, num_images, sequence_length, hidden_size)`.
            image_hidden_states of the model produced by the vision encoder and after projecting the last hidden state.
    Nre   )	r3   r4   r5   rR   re   r   r   rf   rg   r&   r&   r&   r'   rh      s   
 rh   c                   @   s<   e Zd ZeZdZdZdZdZdZ	dZ
dZdZdZdd ZdS )Mistral3PreTrainedModel Trc   c                 C   s   t | jd| j j}t|tjr)|jjj	d|d |j
d ur'|j
j  d S d S t|tjr>|jjd |j
j  d S t|trL|jjd d S d S )Ninitializer_rangeg        )r,   stdg      ?)getattrr8   Zget_text_configrk   rX   r   r>   r   dataZnormal_r:   Zzero_Z	LayerNormZfill_r   )r!   modulerl   r&   r&   r'   _init_weights   s   

z%Mistral3PreTrainedModel._init_weightsN)r3   r4   r5   r   Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_skip_keys_device_placementZ_supports_cache_classZ_supports_flash_attn_2Z_supports_sdpaZ_supports_quantized_cacheZ_supports_static_cacheZ_supports_attention_backendrp   r&   r&   r&   r'   ri      s    ri   zx
    The Mistral3 model which consists of a vision backbone and a language model, without a language modeling head.
    )Zcustom_introc                #       s&  e Zd ZddiZdef fddZdd Zdd	 Z	
ddej	dej
deeeee f  fddZee	
	
	
	
	
	
	
	
	
	
	
	
	
ddejdej	deej
 deej deeej	  deej	 deeeee f  dee dee dee dee deej dej
dee deeef fddZ  ZS ) Mistral3Modelzlanguage_model.modellanguage_modelr8   c                    s>   t  | t|j| _t|| _t|j| _	| 
  d S r_   )r   r   r   Zfrom_configr;   vision_towerrT   multi_modal_projectorrU   rr   	post_initr!   r8   r$   r&   r'   r      s
   
zMistral3Model.__init__c                 C   
   | j  S r_   )rr   get_input_embeddingsr1   r&   r&   r'   rx         
z"Mistral3Model.get_input_embeddingsc                 C      | j | d S r_   )rr   set_input_embeddingsr!   valuer&   r&   r'   r{         z"Mistral3Model.set_input_embeddingsNpixel_valuesrA   rY   c                    s   |dur|n| j j}dd | D }| j|f|dd| t|tr* j| }n fdd|D }tj|dd	}| 	|
d
|}|S )aU  
        Obtains image last hidden states from the vision tower and apply multimodal projection.

        Args:
            pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`):
               The tensors corresponding to the input images.
            vision_feature_layer (`Union[int, List[int]]`, *optional*):
                The index of the layer to select the vision feature. If multiple indices are provided,
                the vision feature of the corresponding indices will be concatenated to form the
                vision features.
            image_sizes (`torch.Tensor`, *optional*):
                Tensor containing the image sizes as returned by the processor.
        Returns:
            image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_length, embed_dim)`).
        Nc                 S   s   i | ]\}}|d ur||qS r_   r&   )rC   kvr&   r&   r'   
<dictcomp>  s    z4Mistral3Model.get_image_features.<locals>.<dictcomp>T)rA   output_hidden_statesc                    s   g | ]} j | qS r&   )r-   )rC   Z	layer_idxZimage_outputsr&   r'   rD   !  s    z4Mistral3Model.get_image_features.<locals>.<listcomp>r(   rG   r   )r8   rY   itemsrs   rX   rZ   r-   r   rO   rt   Zsqueeze)r!   r   rA   rY   kwargsZselected_image_featureZhs_poolr@   r&   r   r'   get_image_features   s   
z Mistral3Model.get_image_features	input_idsattention_maskposition_idsrc   inputs_embeds	use_cacheoutput_attentionsr   return_dictcache_positionr   rB   c                 K   s  |	d ur|	n| j j}	|
d ur|
n| j j}
|d ur|n| j j}|d ur$|n| j j}|d u |d uA r4td|d ur@|d ur@td|d u rJ|  |}|d ur| j|||d}|| j jk	d}|
||j}t s||  | kr|| j jk }|jd |jd  }td| d| ||j|j}|||}| jd||||||	|
d	|d
	|}t|j|j|j|j|d ur|dS d dS )Nz:You must specify exactly one of input_ids or inputs_embedszdYou cannot specify both pixel_values and inputs_embeds at the same time, and must specify either one)r   rY   rA   r(   r   r   z6Image features and image tokens do not match: tokens: z, features T)	r   r   rc   r   r   r   r   r   r   )last_hidden_staterc   r-   rd   re   r&   )r8   r   r   use_return_dictrY   
ValueErrorrx   r   Zimage_token_idrL   Z	expand_asr*   devicer   Znumelsumr0   r)   Zmasked_scatterrr   rh   r   rc   r-   rd   )r!   r   r   r   r   rc   r   rY   r   r   r   r   r   rA   r   r@   Zspecial_image_maskZn_image_tokensZn_image_featuresoutputsr&   r&   r'   r.   '  sh   

zMistral3Model.forwardr_   )NNNNNNNNNNNNN)r3   r4   r5   _checkpoint_conversion_mappingr   r   rx   r{   r   rf   rS   r   r   rZ   r   r   r   r   
LongTensorboolr   r   r   rh   r.   r6   r&   r&   r$   r'   rq      sv    
(	

rq   c                   @   s   e Zd ZdS )KwargsForCausalLMN)r3   r4   r5   r&   r&   r&   r'   r   v  s    r   zV
    The MISTRAL3 model which consists of a vision backbone and a language model.
    c                %       s  e Zd ZdddddZdgZdef fdd	Zd
d Zdd Zde	j
fddZdd Zedd Zedd Zedd Zee														d4dejdejdeej deej deeej  d eej d!eej d"ee d#ee d$ee d%ee d&eej d'eeejf d(eej d)ee deeef f d*d+Z 						d5 fd,d-	Z!e"dejd.ed/ed0ej#d&ejd1efd2d3Z$  Z%S )6 Mistral3ForConditionalGenerationzmodel.language_modelzmodel.vision_towerzmodel.multi_modal_projectorlm_head)z^language_model.modelz^vision_towerz^multi_modal_projectorz^language_model.lm_headzlm_head.weightr8   c                    s<   t  | t|| _tj|jj|jjdd| _	| 
  d S )NFr9   )r   r   rq   modelr   r>   rU   r"   
vocab_sizer   ru   rv   r$   r&   r'   r     s   
z)Mistral3ForConditionalGeneration.__init__c                 C   rw   r_   )r   rx   r1   r&   r&   r'   rx     ry   z5Mistral3ForConditionalGeneration.get_input_embeddingsc                 C   rz   r_   )r   r{   r|   r&   r&   r'   r{     r~   z5Mistral3ForConditionalGeneration.set_input_embeddingsrB   c                 C   s   | j S r_   r   r1   r&   r&   r'   get_output_embeddings  s   z6Mistral3ForConditionalGeneration.get_output_embeddingsc                 C   s
   || _ d S r_   r   )r!   Znew_embeddingsr&   r&   r'   set_output_embeddings  ry   z6Mistral3ForConditionalGeneration.set_output_embeddingsc                 C      | j jS r_   )r   rr   r1   r&   r&   r'   rr        z/Mistral3ForConditionalGeneration.language_modelc                 C   r   r_   )r   rs   r1   r&   r&   r'   rs     r   z-Mistral3ForConditionalGeneration.vision_towerc                 C   r   r_   )r   rt   r1   r&   r&   r'   rt     r   z6Mistral3ForConditionalGeneration.multi_modal_projectorNr   r   r   r   r   rc   r   labelsr   r   r   r   r   logits_to_keeprA   r   c                 K   s   |	dur|	n| j j}	|
dur|
n| j j}
|dur|n| j j}| jd||||||||	|
d||d|}|d }t|trBt| dn|}| |dd|ddf }d}|durg| j	d||| j j
jd|}t|||j|j|j|jdS )a  
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
            config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
            (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

        Example:

        ```python
        >>> from PIL import Image
        >>> import requests
        >>> from transformers import AutoProcessor, Mistral3ForConditionalGeneration

        >>> model = Mistral3ForConditionalGeneration.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")
        >>> processor = AutoProcessor.from_pretrained("mistralai/Mistral-Small-3.1-24B-Instruct-2503")

        >>> prompt = "<s>[INST][IMG]What is the image?[/INST]"
        >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
        >>> image = Image.open(requests.get(url, stream=True).raw)

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

        >>> # Generate
        >>> generate_ids = model.generate(**inputs, max_new_tokens=15)
        >>> processor.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "What is the image?The image depicts two cats lying on a pink blanket."
        ```NT)r   r   r   r   rc   r   r   r   r   r   r   rA   r   )rb   r   r   )ra   rb   rc   r-   rd   re   r&   )r8   r   r   r   r   rX   rZ   slicer   Zloss_functionrU   r   r`   rc   r-   rd   re   )r!   r   r   r   r   rc   r   r   r   r   r   r   r   r   rA   r   r   r-   Zslice_indicesrb   ra   r&   r&   r'   r.     sL   /z(Mistral3ForConditionalGeneration.forwardc           
         s8   t  j|f|||||d|}	|d dkr||	d< |	S )N)rc   r   r   r   r   r   r   )r   prepare_inputs_for_generation)
r!   r   rc   r   r   r   r   r   r   Zmodel_inputsr$   r&   r'   r     s   
z>Mistral3ForConditionalGeneration.prepare_inputs_for_generationsequence_lengthtarget_lengthr)   
batch_sizec                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuer)   r   r   )Zdiagonal)r   r(   r   )rH   r   Zfinfominfullr   ZtriuZarangeZreshapeexpandcloner0   r*   Zmasked_fill)r   r   r   r)   r   r   r   Zcausal_maskZ	min_dtypeZmask_lengthZpadding_maskr&   r&   r'   5_prepare_4d_causal_attention_mask_with_cache_position  s,    $
6  zVMistral3ForConditionalGeneration._prepare_4d_causal_attention_mask_with_cache_position)NNNNNNNNNNNNr   N)NNNNNN)&r3   r4   r5   r   Z_tied_weights_keysr   r   rx   r{   r   Moduler   r   propertyrr   rs   rt   r   r   r   r   rf   r   rS   r   r   r   rZ   r   r   r   r`   r.   r   staticmethodr)   r   r6   r&   r&   r$   r'   r   y  s    


	

Zr   )rq   ri   r   ),dataclassesr   typingr   r   r   r   r   r   Zactivationsr	   Z
generationr
   Zintegrationsr   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   Zmodeling_utilsr   Zprocessing_utilsr   utilsr   r   r   r   autor   Zconfiguration_mistral3r   r   r   r7   rT   r`   rh   ri   rq   r   r   __all__r&   r&   r&   r'   <module>   sH   &'  	 X