
    ^j7                     >   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 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mZ ddlmZmZmZmZ ddl m!Z!m"Z" ddl#m$Z$  ejJ                  e&      Z' G d de!      Z( G d de"      Z) G d de      Z*e G d de             Z+ ed      e G d de                    Z, ed       G d  d!e             Z- G d" d#e      Z. ed$       G d% d&e             Z/ ed'       G d( d)e             Z0g d*Z1y)+    )	dataclassN)nn   )ACT2FN)Cache)create_bidirectional_mask)BaseModelOutputWithPoolingModelOutput)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)merge_with_config_defaults)capture_outputs   )Qwen2AudioEncoderQwen2AudioPreTrainedModel)VoxtralForConditionalGenerationVoxtralModelVoxtralModelOutputWithPastVoxtralMultiModalProjector)WhisperAttentionWhisperEncoderLayer   )AudioFlamingo3Configc                       e Zd Zy)AudioFlamingo3AttentionN__name__
__module____qualname__     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/audioflamingo3/modular_audioflamingo3.pyr   r   .       r$   r   c                       e Zd Zy)AudioFlamingo3EncoderLayerNr   r#   r$   r%   r(   r(   2   r&   r$   r(   c                       e Zd ZdZy)AudioFlamingo3PreTrainedModelTN)r    r!   r"   _supports_attention_backendr#   r$   r%   r*   r*   6   s    "&r$   r*   c                       e Zd Zy)!AudioFlamingo3ModelOutputWithPastNr   r#   r$   r%   r-   r-   :   s    r$   r-   zZ
    Base class for AudioFlamingo3 causal language model (or autoregressive) outputs.
    custom_introc                       e Zd ZU dZdZej                  dz  ed<   dZej                  dz  ed<   dZ	e
dz  ed<   dZeej                     dz  ed<   dZeej                     dz  ed<   dZej                  dz  ed<   y)	$AudioFlamingo3CausalLMOutputWithPastaV  
    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.
    past_key_values (`Cache`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
        It is a [`~cache_utils.Cache`] instance.
    audio_hidden_states (`torch.FloatTensor`, *optional*):
        Hidden states of the audio encoder after projection.
    Nlosslogitspast_key_valueshidden_states
attentionsaudio_hidden_states)r    r!   r"   __doc__r2   torchFloatTensor__annotations__r3   r4   r   r5   tupler6   r7   r#   r$   r%   r1   r1   ?   s    	 &*D%

d
")'+FE$+$(OUT\(59M5**+d2926Je''(4/648**T18r$   r1   zT
    The audio model from AudioFlamingo3 without any head or projection on top.
    c            
       z    e Zd ZdZeedZee	 dde	j                  de	j                  dz  deez  fd              Zy)	AudioFlamingo3EncoderzY
    AudioFlamingo3 encoder: Whisper encoder, average pool (time/2), then LayerNorm.
    )r5   r6   Ninput_featuresinput_features_maskreturnc                    |j                   d   dz
  dz  dz   }|j                  d      }|dz
  dz  dz   }t        j                  ||j                        |dddf   k  }t
        j                  j                  | j                  |            }t
        j                  j                  | j                  |            }|j                  ddd      }|| j                  j                  z   }t
        j                  j                  || j                  | j                        }t        | j                   ||      }| j"                  D ]>  }	| j                  xr" t        j$                  g       | j&                  k  }
|
r6 |	||      }@ |j                  ddd      }| j)                  |      j                  ddd      }| j+                  |      }t-        |	      S )
ap  
        Args:
            input_features (`torch.FloatTensor` of shape `(batch_size, feature_size, sequence_length)`):
                Log-Mel features extracted from raw audio. Use the processor/feature extractor to compute and pad
                these features from waveform input.
            input_features_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding feature indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.
        r   r   deviceNr   )ptraining)configinputs_embedsattention_mask)last_hidden_state)shapesumr9   arangerE   r   
functionalgeluconv1conv2permuteembed_positionsweightdropoutrG   r   rH   layersrand	layerdrop
avg_pooler
layer_normr	   )selfr?   r@   kwargsseq_leninput_features_lengthsrI   r5   rJ   layerdrops              r%   forwardzAudioFlamingo3Encoder.forwardh   s   ( "''+a/A59!4!8!8!<"81"<!BQ!F#ll7>;P;PQTjklnrkrTss **4::n+EF**4::m+DE%--aA6 &(<(<(C(CC--mt||VZVcVc-d2;;'.
 [[ 	EE==DUZZ^dnn%DD %m^ D	E &--aA66>>q!QG6)+
 	
r$   N)r    r!   r"   r8   r(   r   _can_record_outputsr   r   r9   Tensorr<   r	   rb   r#   r$   r%   r>   r>   Y   sg    
 4-
   483
3
 #\\D03

 
+	+3
   3
r$   r>   c                   (     e Zd ZdZdef fdZ xZS )!AudioFlamingo3MultiModalProjectorz
    Audio adaptor (small MLP) that projects AudioFlamingo3Encoder features
    to the LLM embedding space so they can replace `<sound>` tokens.
    rH   c                    t         |           t        j                  |j                  j
                  |j                  j
                  |j                        | _        t        |j                     | _        t        j                  |j                  j
                  |j                  j
                  |j                        | _        y )N)bias)super__init__r   Linearaudio_confighidden_sizetext_configprojector_biaslinear_1r   projector_hidden_actactlinear_2r\   rH   	__class__s     r%   rk   z*AudioFlamingo3MultiModalProjector.__init__   s    		++V-?-?-K-KRXRgRg
 &556		**F,>,>,J,JQWQfQf
r$   )r    r!   r"   r8   r   rk   __classcell__rv   s   @r%   rg   rg      s    

3 
 
r$   rg   z
    The AudioFlamingo3 model (fine-tuned Whisper encoder, multi-modal projector, Qwen2 language model),
    without a language modeling head.
    c                       e Zd ZdZdZdZ fdZe ed      de	j                  de	j                  dee   deez  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	j"                  dz  dedz  de	j                  dz  dedz  dee   fd              Z xZS )AudioFlamingo3ModelNc                 $    t         |   |       y rc   )rj   rk   ru   s     r%   rk   zAudioFlamingo3Model.__init__   s     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.   r?   r@   r]   rA   c                     | j                   |f|dd|}| j                  |j                        }|j                  d      j	                  t
        j                        }| j                   j                  |      \  }}t        j                  |j                  d   |j                        dddf   |dddf   k  }	||	j	                  |j                           |_        |S )a1  
        input_features (`torch.FloatTensor`):
            Float values of mel features extracted from the raw speech waveform.
        input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
            Mask to avoid performing attention on padded feature indices.
        T)r@   return_dictrC   r   rD   N)audio_towermulti_modal_projectorrK   rM   tor9   long _get_feat_extract_output_lengthsrN   rL   rE   pooler_output)
r\   r?   r@   r]   audio_outputaudio_embedsinput_lengths_post_lengths
valid_masks
             r%   get_audio_featuresz&AudioFlamingo3Model.get_audio_features   s    " (t''
0CQU
Y_
 11,2P2PQ ,//366uzzB**KKMZ<\\,"4"4Q"7@S@STUY[\U\]`lmnptmt`uu
%1*--@S@S2T%U"r$   	input_idsrJ   position_idsr4   rI   	use_cachec	           	         | | j                         |      }d}
|_|]| j                  ||d      j                  }
| j                  |||
      }|j	                  ||
j                  |j                              } | j                  d|||||d|	}t        |j                  |j                  |j                  |j                  |
      S )z
        input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
            Mask to avoid performing attention on padding feature indices.
        NT)r}   )rI   audio_features)rI   rJ   r   r4   r   )rK   r4   r5   r6   r7   r#   )get_input_embeddingsr   r   get_placeholder_maskmasked_scatterr   rE   language_modelr-   rK   r4   r5   r6   )r\   r   r?   r@   rJ   r   r4   rI   r   r]   r   special_audio_maskoutputss                r%   rb   zAudioFlamingo3Model.forward   s    $  7D557	BM%)*?22>CVdh2iwwL "&!:!:| "; " *889K\__]j]q]qMrsM%$%% 
')%+
 
 1%77#33!//)) ,
 	
r$   )NNNNNNNN)r    r!   r"   _tp_plan_pp_plan_keep_in_fp32_modules_strictrk   r   r   r9   r:   re   r   r   r<   r	   r   
LongTensorr   boolrb   rw   rx   s   @r%   rz   rz      sW    HH#' !  w)) #\\ +,	
 
+	+ 4  .23737.204(,26!%,
##d*,
 ))D0,
 #\\D0	,

 t+,
 &&-,
 ,
 ((4/,
 $;,
 +,,
  ,
r$   rz   z
    The AudioFlamingo3 model which consists of a fine-tuned Whisper encoder, a multi-modal projector and a Qwen2 language model.
    c                       e Zd Zd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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dddef fdZ xZS )&AudioFlamingo3ForConditionalGenerationNc                 d    t         |   |       t        |      | _        | j	                          y rc   )rj   rk   rz   model	post_initru   s     r%   rk   z/AudioFlamingo3ForConditionalGeneration.__init__  s&     (0
r$   c                 >     | j                   j                  ||fi |S rc   )r   r   )r\   r?   r@   r]   s       r%   r   z9AudioFlamingo3ForConditionalGeneration.get_audio_features  s"    ,tzz,,^=P[TZ[[r$   r   r?   r@   rJ   r   r4   rI   labelsr   logits_to_keepr]   rA   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                  |j                        S )a  
        input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
            Mask to avoid performing attention on padding feature indices.
        labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
            Labels for computing the masked language modeling loss.

        Example:

        ```python
        >>> from transformers import AudioFlamingo3ForConditionalGeneration, AutoProcessor

        >>> model_id = "nvidia/audio-flamingo-3-hf"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = AudioFlamingo3ForConditionalGeneration.from_pretrained(model_id, device_map="auto")
        ```)r   r?   r@   rJ   r   r4   rI   r   N)r3   r   
vocab_size)r2   r3   r4   r5   r6   r7   r#   )r   rK   
isinstanceintslicelm_headloss_functionrH   ro   r   r1   r4   r5   r6   r7   )r\   r   r?   r@   rJ   r   r4   rI   r   r   r   r]   r   r5   slice_indicesr3   r2   s                    r%   rb   z.AudioFlamingo3ForConditionalGeneration.forward  s    > $** 

) 3)%+'

 

  118B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD 4#33!//)) ' ; ;
 	
r$   F)is_first_iterationr   c                    |j                  dd       }|j                  dd       }t        |   |i |}|s|j                  dd      s|||d<   |||d<   |S )Nr?   r@   r   F)poprj   prepare_inputs_for_generationget)r\   r   argsr]   r?   r@   model_inputsrv   s          r%   r   zDAudioFlamingo3ForConditionalGeneration.prepare_inputs_for_generation\  st    $4d;$jj)>Ew<dMfM\%5%5k5%I)1?-.".6I23r$   )
NNNNNNNNNr   )r    r!   r"   _tied_weights_keysrk   r   r   r   r9   r   r:   re   r   r   r   r   r   r<   r1   rb   r   rw   rx   s   @r%   r   r     sG    
\  .23737.204(,26*.!%-.:
##d*:
 ))D0:
 #\\D0	:

 t+:
 &&-:
 :
 ((4/:
   4':
 $;:
 ell*:
 +,:
 
5	5:
  :
x OT t  r$   r   )r   r*   r>   rz   )2dataclassesr   r9   r   activationsr   cache_utilsr   masking_utilsr   modeling_outputsr	   r
   processing_utilsr   utilsr   r   r   r   utils.genericr   utils.output_capturingr    qwen2_audio.modeling_qwen2_audior   r   voxtral.modeling_voxtralr   r   r   r   whisper.modeling_whisperr   r   configuration_audioflamingo3r   
get_loggerr    loggerr   r(   r*   r-   r1   r>   rg   rz   r   __all__r#   r$   r%   <module>r      sW    "   !   6 G & R R 7 5  M > 
		H	%	. 		!4 	'$= ' 	(B 	 	 
 9; 9 9( 
?
- ?

?
D
(B 
" T
, T
T
n 
U-L U
Upr$   