
    ^jW                     8   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 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 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(  e#       rd dlZ G d dejR                        Z*e! G d de             Z+e G d de             Z, G d dejR                        Z-d Z.d Z/ e!d        G d! d"e+             Z0 e!d#       e G d$ d%e                    Z1 e!d&        G d' d(e+e             Z2g d)Z3y)*    )Callable)	dataclass)pi)Optional)Tensorbroadcast_tensorsnn   )initialization)ACT2FN)Cache)GenerationMixin)BaseModelOutputWithPastBaseModelOutputWithPoolingModelOutput)ROPE_INIT_FUNCTIONS)PreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_torch_availabletorch_compilable_check   )	AutoModel   )MusicFlamingoConfigNc                        e Zd ZU dZej
                  ed<   ddef fdZe		 	 	 ddedz  de
d   dedz  d	ed
ef   fd       Z ej                         deded	eeef   fd       Zd Z xZS )MusicFlamingoRotaryEmbeddinga  Rotary time embedding module used by MusicFlamingo checkpoints.

    This is a checkpoint-faithful integration, not a direct implementation of the RoTE formulation described in
    (Goel et al., 2024): https://arxiv.org/abs/2410.12109. It applies axial rotary embeddings over the window index
    within each audio sample and the encoder time index within each window, then modulates both axes with absolute
    timestamps in seconds.
    inv_freqNconfigc                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       | j                  | j                        }| j                  d|d       y )N	rope_typedefaultr    F)
persistentoriginal_inv_freqposition_angles)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr!   rope_parametersr#   compute_default_rope_parametersr   attention_scalingregister_bufferclone_compute_position_anglesr    )selfr!   devicerope_init_fnr    r'   	__class__s         /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/musicflamingo/modeling_musicflamingo.pyr)   z%MusicFlamingoRotaryEmbedding.__init__9   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuU77F.ER    r4   ztorch.deviceseq_lenreturnztorch.Tensorc                 n   | j                   d   }| j                   j                  dd      }t        | dd      xs | j                  | j                  z  }t        ||z        }d}d|t        j                  d|dt        j                        j                  |t        j                  	      |z  z  z  }||fS )
a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetapartial_rotary_factorg      ?head_dimNr   r   dtyper4   r@   )r-   getgetattrhidden_sizenum_attention_headsinttorcharangeint64tofloat)	r!   r4   r9   baser=   r>   dimattention_factorr    s	            r7   r.   z<MusicFlamingoRotaryEmbedding.compute_default_rope_parametersK   s    & %%l3 & 6 6 : :;RTW X6:t4h8J8JfNhNh8h(223 U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r8   
timestampsc                    |dddf   j                  | j                  j                  | j                  j                        }| j                  j
                  dz  |z  }t        j                  ||z        | j                  z  }|j                  d      | j                  z  }t        j                  |dd      }|dddddf   }| j                  d| dddddf   }t        ||      \  }}t        j                  ||fd      }| dz  t        z  j                  |      }	||	j                  d      z  }|j                         |j!                         fS )zBCompute 2D axial rotary embeddings for window and time dimensions.Nr   rA      r   rM   )rJ   r    r4   r@   r!   audio_frame_steprG   roundr+   	unsqueezerepeat_interleaver'   r   catr   cossin)
r3   rO   r9   window_startswindow_durationwindow_positionswindow_freqs
time_freqsfreqsangles
             r7   forwardz$MusicFlamingoRotaryEmbedding.forwardk   s5   
 #1a4(++4==3G3Gt}}ObOb+c++66:WD ;;}'FG$JaJaa'11"5E..|QBG $AtQJ/))(73D!QJ?
#4\:#N j		<4"=q2%))%0++yy{EIIK''r8   c                 B   t        j                  t        | j                        |j                  |j
                        }|| j                  z  dt        z  z  }|j                  d      |z  }t        j                  |dd      }|j                  |j
                        S )NrA   r   rR   rS   r?   )
rG   rH   rF   r+   r4   r@   r   rV   rW   rJ   )r3   r    	positionsr'   s       r7   r2   z5MusicFlamingoRotaryEmbedding._compute_position_angles   s    LLT%<%<!=hoo]e]k]kl	 7 771r6B	#--b1H<11/1"M!!!77r8   N)NNN)__name__
__module____qualname____doc__rG   r   __annotations__r   r)   staticmethodr   rF   tuplerK   r.   no_gradrb   r2   __classcell__r6   s   @r7   r   r   .   s     llS2 S$ -1+/"*#d**(* t* 
~u$	%	* *> U]]_(& (3 (5;P ( (&8r8   r   c                   t     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 ej                          fd       Z xZS )MusicFlamingoPreTrainedModelr!   model)audiotextTNpast_key_valuesc                     t         |   |       t        |t              r<|j	                  |j
                        }t        j                  |j                  |       y y re   )	r(   _init_weights
isinstancer   r2   r    initcopy_r'   )r3   modulebuffer_valuer6   s      r7   rw   z*MusicFlamingoPreTrainedModel._init_weights   sH    f%f:;!::6??KLJJv--|< <r8   )rf   rg   rh   r   rj   base_model_prefixinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_attention_backendrG   rm   rw   rn   ro   s   @r7   rq   rq      sU    (&*##4"5N"&U]]_= =r8   rq   c                   :    e Zd ZU dZdZej                  dz  ed<   y) MusicFlamingoModelOutputWithPastzg
    audio_hidden_states (`torch.FloatTensor`, *optional*):
        Projected audio hidden states.
    Naudio_hidden_states)rf   rg   rh   ri   r   rG   FloatTensorrj    r8   r7   r   r      s    
 59**T18r8   r   c                   .     e Zd ZdZdef fdZd Z xZS ) MusicFlamingoMultiModalProjectorz
    Audio adaptor (small MLP) that projects MusicFlamingoEncoder features
    to the LLM embedding space so they can replace `<sound>` tokens.
    r!   c                    t         |           t        j                  |j                  j
                  |j                  j
                  |j                        | _        t        |j                     | _        t        j                  |j                  j
                  |j                  j
                  |j                        | _        y )Nbias)r(   r)   r	   Linearaudio_configrD   text_configprojector_biaslinear_1r   projector_hidden_actactlinear_2r3   r!   r6   s     r7   r)   z)MusicFlamingoMultiModalProjector.__init__   s    		++V-?-?-K-KRXRgRg
 &556		**F,>,>,J,JQWQfQf
r8   c                 l    | j                  |      }| j                  |      }| j                  |      }|S re   )r   r   r   )r3   audio_featureshidden_statess      r7   rb   z(MusicFlamingoMultiModalProjector.forward   s2    n5/m4r8   )rf   rg   rh   ri   r   r)   rb   rn   ro   s   @r7   r   r      s    

2 
r8   r   c                      | j                   g | j                  d d dd } | j                  d      \  }}t        j                  | |fd      } | j                  d      S )NrR   r   rS   )reshapeshapeunbindrG   stackflatten)xx1x2s      r7   rotate_halfr      sa    		'1773B<''Q'AXX"XFBbS"I2&A99R=r8   c                 V   | j                   }| j                  t        j                        } |j                  |       }|j                  |       }|j                  d   }| d|d f   }| dd |f   }||z  t        |      |z  z   }t        j                  ||fd      j                  |      S )NrR   .rS   )r@   rJ   rG   float64r   r   rX   )r   rY   rZ   original_dtyperot_dimpassthroughrotateds          r7   apply_rotary_time_embr      s    "((N!$$U]]3M
&&
C
&&
CiimGWX.KC'M*G}W!5!;<G99g{+477GGr8   z
    The MusicFlamingo model (fine-tuned Whisper encoder, multi-modal projector, Qwen2 language model),
    without a language modeling head.
    custom_introc                   d    e Zd ZdZdZdZdef fdZe e	d      de
j                  de
j                  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
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de
j                  de
j                  ded
e
j                  fdZ xZS )MusicFlamingoModelNr!   c                    t         |   |       t        j                  |j                        | _        t        j                  |j                        | _        t        |      | _	        t        |      | _        | j                          y re   )r(   r)   r   from_configr   audio_towerr   language_modelr   multi_modal_projectorr   pos_emb	post_initr   s     r7   r)   zMusicFlamingoModel.__init__   se     $001D1DE'33F4F4FG%Ef%M"3F;r8   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   input_featuresinput_features_mask	input_idskwargsr:   c                     | j                   |f|dd|}|j                  }| j                   j                  |j                  d      j	                  t
        j                              \  }}| j                  |||j                  d         }	| j                  |	j	                  |j                        |j                  d         \  }
}t        ||
|      }| j                  |      }t        j                  |j                  d   |j                        dddf   |dddf   k  }||j	                  |j                           |_        |S )	az  
        input_features_mask (`torch.Tensor` of shape `(batch_size, feature_sequence_length)`):
            Mask to avoid performing attention on padded feature indices.
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Token ids containing the audio token ID placeholders, for reconstructing rotary time embedding timestamps.
        T)r   return_dictrR   r   )r9   r   r4   N)r   last_hidden_state _get_feat_extract_output_lengthssumrJ   rG   long_build_audio_timestampsr   r   r4   r   r   rH   pooler_output)r3   r   r   r   r   audio_outputr   _post_lengthsaudio_timestampsrY   rZ   audio_embeds
valid_masks                 r7   get_audio_featuresz%MusicFlamingoModel.get_audio_features   sL   " (t''
 3
 	
 %66**KKL_LcLcdfLgLjLjkpkukuLvw<77	<Q^QdQdegQhi<< 0 3 3M4H4H IS`SfSfgiSj<kS-mS#F11-@ \\,"4"4Q"7@S@STUY[\U\]`lmnptmt`uu
%1*--@S@S2T%U"r8   inputs_embedsr   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@   r4   rR   r   6Audio features and audio tokens do not match, tokens: , features: )get_input_embeddingsrG   tensorr!   audio_token_idr   r4   allr   r   rV   	expand_asrJ   r   numel)r3   r   r   r   special_audio_maskn_audio_tokensn_audio_featuress          r7   get_placeholder_maskz'MusicFlamingoModel.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	
 "!r8   attention_maskposition_idsru   	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   r   )r   r   )r   r   r   ru   r   )r   ru   r   
attentionsr   r   )r   r   r   r   masked_scatterrJ   r4   r   r   r   ru   r   r   )r3   r   r   r   r   r   ru   r   r   r   r   r   outputss                r7   rb   zMusicFlamingoModel.forward  s   $  7D557	BM%)*?22 3yVZ 3 m 
 "&!:!:| "; " *889K\__]j]q]qMrsM%$%% 
')%+
 
 0%77#33!//)) ,
 	
r8   r   max_post_lengthc                    || j                   j                  k(  }t        j                  t        j                  j
                  j                  |j                         dd      d      }t        j                  |dk(        \  }}t        j                  |dk(        \  }}||z
  j                  t        j                        }	|j                         }
|j                         }t        |
|k(  d|
 d|        | j                   j                  d	z  }t        j                  ||j                  t        j                   
      |z  }t        j"                  t        j$                  d|j                        t        j&                  |d      d d g      }t        j&                  |	d      }t        j(                  ||d      }t        j(                  |t        j                  |	j*                  d   |j                              }t        j                  |j*                  d   |j                        ||   z
  }|j-                  d      |z  |z  |z   S )N)r   r   r   )valuer   rS   rR   r   r   rQ   rA   r   T)right)r!   r   rG   diffr	   
functionalpadrF   whererJ   r   r   r   rT   rH   r4   float32rX   zeroscumsumsearchsortedr   rV   )r3   r   r   r   audio_token_maskr   r   startsendssample_lengthsr   r   audio_embed_frame_stepframe_offsetscumsum_postcumsum_samplessample_indicessample_start_rowswindow_indicess                      r7   r   z*MusicFlamingoModel._build_audio_timestampsQ  s    %(B(BBzz%((--112B2F2F2H&XY1Z`abKK	*	6++dbj)4-++EJJ7)--/'++-..D^DTT`aq`rs	
 "&!=!=!ALL1D1DEMMZ]ss 	
 iiQ|7J7J!KU\\ZflmMnorprMs tun!<++NKtT "..ELL)=)=a)@I\I\]
 LL++A.|7J7JKN_`nNoo 	
 ''*_<?UUXeeer8   )NNNNNNNN)rf   rg   rh   _tp_plan_pp_plan_keep_in_fp32_modules_strictr   r)   r   r   rG   r   r   
LongTensorr   r   rl   r   r   r   r   boolr   rb   rF   r   rn   ro   s   @r7   r   r      s    HH#' 2   w)) #\\ ##	
 +, 
+	+ @"))":?:K:K"]b]n]n"0  .23737.204(,26!%.
##d*.
 ))D0.
 #\\D0	.

 t+.
 &&-.
 .
 ((4/.
 $;.
 +,.
 
1	1.
  .
`'f##'f &&'f 	'f
 
		'fr8   r   zY
    Base class for MusicFlamingo causal language model (or autoregressive) outputs.
    c                       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)	#MusicFlamingoCausalLMOutputWithPastaV  
    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logitsru   r   r   r   )rf   rg   rh   ri   r   rG   r   rj   r   ru   r   r   rl   r   r   r   r8   r7   r   r   {  s    	 &*D%

d
")'+FE$+$(OUT\(59M5**+d2926Je''(4/648**T18r8   r   z
    The MusicFlamingo model which consists of a fine-tuned Whisper encoder, rotary time embedding, a multi-modal projector, and a Qwen2 language model.
    c                       e Zd ZdgZdZdef 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 )%MusicFlamingoForConditionalGenerationembed_positionsNr!   c                     t         |   |       t        |      | _        t	        j
                  |j                  j                  |j                  j                  d      | _	        | j                          y )NFr   )r(   r)   r   rr   r	   r   r   rD   
vocab_sizelm_headr   r   s     r7   r)   z.MusicFlamingoForConditionalGeneration.__init__  sS     '/
yy!3!3!?!?ASASA^A^ejkr8   c                 @     | j                   j                  |||fi |S re   )rr   r   )r3   r   r   r   r   s        r7   r   z8MusicFlamingoForConditionalGeneration.get_audio_features  s%    ,tzz,,^=PR[f_effr8   r   r   r   r   r   ru   r   labelsr   logits_to_keepr   r:   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 MusicFlamingoForConditionalGeneration, AutoProcessor

        >>> model_id = "nvidia/audio-flamingo-3-hf"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto")
        ```)r   r   r   r   r   ru   r   r   N)r   r  r  )r   r   ru   r   r   r   r   )rr   r   rx   rF   slicer  loss_functionr!   r   r  r   ru   r   r   r   )r3   r   r   r   r   r   ru   r   r  r   r	  r   r   r   slice_indicesr   r   s                    r7   rb   z-MusicFlamingoForConditionalGeneration.forward  s    > $** 

) 3)%+'

 

  118B>SV8W~ot4]kmA}a,?@A%4%% f9P9P9[9[_eD 3#33!//)) ' ; ;
 	
r8   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)popr(   prepare_inputs_for_generationrB   )r3   r  argsr   r   r   model_inputsr6   s          r7   r  zCMusicFlamingoForConditionalGeneration.prepare_inputs_for_generation  st    $4d;$jj)>Ew<dMfM\%5%5k5%I)1?-.".6I23r8   )
NNNNNNNNNr   )rf   rg   rh   r   _tied_weights_keysr   r)   r   r   r   rG   r   r   r   r   r   rF   r   r   rl   r   rb   r  rn   ro   s   @r7   r  r    sX    %6#6 2 g  .23737.204(,26*.!%-.:
##d*:
 ))D0:
 #\\D0	:

 t+:
 &&-:
 :
 ((4/:
   4':
 $;:
 ell*:
 +,:
 
4	4:
  :
x OT t  r8   r  )r  r   rq   )4collections.abcr   dataclassesr   mathr   typingr   rG   r   r   r	    r   ry   activationsr   cache_utilsr   
generationr   modeling_outputsr   r   r   modeling_rope_utilsr   modeling_utilsr   processing_utilsr   utilsr   r   r   r   r   autor   configuration_musicflamingor   Moduler   rq   r   r   r   r   r   r   r  __all__r   r8   r7   <module>r&     s@  , % !   / / & !   ) ` ` 6 - & u u  < V8299 V8r =? = =& 9'> 9 9ryy .
H bf5 bfbfJ 
 9+ 9 9( 
W,H/ W
Wt jr8   