
    ^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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 ddlmZ ddlmZmZmZmZ ddl m!Z!  G d de      Z" G d de      Z# G d de      Z$ ed       G d de             Z% G d dejL                        Z' ed      e G d d e                    Z( ed!       G d" d#e$             Z) ed$       G d% d&e$e	             Z*g d'Z+y)(    )	dataclassN)nn   )ACT2FN)Cache)GenerationMixin)BaseModelOutputWithPastBaseModelOutputWithPoolingCausalLMOutputWithPast)Unpack)TransformersKwargsauto_docstringcan_return_tupletorch_compilable_check)merge_with_config_defaults)capture_outputs   )	AutoModel)Qwen2AudioAttentionQwen2AudioEncoderQwen2AudioEncoderLayerQwen2AudioPreTrainedModel   )VoxtralConfigc                       e Zd Zy)VoxtralAttentionN__name__
__module____qualname__     v/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/voxtral/modular_voxtral.pyr   r   +       r"   r   c                       e Zd Zy)VoxtralEncoderLayerNr   r!   r"   r#   r&   r&   /   r$   r"   r&   c                        e Zd ZdZdZdZdZdZy)VoxtralPreTrainedModelTN)r   r   r    _supports_flex_attn_supports_cache_class_supports_attention_backend_can_compile_fullgraph_no_split_modulesr!   r"   r#   r(   r(   3   s      "&!r"   r(   z:
    The Voxtral encoder, which is a Whisper encoder.
    custom_introc                   J    e Zd ZeedZee	 ddee	   de
ez  fd              Zy)VoxtralEncoder)
attentionshidden_statesNkwargsreturnc           	         | j                   j                  | j                  j                  d   z  | j                  j                  d   z  }|j
                  d   |k7  r"t        d| d|j
                  d    d| d      |j                  | j                  j                  j                  | j                  j                  j                        }t        j                  j                  | j                  |            }t        j                  j                  | j	                  |            }|j                  ddd	      }| j                  j                  }||z   j                  |j                        }t        j                  j!                  || j                   | j"                  
      }t%        | j&                        D ]  \  }}	 |	||      } | j)                  |      }t+        |      S )a  
        Args:
            input_features (`torch.LongTensor` of shape `(batch_size, feature_size, sequence_length)`):
                Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
                obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a
                `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
                `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
                and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
            attention_mask (`torch.Tensor`)`, *optional*):
                Voxtral does not support masking of the `input_features`, this argument is preserved for compatibility,
                but it is not used. By default the silence in the input log mel spectrogram are ignored.
        r   z7Voxtral expects the mel input features to be of length z, but found z-. Make sure to pad the input mel features to .dtypedevicer   r   )ptraining)attention_mask)last_hidden_state)configmax_source_positionsconv1strideconv2shape
ValueErrortoweightr:   r;   r   
functionalgelupermuteembed_positionsdropoutr=   	enumeratelayers
layer_normr
   )
selfinput_featuresr>   r4   expected_seq_lengthinputs_embeds	embed_posr3   idxencoder_layers
             r#   forwardzVoxtralEncoder.forwardG   s   ( #kk>>ARARSTAUUX\XbXbXiXijkXll#'::IJ]I^^jkykk  AC  lD  kE  Er  sF  rG  GH  I  (**1B1B1H1HQUQ[Q[QbQbQiQi*j**4::n+EF**4::m+DE%--aA6((//	&266}7J7JK--mt||VZVcVc-d"+DKK"8 	C)-M	 6)+
 	
r"   N)r   r   r    r   r&   _can_record_outputsr   r   r   r   tupler
   rX   r!   r"   r#   r1   r1   <   sS     ',
   +
 +,	+

 
+	++
   +
r"   r1   c                   *     e Zd Zdef fdZd Z xZS )VoxtralMultiModalProjectorr@   c                 f   t         |           t        j                  |j                  j
                  |j                  j                  d      | _        t        |j                     | _        t        j                  |j                  j                  |j                  j                  d      | _        y NF)bias)super__init__r   Linearaudio_configintermediate_sizetext_confighidden_sizelinear_1r   projector_hidden_actactlinear_2rQ   r@   	__class__s     r#   rb   z#VoxtralMultiModalProjector.__init__x   sz    		&"5"5"G"GI[I[IgIgnst&556		&"4"4"@"@&BTBTB`B`glmr"   c                 l    | j                  |      }| j                  |      }| j                  |      }|S rY   )rh   rj   rk   )rQ   audio_featuresr3   s      r#   rX   z"VoxtralMultiModalProjector.forward~   s2    n5/m4r"   )r   r   r    r   rb   rX   __classcell__rm   s   @r#   r]   r]   w   s    n} nr"   r]   zL
    Base class for Voxtral outputs, with hidden states and attentions.
    c                   :    e Zd ZU dZdZej                  dz  ed<   y)VoxtralModelOutputWithPastzg
    audio_hidden_states (`torch.FloatTensor`, *optional*):
        Projected audio hidden states.
    Naudio_hidden_states)r   r   r    __doc__rt   torchFloatTensor__annotations__r!   r"   r#   rs   rs      s    
 59**T18r"   rs   z
    The Voxtral model, which consists of Whisper encoder, a multi-modal projector and a Llama language model,
    without a language modeling head.
    c                       e Zd Z fdZe ed      dej                  dee	   de
ez  fd              Zdej                  d	ej                  d
ej                  fdZee	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  dedz  d	ej                  dz  dedz  dee	   de
ez  fd              Z xZS )VoxtralModelc                     t         |   |       t        j                  |j                        | _        t        j                  |j                        | _        t        |      | _	        | j                          y rY   )ra   rb   r   from_configrd   audio_towerrf   language_modelr]   multi_modal_projector	post_initrl   s     r#   rb   zVoxtralModel.__init__   sY     $001D1DE'33F4F4FG%?%G"r"   zThis method is used to get the audio embeddings from input features (a log mel spectrogram), meaning inferring the audio encoder and the multi-modal projector.r.   rR   r4   r5   c                      | j                   |fddi|}|j                  }|j                  d| j                  j                  j
                        }| j                  |      }||_        |S )aa  
        input_features (`torch.FloatTensor`):
            Float values of mel features extracted from the raw speech waveform. Raw speech waveform can be
            obtained by loading a `.flac` or `.wav` audio file into an array of type `list[float]` or a
            `numpy.ndarray`, *e.g.* via the soundfile library (`pip install soundfile`). To prepare the array into
            `input_features`, the [`AutoFeatureExtractor`] should be used for extracting the mel features, padding
            and conversion into a tensor of type `torch.FloatTensor`. See [`~WhisperFeatureExtractor.__call__`]
        return_dictTr7   )r}   r?   reshaper@   rd   re   r   pooler_output)rQ   rR   r4   audio_outputsrt   audio_embedss         r#   get_audio_featureszVoxtralModel.get_audio_features   sn     )((TTTVT+==199"dkk>V>V>h>hi112EF&2#r"   	input_idsrT   ro   c                 .   |m| | j                         t        j                  | j                  j                  t        j
                  |j                              k(  }|j                  d      }n|| j                  j                  k(  }|j                         }|j                  d   }|j                  d      j                  |      j                  |j                        }t        ||   j                         |j                         k(  d| d|        |S )z
        Obtains multimodal placeholder mask from `input_ids` or `inputs_embeds`, and checks that the placeholder token count is
        equal to the length of multimodal features. If the lengths are different, an error is raised.
        r9   r7   r   z6Audio features and audio tokens do not match, tokens: z, features: )get_input_embeddingsrv   tensorr@   audio_token_idlongr;   allsumrE   	unsqueeze	expand_asrG   r   numel)rQ   r   rT   ro   special_audio_maskn_audio_tokensn_audio_featuress          r#   get_placeholder_maskz!VoxtralModel.get_placeholder_mask   s    !.2M$2K2K2MT[[77uzzR_RfRfg3 " "4!7!7!;!*dkk.H.H!H+//1)//2/99"=GGVYYZgZnZno,-3359M9M9OOD^DTT`aq`rs	
 "!r"   Nr>   position_idspast_key_values	use_cachec           	         | | j                         |      }d }	|^|\| j                  |d      j                  }	| j                  |||	      }
|j	                  |
|	j                  |j                              } | j                  d|||||d|}t        |j                  |j                  |j                  |j                  |	      S )NT)r   )rT   ro   )r>   r   r   rT   r   )r?   r   r3   r2   rt   r!   )r   r   r   r   masked_scatterrG   r;   r~   rs   r?   r   r3   r2   )rQ   r   rR   r>   r   r   rT   r   r4   r   r   outputss               r#   rX   zVoxtralModel.forward   s      7D557	BM%)*?22>t2TbbL "&!:!:| "; " *889K\__]j]q]qMrsM+>4+>+> ,
)%+',
 ,
 *%77#33!//)) ,
 	
r"   )NNNNNNN)r   r   r    rb   r   r   rv   rw   r   r   r[   r
   r   
LongTensorr   Tensorr   boolrs   rX   rp   rq   s   @r#   rz   rz      s\     w#//;ABT;U	+	+ &"))":?:K:K"]b]n]n"0  .237.204(,26!%'
##d*'
 ))D0'
 t+	'

 &&-'
 '
 ((4/'
 $;'
 +,'
 
+	+'
  '
r"   rz   zs
    The Voxtral model, which consists of Whisper encoder, a multi-modal projector and a Llama language model.
    c                   ^    e Zd ZdgZ fdZd Zee	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  dej                  dz  d	edz  d
ej                  dz  dej                  dz  dedz  deej                  z  dee   deez  fd              Z fdZ xZS )VoxtralForConditionalGenerationrL   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y r_   )ra   rb   rz   modelr   rc   rf   rg   
vocab_sizelm_headr   rl   s     r#   rb   z(VoxtralForConditionalGeneration.__init__  sS     !&)
yy!3!3!?!?ASASA^A^ejkr"   c                 :     | j                   j                  |i |S rY   )r   r   )rQ   argsr4   s      r#   r   z2VoxtralForConditionalGeneration.get_audio_features  s    ,tzz,,d=f==r"   Nr   rR   r>   r   r   rT   labelsr   logits_to_keepr4   r5   c
                     | j                   d|||||||d|
}|j                  }t        |	t              rt	        |	 d      n|	}| j                  |dd|ddf         }d}|4 | j                  d||| j                  j                  j                  d|
}t        |||j                  |j                  |j                        S )aj  
        Example:

        ```python
        >>> from transformers import VoxtralForConditionalGeneration, AutoProcessor
        >>> import torch

        >>> device = "cuda" if torch.cuda.is_available() else "cpu"
        >>> repo_id = "mistralai/Voxtral-Mini-3B-2507"

        >>> processor = AutoProcessor.from_pretrained(repo_id)
        >>> model = VoxtralForConditionalGeneration.from_pretrained(repo_id, dtype=torch.bfloat16, device_map=device)

        >>> conversation = [
            {
                "role": "user",
                "content": [
                    {
                        "type": "audio",
                        "url": "https://huggingface.co/datasets/hf-internal-testing/dummy-audio-samples/resolve/main/dude_where_is_my_car.wav",
                    },
                    {"type": "text", "text": "What can you tell me about this audio?"},
                ],
            }
        ]

        >>> inputs = processor.apply_chat_template(conversation)
        >>> inputs = inputs.to(device, dtype=torch.bfloat16)

        >>> outputs = model.generate(**inputs, max_new_tokens=30)
        >>> processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True)
        ["This audio is a humorous conversation between two friends, likely in English, where one of them is trying to figure out what the other's tattoo says."]
        ```)r   rR   r>   r   r   rT   r   N)logitsr   r   )lossr   r   r3   r2   r!   )r   r?   
isinstanceintslicer   loss_functionr@   rf   r   r   r   r3   r2   )rQ   r   rR   r>   r   r   rT   r   r   r   r4   r   r3   slice_indicesr   r   s                   r#   rX   z'VoxtralForConditionalGeneration.forward  s    ` $** 	
))%+'	
 	
  118B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD &#33!//))
 	
r"   c                     |j                  dd       }|j                  dd      }t        |   |i |}|s|j                  dd      s||d<   |S )NrR   is_first_iterationFr   T)popgetra   prepare_inputs_for_generation)rQ   r   r4   rR   r   model_inputsrm   s         r#   r   z=VoxtralForConditionalGeneration.prepare_inputs_for_generation[  s]      $4d;#ZZ(<eDw<dMfMVZZT%B-;L)*r"   )	NNNNNNNNr   )r   r   r    _keep_in_fp32_modules_strictrb   r   r   r   rv   r   rw   r   r   r   r   r   r   r[   r   rX   r   rp   rq   s   @r#   r   r      s2    %6#6 >  .237.204(,26*.!%-.I
##d*I
 ))D0I
 t+	I

 &&-I
 I
 ((4/I
   4'I
 $;I
 ell*I
 +,I
 
'	'I
  I
V r"   r   )r(   r1   rz   r   ),dataclassesr   rv   r   activationsr   cache_utilsr   
generationr   modeling_outputsr	   r
   r   processing_utilsr   utilsr   r   r   r   utils.genericr   utils.output_capturingr   autor    qwen2_audio.modeling_qwen2_audior   r   r   r   configuration_voxtralr   r   r&   r(   r1   Moduler]   rs   rz   r   __all__r!   r"   r#   <module>r      s2    "   !   ) 
 ' a a 7 5   1	* 		0 	6  
3
& 3

3
l  
 9!8 9 9 `
) `
`
F 
e&<o e
eP jr"   