
    ^j`                        d dl 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mZmZ ddlmZmZ ddlmZ ddlmZ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&  ejN                  e(      Z)	 	 d2dejT                  dejV                  dejV                  dejV                  dejV                  dz  de,dz  de,fdZ- G d dejT                        Z. G d de      Z/e G d  d!e             Z0 ed"#       G d$ d%e0             Z1 G d& d'ejT                        Z2 ed(#      e G d) d*e                    Z3 ed+#       G d, d-e0             Z4 ed.#       G d/ d0e0e             Z5g d1Z6y)3    N)Callable)	dataclass)nn   )ACT2FN)Cache)GenerationMixin)GradientCheckpointingLayer)BaseModelOutputWithPastBaseModelOutputWithPoolingCausalLMOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleloggingtorch_compilable_check)merge_with_config_defaults)capture_outputs   )	AutoModel   )VoxtralConfigVoxtralEncoderConfigmodulequerykeyvalueattention_maskscalingdropoutc                    ||j                  d      dz  }t        j                  ||j                  dd            |z  }|||z   }t        j
                  j                  |d      }t        j
                  j                  ||| j                        }t        j                  ||      }	|	j                  dd      j                         }	|	|fS )N      r   r   )dimptrainingr   )
sizetorchmatmul	transposer   
functionalsoftmaxr#   r*   
contiguous)
r   r   r   r    r!   r"   r#   kwargsattn_weightsattn_outputs
             w/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/voxtral/modeling_voxtral.pyeager_attention_forwardr6   .   s     **R.D(<<s}}Q':;gEL!#n4==((2(>L==((6??([L,,|U3K''1-88:K$$    c                   ,    e Zd ZdZ	 	 	 	 	 	 ddedededededed	edz  d
edz  f fdZde	j                  dedefdZ	 	 dde	j                  de	j                  dz  dedee	j                  e	j                  dz  ee	j                     dz  f   fdZ xZS )VoxtralAttentionz=Multi-headed attention from 'Attention Is All You Need' paperN	embed_dim	num_headsr#   
is_decoderbias	is_causal	layer_idxconfigc	                 z   t         	|           || _        || _        || _        ||z  | _        || _        | j
                  |z  | j                  k7  rt        d| j                   d| d      | j
                  dz  | _        || _	        || _
        |/|r-t        j                  d| j                  j                   d       || _        t!        j"                  ||d      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        t!        j"                  |||      | _        y )	Nz;embed_dim must be divisible by num_heads (got `embed_dim`: z and `num_heads`: z).r&   zInstantiating a decoder z without passing `layer_idx` is not recommended and will to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` when creating this class.Fr=   )super__init__r:   r;   r#   head_dimr@   
ValueErrorr"   r<   r>   loggerwarning_once	__class____name__r?   r   Lineark_projv_projq_projout_proj)
selfr:   r;   r#   r<   r=   r>   r?   r@   rI   s
            r5   rD   zVoxtralAttention.__init__K   s     	""!Y.MMI%$..8MdnnM]$YKr3  }}d*$"*4>>+B+B*C D, ,
 #ii	95Aii	94@ii	94@		)YTBr7   tensorseq_lenbszc                     |j                  ||| j                  | j                        j                  dd      j	                         S )Nr   r   )viewr;   rE   r.   r1   )rP   rQ   rR   rS   s       r5   _shapezVoxtralAttention._shapes   s7    {{3GQQRSUVWbbddr7   hidden_statesr!   output_attentionsreturnc                 0   |j                         \  }}}| j                  | j                  |      | j                  z  ||      }| j                  | j	                  |      d|      }	| j                  | j                  |      d|      }
t        j                  | j                  j                  t              } || ||	|
|f| j                  sdn| j                  d|d|\  }}|j                  ||d      j                         }| j                  |      }||fS )z#Input shape: Batch x Time x Channelr%                 ?)r#   r"   rX   )r+   rV   rN   r"   rL   rM   r   get_interfacer@   _attn_implementationr6   r*   r#   reshaper1   rO   )rP   rW   r!   rX   r2   rS   tgt_len_query_states
key_statesvalue_statesattention_interfacer4   r3   s                 r5   forwardzVoxtralAttention.forwardv   s    (,,.Wa {{4;;}#=#LgWZ[[[]!;RE
{{4;;}#=r3G(?(M(MKK,,.E)
 %8
%
  $}}C$,,/
%
 
%
!\ "))#w;FFHmmK0L((r7   )r[   FTFNNNF)rJ   
__module____qualname____doc__intfloatboolr   rD   r,   TensorrV   tuplerf   __classcell__rI   s   @r5   r9   r9   H   s	   G   $'+&C&C &C 	&C
 &C &C &C :&C $&CPeU\\ eC ec e /3"'	')||') t+')  	') 
u||U\\D0%2E2LL	M')r7   r9   c                   ~     e Zd Zdef fdZdej                  dej                  dee   dej                  fdZ	 xZ
S )VoxtralEncoderLayerr@   c                 h   t         |           |j                  | _        t	        | j                  |j
                  |j                  |      | _        t        j                  | j                        | _
        |j                  | _        t        |j                     | _        |j                  | _        t        j                   | j                  |j"                        | _        t        j                   |j"                  | j                        | _        t        j                  | j                        | _        y )N)r:   r;   r#   r@   )rC   rD   d_modelr:   r9   encoder_attention_headsattention_dropout	self_attnr   	LayerNormself_attn_layer_normr#   r   activation_functionactivation_fnactivation_dropoutrK   encoder_ffn_dimfc1fc2final_layer_normrP   r@   rI   s     r5   rD   zVoxtralEncoderLayer.__init__   s    )nn44,,	
 %'LL$@!~~#F$>$>?"(";";99T^^V-C-CD99V33T^^D "T^^ <r7   rW   r!   r2   rY   c                     |}| j                  |      } | j                  d||d|\  }}t        j                  j	                  || j                  | j
                        }||z   }|}| j                  |      }| j                  | j                  |            }t        j                  j	                  || j                  | j
                        }| j                  |      }t        j                  j	                  || j                  | j
                        }||z   }|j                  t        j                  k(  rEt        j                  |j                        j                  dz
  }t        j                   || |      }|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 size
                `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
        )rW   r!   r(   i  )minmax )rz   rx   r   r/   r#   r*   r   r|   r   r}   r   dtyper,   float16finfor   clamp)rP   rW   r!   r2   residualra   clamp_values          r5   rf   zVoxtralEncoderLayer.forward   sT    !11-@)4>> 
')
 
q
 --mt||VZVcVc-d =0 --m<**488M+BC--mt?V?Vaeanan-o/--mt||VZVcVc-d =0%--/++m&9&9:>>EK!KKK<[YMr7   )rJ   rh   ri   r   rD   r,   rn   r   r   rf   rp   rq   s   @r5   rs   rs      sL    =} =$"||" " +,	"
 
"r7   rs   c                   F    e Zd ZU eed<   dZdZdZdZdgZ	dZ
dZdZdZdZdZy)VoxtralPreTrainedModelr@   model)audiotextTNpast_key_values)rJ   rh   ri   r   __annotations__base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_cache_class_supports_attention_backend_can_compile_fullgraphr   r7   r5   r   r      sL    (&*##4"5N "&!r7   r   z:
    The Voxtral encoder, which is a Whisper encoder.
    custom_introc                        e Zd ZU dZeed<   dZdZdgZe	e
dZdef fdZd Zd	ej                  fd
Zdej                  fdZee	 ddee   d	eez  fd              Zdej4                  fdZ xZS )VoxtralEncoderz
    Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
    [`VoxtralEncoderLayer`].

    Args:
        config: VoxtralEncoderConfig
    r@   input_featuresr   rs   )
attentionsrW   c                 b   t         |   |       |j                  | _        |j                  | _        |j
                  }|j                  | _        |j                  | _        |j                  rt        j                  |      nd| _        t        j                  | j                  |dd      | _        t        j                  ||ddd      | _        t        j                   | j                  |      | _        | j"                  j%                  d       t        j&                  t)        |j*                        D cg c]  }t-        |       c}      | _        t        j0                  |j
                        | _        t        j4                  dd      | _        d| _        | j;                          y c c}w )	Nr\   r   r   )kernel_sizepaddingr   )r   strider   F)r   )rC   rD   r#   encoder_layerdrop	layerdropru   num_mel_binsmax_source_positionsscale_embeddingmathsqrtembed_scaler   Conv1dconv1conv2	Embeddingembed_positionsrequires_grad_
ModuleListrangeencoder_layersrs   layersry   
layer_norm	AvgPool1d
avg_poolergradient_checkpointing	post_init)rP   r@   r:   ra   rI   s       r5   rD   zVoxtralEncoder.__init__   s6    ~~11NN	"//$*$?$?!393I3I499Y/sYYt00)TUV
YYy)1VWX
!||D,E,EyQ++E2mm%PVPePeJf$gQ%8%@$gh,,v~~6,,q3&+# %hs   6F,c                 J    | j                         D ]	  }d|_         d| _        y rg   )
parametersrequires_grad_requires_grad)rP   params     r5   _freeze_parametersz!VoxtralEncoder._freeze_parameters  s(    __& 	(E"'E	(#r7   rY   c                     | j                   S Nr   )rP   s    r5   get_input_embeddingsz#VoxtralEncoder.get_input_embeddings  s    zzr7   r    c                     || _         y r   r   )rP   r    s     r5   set_input_embeddingsz#VoxtralEncoder.set_input_embeddings!  s	    
r7   r2   c           	         | 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   r%   z7Voxtral expects the mel input features to be of length z, but found z-. Make sure to pad the input mel features to .r   devicer   r   r(   )r!   )last_hidden_state)r@   r   r   r   r   shaperF   toweightr   r   r   r/   gelupermuter   r#   r*   	enumerater   r   r   )
rP   r   r!   r2   expected_seq_lengthinputs_embeds	embed_posrW   idxencoder_layers
             r5   rf   zVoxtralEncoder.forward$  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)+
 	
r7   input_lengthsc                 6    |dz
  dz  dz   }|dz
  dz  dz   }||fS )zs
        Computes the output length of the convolutional layers and the output length of the audio encoder
        r   r   r   )rP   r   output_lengthss      r5    _get_feat_extract_output_lengthsz/VoxtralEncoder._get_feat_extract_output_lengthsT  s7     '*q014'!+1A5n,,r7   r   )rJ   rh   ri   rj   r   r   main_input_namer   r   r9   rs   _can_record_outputsrD   r   r   Moduler   r   r   r   r   r   ro   r   rf   r,   
LongTensorr   rp   rq   s   @r5   r   r      s     ! &O./&,
3 2$
bii "))    +
 +,	+

 
+	++
   +
\-e>N>N -r7   r   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 NFrB   )rC   rD   r   rK   audio_configintermediate_sizetext_confighidden_sizelinear_1r   projector_hidden_actactlinear_2r   s     r5   rD   z#VoxtralMultiModalProjector.__init__^  sz    		&"5"5"G"GI[I[IgIgnst&556		&"4"4"@"@&BTBTB`B`glmr7   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r   r   r   )rP   audio_featuresrW   s      r5   rf   z"VoxtralMultiModalProjector.forwardd  s2    n5/m4r7   )rJ   rh   ri   r   rD   rf   rp   rq   s   @r5   r   r   ]  s    n} nr7   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)rJ   rh   ri   rj   r   r,   FloatTensorr   r   r7   r5   r   r   k  s    
 59**T18r7   r   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 r   )rC   rD   r   from_configr   audio_towerr   language_modelr   multi_modal_projectorr   r   s     r5   rD   zVoxtralModel.__init__  sY     $001D1DE'33F4F4FG%?%G"r7   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   r   r2   rY   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_dictTr%   )r   r   r_   r@   r   r   r   pooler_output)rP   r   r2   audio_outputsr   audio_embedss         r5   get_audio_featureszVoxtralModel.get_audio_features  sn     )((TTTVT+==199"dkk>V>V>h>hi112EF&2#r7   	input_idsr   r   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.
        r   r%   r   z6Audio features and audio tokens do not match, tokens: z, features: )r   r,   rQ   r@   audio_token_idlongr   allsumr   	unsqueeze	expand_asr   r   numel)rP   r  r   r   special_audio_maskn_audio_tokensn_audio_featuress          r5   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	
 "!r7   Nr!   position_idsr   	use_cachec           	         | | j                         |      }d }	|^|\| j                  |d      j                  }	| j                  |||	      }
|j	                  |
|	j                  |j                              } | j                  d|||||d|}t        |j                  |j                  |j                  |j                  |	      S )NT)r   )r   r   )r!   r  r   r   r  )r   r   rW   r   r   r   )r   r  r   r  masked_scatterr   r   r   r   r   r   rW   r   )rP   r  r   r!   r  r   r   r  r2   r  r  outputss               r5   rf   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!//)) ,
 	
r7   )NNNNNNN)rJ   rh   ri   rD   r   r   r,   r   r   r   ro   r   r  r   r  rn   r   rm   r   rf   rp   rq   s   @r5   r   r   z  s\     w#//;ABT;U	+	+ &"))":?:K:K"]b]n]n"0  .237.204(,26!%'
##d*'
 ))D0'
 t+	'

 &&-'
 '
 ((4/'
 $;'
 +,'
 
+	+'
  '
r7   r   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 )VoxtralForConditionalGenerationr   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y r   )rC   rD   r   r   r   rK   r   r   
vocab_sizelm_headr   r   s     r5   rD   z(VoxtralForConditionalGeneration.__init__  sS     !&)
yy!3!3!?!?ASASA^A^ejkr7   c                 :     | j                   j                  |i |S r   )r   r  )rP   argsr2   s      r5   r  z2VoxtralForConditionalGeneration.get_audio_features  s    ,tzz,,d=f==r7   Nr  r   r!   r  r   r   labelsr  logits_to_keepr2   rY   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  r   r!   r  r   r   r  N)logitsr  r  )lossr  r   rW   r   r   )r   r   
isinstancerk   slicer  loss_functionr@   r   r  r   r   rW   r   )rP   r  r   r!   r  r   r   r  r  r  r2   r  rW   slice_indicesr  r   s                   r5   rf   z'VoxtralForConditionalGeneration.forward  s    ` $** 	
))%+'	
 	
  118B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD &#33!//))
 	
r7   c                     |j                  dd       }|j                  dd      }t        |   |i |}|s|j                  dd      s||d<   |S )Nr   is_first_iterationFr  T)popgetrC   prepare_inputs_for_generation)rP   r  r2   r   r&  model_inputsrI   s         r5   r)  z=VoxtralForConditionalGeneration.prepare_inputs_for_generationA  s]      $4d;#ZZ(<eDw<dMfMVZZT%B-;L)*r7   )	NNNNNNNNr   )rJ   rh   ri   _keep_in_fp32_modules_strictrD   r  r   r   r,   r   r   rn   r   rm   rk   r   r   ro   r   rf   r)  rp   rq   s   @r5   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 r7   r  )r   r   r   r  )Nr[   )7r   collections.abcr   dataclassesr   r,   r   activationsr   cache_utilsr   
generationr	   modeling_layersr
   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   utils.output_capturingr   autor   configuration_voxtralr   r   
get_loggerrJ   rG   r   rn   rl   r6   r9   rs   r   r   r   r   r   r  __all__r   r7   r5   <module>r<     s  ,  $ !   !   ) 9 k k F & j j 7 5  F 
		H	% !%II%<<% 
% <<	%
 LL4'% T\% %4U)ryy U)p54 5p "_ " " 
m-+ m-
m-`  
 9!8 9 9 `
) `
`
F 
e&<o e
eP jr7   