
    ^jE
                    D   d Z ddlZddlm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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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(  e$jR                  e*      Z+e#e G d de!                    Z, G d d      Z-e#e G d de!                    Z.e#e G d de!                    Z/ G d de	j`                        Z1 G d d e	j`                        Z2 G d! d"e	j`                        Z3 G d# d$e	j`                        Z4 G d% d&e	j`                        Z5 G d' d(e	j`                        Z6d) Z7dPd*Z8 G d+ d,e	j`                        Z9d-ejt                  d.e;d/ejt                  fd0Z<	 dQd1e	j`                  d2ejt                  d3ejt                  d4ejt                  d5ejt                  dz  d6e=d7e=d8ee"   fd9Z> G d: d;e	j`                        Z? G d< d=e      Z@ G d> d?e	j`                        ZA G d@ dAe	j`                        ZB G dB dCe	j`                        ZC G dD dEe	j`                        ZD G dF dGe	j`                        ZE G dH dIe	j`                        ZFe# G dJ dKe             ZG e#dLM       G dN dOeG             ZHdOdKgZIy)RzPyTorch Mimi model.    N)Callable)	dataclass)Optional)nn   )initialization)ACT2FN)CacheDynamicCache)!create_sliding_window_causal_mask)GradientCheckpointingLayer)BaseModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringlogging)maybe_autocast   )
MimiConfigc                       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dz  ed<   y)
MimiOutputaV  
    audio_codes (`torch.LongTensor`  of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
        Discrete code embeddings computed using `model.encode`.
    audio_values (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
        Decoded audio values, obtained using the decoder part of Mimi.
    encoder_past_key_values (`Cache`, *optional*):
        Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
        This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

        The model will output the same cache format that is fed as input.

        If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
        have their past key value states given to this model).
    decoder_past_key_values (`Cache`, *optional*):
        Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
        This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

        The model will output the same cache format that is fed as input.

        If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
        have their past key value states given to this model).
    Naudio_codesaudio_valuesencoder_past_key_valuesdecoder_past_key_values)__name__
__module____qualname____doc__r   torch
LongTensor__annotations__r   FloatTensorr   r
   r         q/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/mimi/modeling_mimi.pyr   r   )   sQ    . ,0K!!D(/-1L%##d*1,0UT\0,0UT\0r*   r   c            	           e Zd ZdZdedee   dee   dee   fdZdej                  defd	Z
dej                  defd
Zy)MimiConv1dPaddingCachea  
    Padding cache for MimiConv1d causal convolutions in order to support streaming via cache padding.
    See: https://huggingface.co/papers/2005.06720 & https://huggingface.co/papers/2204.07064

    A padding cache is a list of cached partial hidden states for each convolution layer.
    Hidden states are cached from the previous call to the MimiConv1d forward pass, given the padding size.
    
num_layersper_layer_paddingper_layer_padding_modeper_layer_in_channelsc                     t        |      t        |      t        |      h}t        |      dk7  s|j                         |k7  rt        d| d      || _        || _        || _        d g|z  | _        y )Nr   zExpected `num_layers` (zU) values in `per_layer_padding`, `per_layer_padding_mode` and `per_layer_in_channels`)lenpop
ValueErrorr/   r0   r1   padding_cache)selfr.   r/   r0   r1   from_args_num_layerss         r+   __init__zMimiConv1dPaddingCache.__init__R   s     !$$5 6<R8SUXYnUop#$)-A-E-E-G:-U)*  6K  L  "3&<#%:""Vj0r*   hidden_states	layer_idxc                 `   |j                   d   |j                  |j                  }}}| j                  |   | j                  |   | j
                  |   }}}|dk(  rt        j                  |||||      }	|	S |dk(  r&t        j                  |||||      |dddf   z  }	|	S t        d| d	      )
ad  
        Initialize the cache for a specific layer.

        Parameters:
            hidden_states (`torch.Tensor`):
                The hidden states to initialize the cache with.
            layer_idx (`int`):
                The index of the layer to initialize the cache for.
        Returns:
            `torch.Tensor`, the initialized cache.
        r   constantdevicedtype	replicate.Nr   zPadding mode z not supported)
shaper@   r?   r/   r0   r1   r%   zerosonesNotImplementedError)
r7   r:   r;   
batch_sizer@   r?   paddingpadding_modein_channelscurrent_caches
             r+   _cache_initz"MimiConv1dPaddingCache._cache_initg   s     %2$7$7$:M<O<OQ^QeQe6E
""9-''	2&&y1  + :%!KK
KQW_deM  [(

:{GFRWX[hilnpopnpip[qq   &l^>&RSSr*   c                    |j                   d   |j                  |j                  }}}| j                  |   | j                  |   }}| j
                  |   | j                  ||      }n| j
                  |   }|dkD  rXt        d||j                   d   z
        }	|	dkD  r't        j                  |dddd|	 df   |gd      }
n*|dddd| df   }
nt        j                  ||d||      }
|
| j
                  |<   |S )a  
        Updates the padding cache with the new padding states for the layer `layer_idx` and returns the current cache.

        Parameters:
            hidden_states (`torch.Tensor`):
                The hidden states to be partially cached.
            layer_idx (`int`):
                The index of the layer to cache the states for.
        Returns:
            `torch.Tensor` or `None`, the current padding cache.
        r   Ndim)r@   r?   )rB   r@   r?   r/   r1   r6   rK   maxr%   catempty)r7   r:   r;   rF   r@   r?   rG   rI   rJ   	shortfallpadding_statess              r+   updatezMimiConv1dPaddingCache.update   s    %2$7$7$:M<O<OQ^QeQe6E
#55i@$B\B\]fBgi(0 ,,]IFM ..y9M Q;Aw)<)<R)@@AI1}!&M!Q
:K,Lm+\bd!e!.q!gXY!?"[[[!5Y_`N(69%r*   N)r!   r"   r#   r$   intliststrr9   r%   TensorrK   rU   r)   r*   r+   r-   r-   I   sl    11  91 !%S		1
  $Cy1* # <ELL S r*   r-   c                   b    e Zd ZU dZdZej                  dz  ed<   dZe	dz  ed<   dZ
edz  ed<   y)MimiEncoderOutputa  
    audio_codes (`torch.LongTensor`  of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
        Discrete code embeddings computed using `model.encode`.
    encoder_past_key_values (`Cache`, *optional*):
        Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
        This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

        The model will output the same cache format that is fed as input.

        If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
        have their past key value states given to this model).
    padding_cache (`MimiConv1dPaddingCache`, *optional*):
        Padding cache for MimiConv1d causal convolutions in order to support streaming via cache padding.
    Nr   r   r6   )r!   r"   r#   r$   r   r%   r&   r'   r   r
   r6   r-   r)   r*   r+   r[   r[      s=     ,0K!!D(/,0UT\037M)D07r*   r[   c                   N    e Zd ZU dZdZej                  dz  ed<   dZe	dz  ed<   y)MimiDecoderOutputa+  
    audio_values (`torch.FloatTensor`  of shape `(batch_size, segment_length)`, *optional*):
        Decoded audio values, obtained using the decoder part of Mimi.
    decoder_past_key_values (`Cache`, *optional*):
        Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
        This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

        The model will output the same cache format that is fed as input.

        If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
        have their past key value states given to this model).
    Nr   r    )
r!   r"   r#   r$   r   r%   r(   r'   r    r
   r)   r*   r+   r]   r]      s-     .2L%##d*1,0UT\0r*   r]   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edz  f fdZd Zd Z	de
j                  de
j                  fdZedde
j                  deeef   dedefd       Zde
j"                  de
j"                  fdZddZ xZS )
MimiConv1dz;Conv1d with asymmetric or causal padding and normalization.NrI   out_channelskernel_sizestridedilationgroupspad_modebiasr;   c           	      8   t         |           |j                  | _        ||j                  n|| _        |
| _        || _        |dkD  r$|dkD  rt        j                  d| d| d| d       t        j                  |||||||	      | _        | j                  j                  d   }t        j                  | j                  j                  d   t        j                         }| j                  j"                  d   }t        j                  |dz
  |z  dz   t        j                         }| j%                  d	|d
       | j%                  d|d
       | j%                  d||z
  d
       | j&                  dz  | _        | j&                  | j(                  z
  | _        y )Nr   zNMimiConv1d has been initialized with stride > 1 and dilation > 1 (kernel_size=z stride=z, dilation=).)rc   rd   rf   r   r@   rb   F
persistentra   padding_total   )superr9   use_causal_convcausalre   r;   rI   loggerwarningr   Conv1dconvra   r%   tensorrb   int64rc   register_bufferrl   padding_rightpadding_left)r7   configrI   r`   ra   rb   rc   rd   re   rf   r;   	__class__s              r+   r9   zMimiConv1d.__init__   s~    	,,+3+;"& A:(Q,NN!!,XfX[
RTV
 II{FXV\cg
	 ii++A.dii..q1E99%%a( llK!Ox#?!#C5;;WXv%@]KEJ_kF.BuU "//14 ..1C1CCr*   c                     t         j                  j                  }t        t         j                  j                  d      r$t         j                  j                  j                  } || j
                         y Nweight_normr   utilsr~   hasattrparametrizationsrt   r7   r~   s     r+   apply_weight_normzMimiConv1d.apply_weight_norm  F    hh**288,,m<((33??KDIIr*   c                 V    t         j                  j                  | j                         y Nr   r   remove_weight_normrt   r7   s    r+   r   zMimiConv1d.remove_weight_norm	      
##DII.r*   r:   returnc                 >   |j                   d   }|| j                  z
  | j                  z   | j                  z  dz   }t	        j
                  |      j                  t        j                        dz
  }|| j                  z  | j                  z   | j                  z
  }||z
  S )zSee `pad_for_conv1d`.rM   r   )rB   ra   rl   rb   r%   ceiltorv   )r7   r:   lengthn_framesideal_lengths        r+   _get_extra_padding_for_conv1dz(MimiConv1d._get_extra_padding_for_conv1d  s    
 $$R(T---0B0BBdkkQTUU::h'**5;;7!;$++-0@0@@4CUCUUf$$r*   paddingsmodevaluec                 l   | j                   d   }|\  }}|dk7  r"t        j                  j                  | |||      S t	        ||      }d}||k  r*||z
  dz   }t        j                  j                  | d|f      } t        j                  j                  | |||      }	|	j                   d   |z
  }
|	dd|
f   S )zTiny wrapper around torch.nn.functional.pad, just to allow for reflect padding on small input.
        If this is the case, we insert extra 0 padding to the right before the reflection happens.
        rM   reflectr   r   .N)rB   r   
functionalpadrP   )r:   r   r   r   r   ry   rx   max_pad	extra_padpaddedends              r+   _pad1dzMimiConv1d._pad1d  s     $$R(&.#m9==$$]HdEJJlM2	W&(1,IMM--ma^LM""=(D%Hll2*c4C4i  r*   input_lengthc                    || j                   z
  | j                  z   | j                  z  dz   }t        j                  |      j                  t        j                        dz
  }|| j                  z  | j                   z   | j                  z
  }||z
  }| j                  r| j                  }|}n| j                  }| j                  |z   }||z   |z   }|d| j                  j                  d   z  z   | j                  j                  d   | j                  j                   d   dz
  z  z
  dz
  | j                  j                  d   z  dz   }|S )zD
        Return the length of the output of the MimiConv1d.
        r   rm   r   )ra   rl   rb   r%   r   r   rv   rp   ry   rx   rt   rG   rc   )r7   r   r   r   extra_paddingry   rx   output_lengths           r+   _get_output_lengthzMimiConv1d._get_output_length-  s=   
 !4#3#33d6H6HHDKKWZ[[::h'**5;;7!;$++-0@0@@4CUCUU$|3;;--L)M,,L ..>M $l2]B 1tyy00333dii6H6H6KtyyOdOdefOgjkOk6lloppYYa !#$% r*   c                    | j                  |      }| j                  s|t        d      | j                  r8|6|j                  || j                        }t        j                  ||gd      }nn| j                  r+| j                  || j                  |f| j                        }n7| j                  || j                  | j                  |z   f| j                        }| j                  |      }|S )Nz=`padding_cache` is not supported for non-causal convolutions.rm   rN   )r   )r   rp   r5   rU   r;   r%   rQ   r   rl   re   ry   rx   rt   )r7   r:   r6   r   layer_padding_caches        r+   forwardzMimiConv1d.forwardG  s    ::=I{{}8\]];;=4"/"6"6}dnn"U!II':M&JPQRM[[ KK8J8JM7ZaeananKoM !KK 1 143E3E3UV]a]j]j ( M 		-0r*   )r   r   r   NTN)zero        r   )r!   r"   r#   r$   rV   rX   boolr9   r   r   r%   rY   r   staticmethodtuplefloatr   r&   r   r   __classcell__r{   s   @r+   r_   r_      s   E # $+D +D 	+D
 +D +D +D +D *+D +D :+DZ/
%||
% 

% !ell !eCHo !S !bg ! !$u/?/? EDTDT 4r*   r_   c                   R     e Zd ZdZ	 	 	 ddededededef
 fdZd Zd	 Zd
 Z xZ	S )MimiConvTranspose1dzDConvTranspose1d with asymmetric or causal padding and normalization.rI   r`   ra   rb   rd   c                    t         	|           |j                  | _        |j                  | _        t        j                  ||||||      | _        | j                  s| j                  dk(  st        d      | j                  j                  d   }| j                  j                  d   }||z
  }| j                  r(t        j                  || j                  z        | _        n
|dz  | _        || j                  z
  | _        y )N)rd   rf         ?zB`trim_right_ratio` != 1.0 only makes sense for causal convolutionsr   rm   )rn   r9   ro   rp   trim_right_ratior   ConvTranspose1drt   r5   ra   rb   mathr   rx   ry   )
r7   rz   rI   r`   ra   rb   rd   rf   rl   r{   s
            r+   r9   zMimiConvTranspose1d.__init__a  s     	,, & 7 7&&{L+v^dkop	t44;abbii++A.!!!$#f, ;; "&=4;P;P+P!QD "/!!3D)D,>,>>r*   c                     t         j                  j                  }t        t         j                  j                  d      r$t         j                  j                  j                  } || j
                         y r}   r   r   s     r+   r   z%MimiConvTranspose1d.apply_weight_norm  r   r*   c                 V    t         j                  j                  | j                         y r   r   r   s    r+   r   z&MimiConvTranspose1d.remove_weight_norm  r   r*   c                     | j                  |      }|j                  d   | j                  z
  }|d| j                  |f   }|S )NrM   .)rt   rB   rx   ry   )r7   r:   r   s      r+   r   zMimiConvTranspose1d.forward  sM    		-0 !!"%(:(::%c4+<+<s+B&BCr*   )r   r   T)
r!   r"   r#   r$   rV   r9   r   r   r   r   r   s   @r+   r   r   ^  sX    N "? "? 	"?
 "? "? "?H/r*   r   c                   >     e Zd ZdZdededee   f fdZddZ xZ	S )MimiResnetBlockz;
    Residual block from SEANet model as used by Mimi.
    rz   rO   	dilationsc           	          t         |           |j                  df}t        |      t        |      k7  rt	        d      ||j
                  z  }g }t        t        ||            D ]R  \  }\  }}	|dk(  r|n|}
|t        |      dz
  k(  r|n|}|t        j                         gz  }|t        ||
|||	      gz  }T t        j                  |      | _        |j                  rt        |||d      | _        y t        j                         | _        y )Nr   z7Number of kernel sizes should match number of dilationsr   )rc   )ra   )rn   r9   residual_kernel_sizer3   r5   compress	enumeratezipr   ELUr_   
ModuleListblockuse_conv_shortcutshortcutIdentity)r7   rz   rO   r   kernel_sizeshiddenr   ira   rc   in_chsout_chsr{   s               r+   r9   zMimiResnetBlock.__init__  s   33Q7|I.VWW'*3Ci4P*Q 	[&A&XFSF#l"3a"77cVGbffhZEj+PXYZZE		[
 ]]5)
##&vsCQGDMKKMDMr*   c                     |}| j                   D ]%  }t        |t              r |||      } ||      }' t        | j                  t              r| j                  ||      }||z   S | j                  |      }||z   S Nr6   )r   
isinstancer_   r   )r7   r:   r6   residuallayers        r+   r   zMimiResnetBlock.forward  s     ZZ 	5E%, %m= Q %m 4		5 dmmZ0}}X]}KH -'' }}X.H-''r*   r   )
r!   r"   r#   r$   r   rV   rW   r9   r   r   r   s   @r+   r   r     s+    *z * *S	 *((r*   r   c                   0     e Zd ZdZdef fdZddZ xZS )MimiEncoderzSEANet encoder as used by Mimi.rz   c           	         t         |           t        ||j                  |j                  |j
                        g}d}dg}t        |j                        D ]  }||j                  z  }t        |j                        D ]O  }|j                  dt        |       ddt        |       dg       |t        |||j                  |z  dg      gz  }Q |t        j                         gz  }|j!                  dt        |              |t        |||dz  |dz  |      gz  }|dz  } |t        j                         gz  }|j!                  dt        |              |t        |||j                  z  |j"                  |j$                        gz  }t        j&                  |      | _        || _        t-        | j*                        D ]#  \  }}	| j/                  |	      }
t1        |
d|       % y )	Nr   zlayers.0zlayers.z.block.1z.block.3rm   ra   rb   r;   )rn   r9   r_   audio_channelsnum_filtersra   reversedupsampling_ratiosrangenum_residual_layersextendr3   r   dilation_growth_rater   r   appendhidden_sizelast_kernel_sizer   layers_mimiconv1d_layer_namesr   get_submodulesetattr)r7   rz   modelscalingmimiconv1d_layer_namesratiocurrent_scalejr;   	layername
conv_layerr{   s              r+   r9   zMimiEncoder.__init__  s   FF$9$96;M;MvOaOabc #- f667 
	E#f&8&88M6556 g&--UH/MQXY\]bYcXddlOm.no/&-&B]B]_`B`bcAdeffg bffhZE"))GCJ<*@Aj8IW\_`W`inoppEqLG
	 	"&&(%%E
|&<=*VWv/A/A%A6CUCUW]WnWnoppmmE*'=$ %.d.J.J$K 	8 Iy++I6JJY7	8r*   c                 z    | j                   D ]+  }t        |t        t        f      r |||      }$ ||      }- |S r   )r   r   r_   r   )r7   r:   r6   r   s       r+   r   zMimiEncoder.forward  sB    [[ 	5E%*o!>? %m= Q %m 4		5
 r*   r   r!   r"   r#   r$   r   r9   r   r   r   s   @r+   r   r     s    )8z 8Br*   r   c                   B     e Zd ZdZ fdZdej                  fdZ xZS )MimiLayerScalezLayer scale from [Touvron et al 2021] (https://huggingface.co/papers/2103.17239).
    This rescales diagonally the residual outputs close to 0, with a learnt scale.
    c                     t         |           |j                  }|j                  }t	        j
                  t        j                  |f|d            | _        y )NT)requires_grad)	rn   r9   r   layer_scale_initial_scaler   	Parameterr%   fullscale)r7   rz   channelsinitial_scaler{   s       r+   r9   zMimiLayerScale.__init__  sD    %%88\\%**h[-W["\]
r*   xc                      | j                   |z  S r   )r   )r7   r   s     r+   r   zMimiLayerScale.forward  s    zzA~r*   )	r!   r"   r#   r$   r9   r%   rY   r   r   r   s   @r+   r   r     s    ^ r*   r   c                        e Zd ZU 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                         ed               Z xZS )MimiRotaryEmbeddinginv_freqNrz   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr   Frj   original_inv_freq)rn   r9   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrz   rope_parametersr   compute_default_rope_parametersr   attention_scalingrw   clone)r7   rz   r?   rope_init_fnr   r{   s        r+   r9   zMimiRotaryEmbedding.__init__  s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr*   r?   ztorch.deviceseq_lenr   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  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head_dimNr   r   rm   ri   r>   )	r  getattrr   num_attention_headsr%   arangerv   r   r   )rz   r?   r  baserO   attention_factorr   s          r+   r  z3MimiRotaryEmbedding.compute_default_rope_parameters  s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r*   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   rM   r   mpscpuF)device_typeenabledrm   rN   ri   )r   r   expandrB   r   r?   r   typerX   r   	transposer%   rQ   cosr  sinr@   )
r7   r   position_idsinv_freq_expandedposition_ids_expandedr  freqsembr  r  s
             r+   r   zMimiRotaryEmbedding.forward0  sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r   NNN)r!   r"   r#   r%   rY   r'   r   r9   r   r   rV   r   r   r  no_gradr   r   r   r   s   @r+   r   r     s    llVz V  $(+/"*T!*(* t* 
~u$	%	* *: U]]_<  <r*   r   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..NrM   rm   rN   )rB   r%   rQ   )r   x1x2s      r+   rotate_halfr(  A  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r*   c                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )	unsqueezer(  )qkr  r  unsqueeze_dimq_embedk_embeds          r+   apply_rotary_pos_embr0  I  sY    $ --
&C
--
&C3w;q>C/0G3w;q>C/0GGr*   c                   V     e Zd Z fdZdej
                  dej
                  fdZ xZS )MimiMLPc                 $   t         |           || _        t        |j                     | _        t        j                  |j                  |j                  d      | _
        t        j                  |j                  |j                  d      | _        y )NFrf   )rn   r9   rz   r	   
hidden_actactivation_fnr   Linearr   intermediate_sizefc1fc2r7   rz   r{   s     r+   r9   zMimiMLP.__init__c  sj    #F$5$5699V//1I1IPUV99V55v7I7IPUVr*   r:   r   c                 l    | j                  |      }| j                  |      }| j                  |      }|S r   )r9  r6  r:  )r7   r:   s     r+   r   zMimiMLP.forwardk  s4    /**=9/r*   )r!   r"   r#   r9   r%   rY   r   r   r   s   @r+   r2  r2  b  s$    WU\\ ell r*   r2  r:   n_repr   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)rB   r  reshape)r:   r=  batchnum_key_value_headsslenr  s         r+   	repeat_kvrC  s  so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr*   modulequerykeyr   attention_maskr   dropoutkwargsc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nrm   r   rM   )rO   r@   )ptrainingr   )rC  num_key_value_groupsr%   matmulr  r   r   softmaxfloat32r   r@   rH  rL  
contiguous)rD  rE  rF  r   rG  r   rH  rI  
key_statesvalue_statesattn_weightsattn_outputs               r+   eager_attention_forwardrV    s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r*   c                        e Zd ZdZddededz  f fdZ	 	 	 ddej                  dej                  dz  de	dz  d	e
ej                  ej                  f   dz  d
e
ej                  ej                  f   f
dZ xZS )MimiAttentionz=Multi-headed attention from 'Attention Is All You Need' paperNrz   r;   c                    t         |           || _        || _        |j                  | _        |j
                  | _        |j                  | _        |j                  | _        |j                  | _	        | j                  | j                  z  | _
        |j                  | _        d| _        dt        j                  |j                        z  | _        | j
                  | j                  z  dk7  r&t!        d| j
                   d| j                   d      t#        j$                  | j
                  | j                  | j                  z  |j&                        | _        t#        j$                  | j
                  | j                  | j                  z  |j&                        | _        t#        j$                  | j
                  | j                  | j                  z  |j&                        | _        t#        j$                  | j                  | j                  z  | j
                  |j&                        | _        |j0                  | _        y )NTr   r   z?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: rh   r4  )rn   r9   rz   r;   attention_dropoutr   r  	num_headsr  rA  rM  r  	is_causalr   sqrtr   r5   r   r7  attention_biasq_projk_projv_projo_projsliding_windowr7   rz   r;   r{   s      r+   r9   zMimiAttention.__init__  s   "!'!9!9!--33#)#=#= $(NNd6N6N$N!'-'E'E$499V__55dnn,1QRVRbRbQc$T^^$4B8 
 ii 0 0$..4==2PW]WlWlmii 0 0$2J2JT]]2Zagavavwii 0 0$2J2JT]]2Zagavavwii >@P@PW]WlWlm$33r*   r:   rG  past_key_valuesposition_embeddingsr   c                     |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
|\  }}t        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                  j                  t              } || ||	|
|f| j                  sdn| j                   | j"                  | j$                  d|\  }} |j&                  g |d j)                         }| j+                  |      }||fS )NrM   r   rm   r   )rH  r   rc  )rB   r  r_  viewr  r`  ra  r0  rU   r;   r   get_interfacerz   _attn_implementationrV  rL  rZ  r   rc  r?  rQ  rb  )r7   r:   rG  re  rf  rI  input_shapehidden_shapequery_statesrR  rS  r  r  attention_interfacerU  rT  s                   r+   r   zMimiAttention.forward  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&S#7jRUWZ#[ j&'6'='=j,X\XfXf'g$J(?(M(MKK,,.E)
 %8
%
  $}}C$2H2HLL..
%
 
%
!\ *k));;;;FFHkk+.L((r*   r   r#  )r!   r"   r#   r$   r   rV   r9   r%   rY   r
   r   r   r   r   s   @r+   rX  rX    s    G4z 4cDj 4< /3(,HL')||') t+') 	')
 #5<<#=>E') 
u||U\\)	*')r*   rX  c                   &    e Zd Zdedef fdZ	 	 	 	 	 ddej                  dej                  dz  dedz  de	dz  d	e	dz  d
e
ej                  ej                  f   dz  de
ej                  e
ej                  ej                  f   dz  f   fdZ xZS )MimiTransformerLayerrz   r;   c                    t         |           |j                  | _        t        ||      | _        t        |      | _        t        j                  |j                  |j                        | _
        t        j                  |j                  |j                        | _        t        |      | _        t        |      | _        y )N)rz   r;   )eps)rn   r9   r   rX  	self_attnr2  mlpr   	LayerNormnorm_epsinput_layernormpost_attention_layernormr   self_attn_layer_scalemlp_layer_scalerd  s      r+   r9   zMimiTransformerLayer.__init__  s    !--&f	J6?!||F,>,>FOOT(*V5G5GV__(]%%3F%;"-f5r*   Nr:   rG  re  output_attentions	use_cacherf  r   c           
         |}| j                  |      } | j                  d||||||d|\  }}	|| j                  |      z   }|}| j                  |      }| j	                  |      }|| j                  |      z   }|f}
|r|
|	fz  }
|
S )N)r:   rG  re  r{  r|  rf  r)   )rw  rs  ry  rx  rt  rz  )r7   r:   rG  re  r{  r|  rf  rI  r   self_attn_weightsoutputss              r+   r   zMimiTransformerLayer.forward  s     !,,]; ,:4>> ,
')+/ 3,
 ,
(( !4#=#=m#LL !55mD/ 4#7#7#FF ")++Gr*   )NNFFN)r!   r"   r#   r   rV   r9   r%   rY   r
   r   r   r(   r   r   r   s   @r+   rp  rp    s    
6z 
6c 
6 /3(,).!&HL%||% t+% 	%
  $;% $;% #5<<#=>E% 
u  %(9(95;L;L(L"MPT"TT	U%r*   rp  c                        e Zd ZdZdef fdZ	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  de	dz  d	e
dz  d
e
dz  de
dz  de
dz  deez  fdZ xZS )MimiTransformerModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MimiTransformerLayer`]

    Args:
        config: MimiConfig
    rz   c           	          t         |           t        j                  t	        |j
                        D cg c]  }t        ||       c}      | _        t        |      | _	        d| _
        || _        y c c}w )NF)rn   r9   r   r   r   num_hidden_layersrp  r   r   
rotary_embgradient_checkpointingrz   rd  s      r+   r9   zMimiTransformerModel.__init__  sb    mmFKFLdLdFef!&)4f
 .f5&+# gs   A4Nr:   rG  r  re  r|  r{  output_hidden_statesreturn_dictr   c	           
      X   ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }| j
                  r%| j                  r|rt        j                  d       d}|r|t        | j                         }|V||j                         nd}
t        j                  |j                  d   |j                        |
z   }|j                  d      }t!        | j                   ||||      }| j#                  ||      }|rd	nd}|rd	nd}| j$                  D ]*  }|r||fz  } ||||||||
      }|d   }|s"||d   fz  }, |r||fz  }|st'        d ||||fD              S t)        ||||      S )a|  
        Args:
            hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
                Embedded representation that will be contextualized by the model
            attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
                Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

                - 1 for tokens that are **not masked**,
                - 0 for tokens that are **masked**.

                [What are attention masks?](../glossary#attention-mask)

                Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
                [`PreTrainedTokenizer.__call__`] for details.

                If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
                `past_key_values`).

                If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
                and modify to your needs. See diagram 1 in [the paper](https://huggingface.co/papers/1910.13461) for more
                information on the default strategy.

                - 1 indicates the head is **not masked**,
                - 0 indicates the head is **masked**.
            position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
                Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
                config.n_positions - 1]`.

                [What are position IDs?](../glossary#position-ids)
            past_key_values (`Cache`, *optional*):
                It is a [`~cache_utils.Cache`] instance. For more details, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache).

                If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
                have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
                of shape `(batch_size, sequence_length)`.
            use_cache (`bool`, *optional*):
                If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
                `past_key_values`).
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
                tensors for more detail.
            output_hidden_states (`bool`, *optional*):
                Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
                more detail.
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        NzX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.F)rz   r   r   r?   )rz   inputs_embedsrG  re  r  r)   )rG  r  re  r{  r|  rf  c              3   &   K   | ]	  }||  y wr   r)   ).0vs     r+   	<genexpr>z/MimiTransformerModel.forward.<locals>.<genexpr>  s      bcbos   )last_hidden_statere  r:   
attentions)rz   r{  r  r|  r  r  rL  rq   warning_oncer   get_seq_lengthr%   r  rB   r?   r*  r   r  r   r   r   )r7   r:   rG  r  re  r|  r{  r  r  rI  past_seen_tokenscausal_maskrf  all_hidden_statesall_self_attnsdecoder_layerlayer_outputss                    r+   r   zMimiTransformerModel.forward)  s   v 2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++BYBY&&4==Yj I0*$++>OCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L7;;')+%
 #oom\J #7BD0d![[ 	6M#!m%55!)*) /"3#$7M *!,M =#3"55#	6(  -!11 )?<M~^   '+++%	
 	
r*   )NNNNNNNN)r!   r"   r#   r$   r   r9   r%   r&   rY   r
   r   r   r   r   r   r   s   @r+   r  r    s    	z 	 26.204(,!%)-,0#'
''$.
 t+
 &&-	

 
 $;
  $;
 #Tk
 D[
 
(	(
r*   r  c                   .     e Zd ZdZdef fdZd Z xZS )MimiDecoderzSEANet decoder as used by Mimi.rz   c           	         t         |           t        dt        |j                        z        }t        ||j                  ||j                  z  |j                        g}|j                  D ]  }||j                  z  }|t        j                         gz  }|t        |||dz  |dz  |      gz  }t        |j                        D ]%  }|t        ||dz  |j                  |z  df      gz  }' |dz  } |t        j                         gz  }|t        ||j                  |j                   |j"                        gz  }t        j$                  |      | _        y )Nrm   r   r   )rn   r9   rV   r3   r   r_   r   r   ra   r   r   r   r   r   r   r   r   r   r   r   )r7   rz   r   r   r   r   r   r{   s          r+   r9   zMimiDecoder.__init__  s[   a3v77889FF$6$6&BTBT8TV\VhVhij -- 
	E#f&8&88MbffhZE#FM=A;M[`cd[dmrs E 6556 l/&-12DvGbGbdeGeghFijkklMG
	 	"&&(*VV%7%79N9NPVPgPghiimmE*r*   c                 8    | j                   D ]
  } ||      } |S r   )r   )r7   r:   r   s      r+   r   zMimiDecoder.forward  s%    [[ 	1E!-0M	1r*   r   r   s   @r+   r  r    s    )+z +0r*   r  c                   j     e Zd ZdZd
dedef fdZedej                  fd       Z
d Zd Zd	 Z xZS )MimiEuclideanCodebookz!Codebook with Euclidean distance.rz   epsilonc                    t         |           t        j                  |j                  |j
                        }|j                  | _        | j                  dt        j                  dgt        j                               | j                  dt        j                  |j                               | j                  d|       d | _
        || _        y )NinitializedTri   cluster_usage	embed_sum)rn   r9   r%   rC   codebook_sizecodebook_dimrw   ru   rP  rD   _embedr  )r7   rz   r  embedr{   s       r+   r9   zMimiEuclideanCodebook.__init__  s    F00&2E2EF#11]ELL$u}},UV_ejj9M9M.NO[%0r*   r   c                     | j                   ?| j                  | j                  j                  | j                        d d d f   z  | _         | j                   S )N)min)r  r  r  clampr  r   s    r+   r  zMimiEuclideanCodebook.embed  sJ    ;;..4+=+=+C+C+C+UVWY]V]+^^DK{{r*   c                     t        j                  |d    j                         | j                  d    j                         d      d   }|j	                  d      }|S )Nrm   )rK  r   rM   rN   )r%   cdistr   r  argmin)r7   r:   dists	embed_inds       r+   quantizezMimiEuclideanCodebook.quantize  sS     M$/557D9I9O9O9QUVWXYZLLRL(	r*   c                     |j                   }|j                  d|d   f      }| j                  |      } |j                  |d d  }|S )NrM   )rB   r?  r  rh  )r7   r:   rB   r  s       r+   encodezMimiEuclideanCodebook.encode  sO    ##%--r59o>MM-0	"INNE#2J/	r*   c                 Z    t         j                  j                  || j                        }|S r   )r   r   	embeddingr  r7   r  r  s      r+   decodezMimiEuclideanCodebook.decode  s!    ==**9djjAr*   )gh㈵>)r!   r"   r#   r$   r   r   r9   propertyr%   rY   r  r  r  r  r   r   s   @r+   r  r    sG    +
z 
E 
 u||  
r*   r  c                   4     e Zd ZdZdef fdZd Zd Z xZS )MimiVectorQuantizationzY
    Vector quantization implementation. Currently supports only euclidean distance.
    rz   c                 B    t         |           t        |      | _        y r   )rn   r9   r  codebookr;  s     r+   r9   zMimiVectorQuantization.__init__  s    -f5r*   c                 b    |j                  ddd      }| j                  j                  |      }|S Nr   rm   r   )permuter  r  )r7   r:   embed_ins      r+   r  zMimiVectorQuantization.encode  s/    %--aA6==''6r*   c                 b    | j                   j                  |      }|j                  ddd      }|S r  )r  r  r  r  s      r+   r  zMimiVectorQuantization.decode  s/    ==''	2##Aq!,r*   )	r!   r"   r#   r$   r   r9   r  r  r   r   s   @r+   r  r    s    6z 6
r*   r  c                        e Zd ZdZddededz  f fdZddej                  dedz  dej                  fdZ	d	ej                  dej                  fd
Z
 xZS )MimiResidualVectorQuantizerzResidual Vector Quantizer.Nrz   num_quantizersc                 b   t         |           |j                  | _        |j                  | _        ||n|j                  | _        t        j                  t        | j                        D cg c]  }t        |       c}      | _	        d | _
        d | _        |j                  |j                  k7  ryt        j
                  j                  |j                  |j                  dd      | _
        t        j
                  j                  |j                  |j                  dd      | _        y y c c}w )Nr   Fr4  )rn   r9   r  
frame_rater  r   r   r   r  r   
input_projoutput_proj$vector_quantization_hidden_dimensionr   r%   rs   )r7   rz   r  _r{   s       r+   r9   z$MimiResidualVectorQuantizer.__init__  s    #11 ++0>0JnPVPePemmUSWSfSfMg$h%;F%C$hi66&:L:LL#hhoo""F$O$OQRY^ . DO  %xx;;V=O=OQRY^  /  D	 M	 %is   -D,
embeddingsr   c                 *   | j                   | j                  |      }||n| j                  }|}g }| j                  d| D ]:  }|j                  |      }|j	                  |      }||z
  }|j                  |       < t        j                  |      }|S )
        Encode a given input tensor with the specified frame rate at the given number of quantizers / codebooks. The RVQ encode method sets
        the appropriate number of quantizers to use and returns indices for each quantizer.
        N)r  r  r   r  r  r   r%   stack)	r7   r  r  r   all_indicesr   indices	quantizedout_indicess	            r+   r  z"MimiResidualVectorQuantizer.encode"  s    
 ??&4J+9+E4K^K^[[.1 	(Ell8,GW-I)+Hw'		(
 kk+.r*   codesc                    t        j                  d|j                        }|j                  dd      }t	        |      D ]*  \  }}| j
                  |   }|j                  |      }||z   }, | j                  | j                  |      }|S )zJDecode the given codes of shape [B, K, T] to the quantized representation.r   r  r   r   )r%   ru   r?   r  r   r   r  r  )r7   r  quantized_outr   r  r   r  s          r+   r  z"MimiResidualVectorQuantizer.decode6  s    S>1%#E* 	6JAwKKNEW-I)I5M	6
 ' ,,];Mr*   r   )r!   r"   r#   r$   r   rV   r9   r%   rY   r  r  r   r   s   @r+   r  r    sa    $z 3: " sTz UZUaUa (ELL U\\ r*   r  c                        e Zd ZdZdef fdZddej                  dedz  dej                  fdZ	d	ej                  dej                  fd
Z
 xZS ) MimiSplitResidualVectorQuantizerz Split Residual Vector Quantizer.rz   c                 R   t         |           |j                  | _        |j                  | _        |j                  | _        |j                  | _        |j                  |j                  z
  | _        t        || j                        | _	        t        || j                        | _
        y r   )rn   r9   r  r  r  max_num_quantizersnum_semantic_quantizersnum_acoustic_quantizersr  "semantic_residual_vector_quantizer"acoustic_residual_vector_quantizerr;  s     r+   r9   z)MimiSplitResidualVectorQuantizer.__init__G  s    #11 ++"("7"7'-'E'E$'-'<'<v?]?]']$2MfVZVrVr2s/2MfVZVrVr2s/r*   Nr  r  r   c                    || j                   n|}|| j                   kD  rt        d| j                    d| d      || j                  k  rt        d| j                   d| d      | j                  j	                  |      }|| j                  kD  rC| j
                  j	                  ||| j                  z
        }t        j                  ||gd      }|S )r  cThe number of quantizers (i.e codebooks) asked should be lower than the total number of quantizers , but is currently .zgThe number of quantizers (i.e codebooks) asked should be higher than the number of semantic quantizers )r  r   rN   )r  r5   r  r  r  r  r%   rQ   )r7   r  r  r  acoustic_codess        r+   r  z'MimiSplitResidualVectorQuantizer.encodeS  s8    5C4J00P^D333uvz  wN  wN  vO  Ob  cq  br  rs  t  D888yz~  {W  {W  zX  Xk  lz  k{  {|  } 
 77>>zJD888!DDKK>D<X<X+X L N IIun51=Er*   r  c                     | j                   j                  |ddd| j                  f         }|j                  d   | j                  kD  r1|| j                  j                  |dd| j                  df         z  }|S )z7Decode the given codes to the quantized representation.Nr   )r  r  r  rB   r  )r7   r  r  s      r+   r  z'MimiSplitResidualVectorQuantizer.decodep  s     ??FFuQPnRVRnRnPnMnGop ;;q>D888TDDKKERSUYUqUqUsRsLtuuMr*   r   )r!   r"   r#   r$   r   r9   r%   rY   r   r  r  r   r   s   @r+   r  r  D  sX    *
tz 
t ut| W\WcWc :	ELL 	U\\ 	r*   r  c                        e Zd ZU eed<   dZdZdZdZddgZ	dgZ
dZdZdZdZdZ ej"                          fd	       Z xZS )
MimiPreTrainedModelrz   mimiinput_valuesaudioTr  rp  re  c                    t         |   |       t        |t        j                  t        j
                  f      rt        j                  |j                         |j                  `t        j                  |j                  |j                  |j                  d   z  z        }t        j                  |j                  | |       yyt        |t               r5t        j"                  |j$                  | j&                  j(                         yt        |t*              r|j,                  j                  d   }|j,                  j.                  d   }|j,                  j0                  d   }|dz
  |z  dz   }t        j"                  |j.                  |       t        j"                  |j                  |       t        j"                  |j2                  ||z
         yt        |t4              r^t        j6                  |j8                         t        j6                  |j:                         t        j<                  |j>                         yy)zInitialize the weightsNr   )abr   ) rn   _init_weightsr   r   rs   r   initkaiming_normal_weightrf   r   r]  rd   rI   ra   uniform_r   	constant_r   rz   r   r_   rt   rb   rc   rl   r  ones_r  r  zeros_r  )r7   rD  r,  ra   rb   rc   r{   s         r+   r  z!MimiPreTrainedModel._init_weights  s    	f%fryy"*<*<=>  /{{&IIfmmv/A/AFDVDVWXDY/YZ[fkkaR15 ' /NN6<<)N)NO
+ ++11!4K[[''*F{{++A.H&?h6:KNN6==&1NN6--{;NN6//v1EF 56JJv))*JJv++,KK(() 7r*   )r!   r"   r#   r   r'   base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_supports_flex_attn_supports_attention_backend_can_compile_fullgraphr%   r$  r  r   r   s   @r+   r  r  |  sl    $O&*#;=ST#4"5N"&!U]]_* *r*   r  z,
    The Mimi neural audio codec model.
    )custom_introc                       e Zd Zdef fdZ	 	 	 	 ddej                  dedededz  de	dz  d	e
dz  d
e
dz  deej                  ej                  dz  f   fdZdej                  dej                  fdZddej                  defdZ	 	 	 	 	 	 ddej                  dej                  dz  dedz  dedz  de	dz  d	e
dz  d
e
dz  deej                  ej                  dz  f   ez  fdZ	 	 ddej                  dedz  d
e
dz  dej                  fdZ	 	 	 ddej                  dej                  dz  dedz  d
e
dz  deej                  ej                  f   ez  f
dZe	 	 	 	 	 	 ddej                  dej                  dz  dedz  dej                  dz  dedz  dedz  d
e
dz  deej                  ej                  f   ez  fd       Z xZS )	MimiModelrz   c                    t         |   |       || _        t        |      | _        t        |      | _        d | _        d | _        |j                  |j                  k7  rt        ||j                  |j                  dt        |j                  |j                  z        z  dddt        | j                  j                              | _        t!        ||j                  |j                  dt        |j                  |j                  z        z  dd|j"                        | _        t        |      | _        t'        |      | _        t+        |      | _        t        t/        j0                  | j                  j2                              | _        d| j4                  z  | j                  j2                  k7  rt7        d      | j9                          y )Nrm   FrA   )ra   rb   rf   re   r;   )ra   rb   rf   rd   z'The codebook_size must be a power of 2.)rn   r9   rz   r   encoderr  encoder_transformer
downsampleupsampler  encodec_frame_rater_   r   rV   r3   r   r   upsample_groupsdecoder_transformerr  decoderr  	quantizerr   log2r  bits_per_codebookr5   	post_initr;  s     r+   r9   zMimiModel.__init__  sx    "6*#7#?  9 99(""""F$=$=@Q@Q$Q RR$dllBBC	DO 0""""F$=$=@Q@Q$Q RR--DM $8#? "6*9&A!$TYYt{{/H/H%I!Jd$$$(A(AAFGG 	r*   Nr  r  padding_maskre  r6   use_streamingr  r   c                 v   | j                  ||      }| j                  |j                  dd      |||      }	|r|	j                  d      }nt	        |	      dkD  r|	d   }|	d   j                  dd      }| j                  ||      }| j                  j                  ||      }
|
j                  dd      }
|
||fS )z
        Encodes the given input using the underlying VQVAE. The padding mask is required to compute the correct scale.
        r   r   rm   )re  r|  r  re  r   )r  r  r  getr3   r  r
  r  )r7   r  r  r  re  r6   r  r  r  encoder_outputsr  s              r+   _encode_framezMimiModel._encode_frame  s     \\,m\L
 22  A&+##	 3 
 -112CDO!A%-a0O$Q'11!Q7
__Z}_M
%%j.A1%o}44r*   r   c                     |}| j                   j                  D ],  }| j                   j                  |      j                  |      }. | j                  j                  |      }|S )zL
        Return the number of frames of the encoded audio waveform.
        )r  r   r   r   r  )r7   r   r   
layer_names       r+   get_encoded_lengthzMimiModel.get_encoded_length  sb     % ,,>> 	eJ LL66zBUUVcdM	e ::=Ir*   padding_sidec                 f   | j                  |j                  d            }t        j                  |j	                         |j
                        j                  t        |      d      }||j                  d      k  }|j                  |j
                        }|dk(  r|S |j                  dg      S )zR
        Get the mask for the audio codes from the original padding mask.
        rM   rN   r  r   right)dims)r  sumr%   r  rP   r?   r  r3   r*  r   flip)r7   r  r  encoded_lengthsaudio_codes_masks        r+   get_audio_codes_maskzMimiModel.get_audio_codes_mask  s     11,2B2Br2B2JK <<(;(;(=oF\F\]dd "
 ,o.G.G.JJ+..|/B/BC7"###((rd(33r*   r   c           	         ||n| j                   j                  }||n| j                   j                  }|| j                   j                  n|}|| j                   j                  kD  r&t	        d| j                   j                   d| d      |j
                  \  }}	}
|	dk  s|	dkD  rt	        d|	       |#t        j                  |      j                         }|r^|[g g g }}}| j                  j                  D ]  }|j                  | j                  j                  |      j                         |j                  | j                  j                  |      j                         |j                  | j                  j                  |      j                          |j                  | j                   j                         |j                  | j                   j                         |j                  | j                   j                         t#        t%        | j                  j                        dz   |||      }| j'                  |||j                         ||||      \  }}}|s|||fS t)        |||      S )	aE  
        Encodes the input audio waveform into discrete codes.

        Args:
            input_values (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
                Float values of the input audio waveform.
            padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
                Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
                for *masked*.
            num_quantizers (`int`, *optional*):
                Number of quantizers (i.e codebooks) to use. By default, all quantizers are used.
            encoder_past_key_values (`Cache`, *optional*):
                Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
                This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

                The model will output the same cache format that is fed as input.

                If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
                have their past key value states given to this model).
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Returns:
            `codebook` of shape `[batch_size, num_codebooks, frames]`, the discrete encoded codes for the input audio waveform.
        r  r  r  r   rm   z1Number of audio channels must be 1 or 2, but got )r.   r/   r0   r1   )re  r6   r  r  )rz   r  r  r  r5   rB   r%   	ones_liker   r  r   r   r   rl   re   rI   r  r-   r3   r  r[   )r7   r  r  r  r   r6   r  r  r  r   r   r/   r0   r1   r  encoded_framess                   r+   r  zMimiModel.encode  s   F &1%<k$++BYBY)6)BHaHa7E7M33SaDKK666uvz  wB  wB  wQ  wQ  vR  Re  ft  eu  uv  w  %1$6$6!8\a<8a<PQYPZ[\\ ??<8==?L]2OQSUWY7L5"llBB a
!(()C)CJ)O)])]^&--dll.H.H.T.].]^%,,T\\-G-G
-S-_-_`a $$T__%B%BC"))$//*B*BC!(()D)DE2t||CCDqH"3'=&;	M BFASAS3''# BT B
>/ '  !1H-XXr*   r  c                 D   | j                   j                  |      }| j                  |      }| j                  |j	                  dd      ||      }|r|j                  d      }nt        |      dkD  r|d   }|d   j	                  dd      }| j                  |      }||fS )Nr   rm   re  r  re  r   )r
  r  r  r  r  r  r3   r	  )r7   r  re  r  r  decoder_outputsr  s          r+   _decode_framezMimiModel._decode_framet  s     ^^**51
]]:.
22  A&U` 3 
 -112CDO!A%-a0O$Q'11!Q7
,,z*''r*   r   r    c                     ||n| j                   j                  }| j                  |||      \  }}|5|j                  d   |j                  d   k  r|dd|j                  d   f   }|s||fS t	        ||      S )a  
        Decodes the given frames into an output audio waveform.

        Note that the output might be a bit bigger than the input. In that case, any extra steps at the end can be
        trimmed.

        Args:
            audio_codes (`torch.LongTensor`  of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
                Discrete code embeddings computed using `model.encode`.
            padding_mask (`torch.Tensor` of shape `(batch_size, channels, sequence_length)`):
                Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
                for *masked*.
            decoder_past_key_values (`Cache`, *optional*):
                Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
                This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

                The model will output the same cache format that is fed as input.

                If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
                have their past key value states given to this model).
            return_dict (`bool`, *optional*):
                Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.

        Nr$  rM   .)rz   r  r&  rB   r]   )r7   r   r  r    r  r   s         r+   r  zMimiModel.decode  s    > &1%<k$++BYBY040B0B)@k 1C 1
--
 #(:(:2(>ASASTVAW(W'-E|/A/A"/E-E(EFL'  !/FGGr*   c                    ||n| j                   j                  }|#t        j                  |      j	                         }|B| j                  |||||      }	|	d   }|r|	j                  d      }nt        |	      dkD  r|	d   }| j                  ||||      }
|
d   }|r|
j                  d      }nt        |
      dkD  r|
d   }|s||||fS t        ||||      S )a
  
        input_values (`torch.FloatTensor` of shape `(batch_size, channels, sequence_length)`, *optional*):
            Raw audio input converted to Float.
        padding_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
            Indicates which inputs are to be ignored due to padding, where elements are either 1 for *not masked* or 0
            for *masked*.
        num_quantizers (`int`, *optional*):
            Number of quantizers (i.e codebooks) to use. By default, all quantizers are used.
        audio_codes (`torch.LongTensor`  of shape `(batch_size, num_quantizers, codes_length)`, *optional*):
            Discrete code embeddings computed using `model.encode`.
        encoder_past_key_values (`Cache`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the encoder transformer.
            This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            The model will output the same cache format that is fed as input.

            If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
            have their past key value states given to this model).
        decoder_past_key_values (`Cache`, *optional*):
            Pre-computed hidden-states (key and values in the self-attention blocks) that can be used to speed up sequential decoding of the decoder transformer.
            This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.

            The model will output the same cache format that is fed as input.

            If `past_key_values` are used, the user can optionally input only the last `audio_values` or `audio_codes (those that don't
            have their past key value states given to this model).

        Examples:

        ```python
        >>> from datasets import load_dataset
        >>> from transformers import AutoFeatureExtractor, MimiModel

        >>> dataset = load_dataset("hf-internal-testing/ashraq-esc50-1-dog-example")
        >>> audio_sample = dataset["train"]["audio"][0]["array"]

        >>> model_id = "kyutai/mimi"
        >>> model = MimiModel.from_pretrained(model_id)
        >>> feature_extractor = AutoFeatureExtractor.from_pretrained(model_id)

        >>> inputs = feature_extractor(raw_audio=audio_sample, return_tensors="pt")

        >>> outputs = model(**inputs)
        >>> audio_codes = outputs.audio_codes
        >>> audio_values = outputs.audio_values
        ```)r  r   re  r   )r   r   r   r    )
rz   r  r%   r!  r   r  r  r3   r  r   )r7   r  r  r  r   r   r    r  rI  r  r%  r   s               r+   r   zMimiModel.forward  s   t &1%<k$++BYBY ??<8==?L"kklN<Sal * O *!,K*9*=*=>O*P'_%)*9!*<'++k<AXfq+r&q)&5&9&9:K&L#!A%&5a&8#/FH_``#%$;$;	
 	
r*   )NNNN)r  )NNNNNN)NNr#  )r!   r"   r#   r   r9   r%   rY   rV   r
   r-   r   r   r  r&   r  rX   r  r   r[   r  r&  r]   r  r   r   r   r   r   s   @r+   r   r     s   )z )` )-7;%)#'!5ll!5 !5 	!5
 !5 .4!5 d{!5 D[!5 
u||U\\D00	1!5Fu/?/? EDTDT 4 4S 4( -1'+047;%)#'YYllYY llT)YY 	YY
 "'YY .4YY d{YY D[YY 
u||U\\D00	14E	EYY| )-#'	(||( ( D[	(
 
(. -104#'.H\\.H llT).H "'	.H
 D[.H 
u||U\\)	*->	>.H`  -1%)+/0404#'W
llW
 llT)W
 d
	W

 \\D(W
 "'W
 "'W
 D[W
 
u||U\\)	*Z	7W
 W
r*   r   )r   )r   )Jr$   r   collections.abcr   dataclassesr   typingr   r%   r    r   r  activationsr	   cache_utilsr
   r   masking_utilsr   modeling_layersr   modeling_outputsr   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   r   r   r   r   r   utils.genericr   configuration_mimir   
get_loggerr!   rq   r   r-   r[   r]   Moduler_   r   r   r   r   r   r(  r0  r2  rY   rV   rC  r   rV  rX  rp  r  r  r  r  r  r  r  r   __all__r)   r*   r+   <module>r:     s     $ !    & ! . > 9 7 K F & M M + * 
		H	% 
1 1  1<[ [| 
8 8  8* 
1 1  1$I IX7")) 7t'(bii '(T*")) *ZRYY  ><")) ><D(2bii "	UU\\ 	U# 	U%,, 	U( %II%<<% 
% <<	%
 LL4'% % % '(%2E)BII E)P25 2jR
299 R
j")) B*BII *\RYY (3")) 3l5ryy 5p %*/ %* %*P 
f
# f

f
R -
.r*   