Ë
    ÜÓ^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Õ  € ð( #Ÿk™k×>Ñ>ÀÇÁ×ARÑARÐSTÑAUÑUÐX\×XbÑXb×XiÑXiÐjkÑXlÑlÐØ×Ñ Ñ#Ð':Ò:ÜØIÐJ]ÐI^Ð^jÐky×kÑkð  ACñ  lDð  kEð  Erð  sFð  rGð  GHð  Ióð ð (×*Ñ*°·±×1BÑ1B×1HÑ1HÐQU×Q[ÑQ[×QbÑQb×QiÑQiÐ*ÓjˆÜŸ™×*Ñ*¨4¯:©:°nÓ+EÓFˆÜŸ™×*Ñ*¨4¯:©:°mÓ+DÓEˆØ%×-Ñ-¨a°°AÓ6ˆà×(Ñ(×/Ñ/ˆ	Ø&¨Ñ2×6Ñ6°}×7JÑ7JÓKˆÜŸ™×-Ñ-¨m¸t¿|¹|ÐVZ×VcÑVcÐ-Ódˆä"+¨D¯K©KÓ"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[×IgÑIgÐnsÔtˆŒÜ˜&×5Ñ5Ñ6ˆŒÜŸ	™	 &×"4Ñ"4×"@Ñ"@À&×BTÑBT×B`Ñ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°×1DÑ1DÓEˆÔÜ'×3Ñ3°F×4FÑ4FÓGˆÔÜ%?ÀÓ%GˆÔ"Ø�‰Õr"   zŸThis 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   € ð )˜×(Ñ(¨ÑTÀTÐTÈVÑTˆØ+×=Ñ=ÐØ1×9Ñ9¸"¸d¿k¹k×>VÑ>V×>hÑ>hÓiÐØ×1Ñ1Ð2EÓ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°$×2KÑ2KÓ2MÜ—‘˜TŸ[™[×7Ñ7¼u¿z¹zÐR_×RfÑRfÔgó3ñ "Ðð "4×!7Ñ!7¸Ó!;Ñà!*¨d¯k©k×.HÑ.HÑ!HÐà+×/Ñ/Ó1ˆØ)×/Ñ/°Ñ2ÐØ/×9Ñ9¸"Ó=×GÑGÈÓV×YÑYÐZg×ZnÑZnÓoÐÜØÐ,Ñ-×3Ñ3Ó5¸×9MÑ9MÓ9OÑOØDÀ^ÐDTÐT`Ð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ô   € ð Ð Ø7˜D×5Ñ5Ó7¸	ÓBˆMàˆØÐ%¨)Ð*?Ø×2Ñ2°>ÈtÐ2ÓT×bÑbˆLð "&×!:Ñ!:Ø¨À|ð ";ó "Ðð *×8Ñ8Ð9KÈ\Ï_É_Ð]j×]qÑ]qÓMrÓsˆMà+>¨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ôðØ#×/Ñ/ðØ;AÐBTÑ;Uðà	Ð+Ñ	+òóó ðð&"Ø×)Ñ)ð"Ø:?×:KÑ:Kð"Ø]b×]nÑ]nó"ð0 Øð .2Ø37Ø.2Ø04Ø(,Ø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   ø€ Ü‰Ñ˜Ô Ü! &Ó)ˆŒ
Ü—y‘y ×!3Ñ!3×!?Ñ!?À×ASÑAS×A^ÑA^ÐejÔkˆŒØ�‰Õr"   c                 ó:   —  | j                   j                  |i |¤ŽS rY   )r£   r‡   )rQ   Úargsr4   s      r#   r‡   z2VoxtralForConditionalGeneration.get_audio_features  s   € Ø,ˆt�z‰z×,Ñ,¨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À>ÔSVÔ8Wœ˜~˜o¨tÔ4Ð]kˆØ—‘˜mªA¨}ºaÐ,?Ñ@ÓAˆàˆØÐØ%�4×%Ñ%ð Ø f¸¿¹×9PÑ9P×9[Ñ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]   ø€ ð  Ÿ™Ð$4°dÓ;ˆØ#ŸZ™ZÐ(<¸eÓDÐä‘wÑ<¸dÐMÀfÑMˆá V§Z¡Z°¸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Ð ôò>ð Øð .2Ø37Ø.2Ø04Ø(,Ø26Ø*.Ø!%Ø-.ñI
à×#Ñ# dÑ*ðI
ð ×)Ñ)¨DÑ0ðI
ð Ÿ™ tÑ+ð	I
ð
 ×&Ñ&¨Ñ-ðI
ð  ™ðI
ð ×(Ñ(¨4Ñ/ðI
ð × Ñ  4Ñ'ðI
ð ˜$‘;ðI
ð ˜eŸl™lÑ*ð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"   