
    ^j                     &   d dl Z d dlmZ d dlmZ d dlZd dlmZ ddlmZ	 ddl
mZ ddlmZ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 ddlmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z# ddl$m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2m3Z3  e#jh                  e5      Z6 e!d      e G d de                    Z7 G d dejp                        Z9 G d dejp                        Z: G d dejp                        Z;d  Z< ed!      dQd"       Z=d#ej|                  d$e?d%ej|                  fd&Z@	 dRd'ejp                  d(ej|                  d)ej|                  d*ej|                  d+ej|                  dz  d,eAd-eAd.ee    fd/ZB ee=       G d0 d1ejp                               ZC G d2 d3ejp                        ZD G d4 d5e      ZEe! G d6 d7e             ZF e!d8       G d9 d:eF             ZGe G d; d<e             ZHe G d= d>eH             ZI e!d?       G d@ dAeFe             ZJ G dB dCejp                        ZK G dD dEejp                        ZLe G dF dGe             ZM e!dH       G dI dJeFe2             ZN G dK dLeL      ZO e!dM       G dN dOe3eN             ZPg dPZQy)S    N)Callable)	dataclass)nn   )initialization)ACT2FN)CompileConfigGenerationMixinGenerationMode)use_kernel_func_from_hubuse_kernelized_func)GradientCheckpointingLayer)BaseModelOutputBaseModelOutputWithPoolingCausalLMOutput)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tuplelogging)maybe_autocastmerge_with_config_defaults)capture_outputs   )	AutoModel   )ParakeetCTCConfigParakeetEncoderConfigParakeetRNNTConfigParakeetTDTConfig)ParakeetRNNTDecoderCacheParakeetRNNTGenerationMixinParakeetTDTGenerationMixinz
    Extends [~modeling_outputs.BaseModelOutputWithPooling] to include the output attention mask since sequence length
    is not preserved in the model's forward.
    )custom_introc                   :    e Zd ZU dZdZej                  dz  ed<   y)ParakeetEncoderModelOutputa  
    attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
        Mask to avoid performing attention on padding token indices after sequence compression. Returned because the
        sequence length may differ from the input sequence length. Mask values selected in `[0, 1]`:

        - 1 for tokens that are **not masked**,
        - 0 for tokens that are **masked**.
    Nattention_mask)__name__
__module____qualname____doc__r*   torchTensor__annotations__     y/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/parakeet/modeling_parakeet.pyr)   r)   /   s     +/NELL4'.r3   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j                  fd       Z	 ej                         dej                  fd       Z xZS )$ParakeetEncoderRelPositionalEncodinginv_freqNconfigc                     t         |           |j                  | _        || _        | j	                  ||      }| j                  d|d       y )Ndevicer7   F)
persistent)super__init__max_position_embeddingsr8   .compute_default_relative_positional_parametersregister_buffer)selfr8   r;   r7   	__class__s       r4   r>   z-ParakeetEncoderRelPositionalEncoding.__init__F   sN    '-'E'E$FFvV\F]ZeDr3   returnc                     d}d|t        j                  d| j                  dt         j                        j	                  |t         j
                        | j                  z  z  z  }|S )Ng     @      ?r   r   dtype)r;   rH   )r/   arangehidden_sizeint64tofloat)r8   r;   baser7   s       r4   r@   zSParakeetEncoderRelPositionalEncoding.compute_default_relative_positional_parametersM   sd    
 Q 2 2AU[[ILLTZbgbmbmLn$$%
 r3   hidden_statesc                    |j                   d   }t        j                  |dz
  | d|j                        }| j                  d d d d f   j                         j                  |j                   d   dd      j                  |j                        }|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	      }|j                         }|j                         }	t        j                  ||	gd
      }
 |
j                   g |
j                   d d d }
d d d        
j                  |j"                        S # 1 sw Y   %xY w)Nr   r:   r   mpscpuF)device_typeenabledr   dimrG   )shaper/   rI   r;   r7   rM   expandrL   
isinstancetypestrr   	transposesincosstackreshaperH   )rB   rO   
seq_lengthposition_idsinv_freq_expandedposition_ids_expandedrT   freqsr_   r`   	pos_embeds              r4   forwardz,ParakeetEncoderRelPositionalEncoding.forward\   s   "((+
||JNZKML`L`aMM$4-(..0778K8KA8NPRTUVYYZgZnZno 	 !-T4] ; A A C -..33S9m>R>R>W>W[`>`   %% 	
 UC 	E&,,.1F1L1L1NNYYZ[]^_E))+C))+CS#JB7I)	))D9??3B+?DDI	E ||-"5"5|66	E 	Es   
BF::GNNN)r+   r,   r-   r/   r0   r1   r!   r>   staticmethodr@   no_gradri   __classcell__rC   s   @r4   r6   r6   C   sx    llE4 E /3%, 
  U]]_7U\\ 7 7r3   r6   c                   *     e Zd Zdef fdZd Z xZS )ParakeetEncoderFeedForwardr8   c                 `   t         |           t        j                  |j                  |j
                  |j                        | _        t        |j                     | _
        t        j                  |j
                  |j                  |j                        | _        |j                  | _        y )Nbias)r=   r>   r   LinearrJ   intermediate_sizeattention_biaslinear1r   
hidden_act
activationlinear2activation_dropoutrB   r8   rC   s     r4   r>   z#ParakeetEncoderFeedForward.__init__v   s|    yy!3!3V5M5MTZTiTij !2!23yy!9!96;M;MTZTiTij"(";";r3   c                     | j                  | j                  |            }t        j                  j	                  || j
                  | j                        }| j                  |      }|S )Nptraining)rz   rx   r   
functionaldropoutr|   r   r{   )rB   rO   s     r4   ri   z"ParakeetEncoderFeedForward.forward}   sU    ](CD--mt?V?Vaeanan-o]3r3   r+   r,   r-   r!   r>   ri   rn   ro   s   @r4   rq   rq   u   s    <4 <r3   rq   c                   .     e Zd Zddef fdZddZ xZS ) ParakeetEncoderConvolutionModuler8   c           	      6   t         |           |j                  }|&|j                  }t        t        |dd         | _        n#|d   }t        |j                  dd         | _        |dz
  dz  | _        t        j                  |d|z  ddd|j                  	      | _        t        j                  |||d| j                  ||j                  
      | _        t        j                  |      | _        t        j                  ||ddd|j                  	      | _        y)z
        Args:
            config (ParakeetEncoderConfig): Configuration for the model.
            module_config (dict): Configuration for the module (e.g., encoder or decoder).
        Nry   silukernel_sizerz   r   r   r   )r   stridepaddingrt   )r   r   groupsrt   )r=   r>   rJ   conv_kernel_sizer   getattrrz   getr   r   Conv1dconvolution_biaspointwise_conv1depthwise_convBatchNorm1dnormpointwise_conv2)rB   r8   module_configchannelsr   rC   s        r4   r>   z)ParakeetEncoderConvolutionModule.__init__   s    	%%  11K$WV\6%JKDO'6K$]%6%6|V%LMDO#aA-!yya(l!QVMdMd 
 !iiLL((
 NN8,	!yyhAaI`I` 
r3   c                     |j                  dd      }| j                  |      }t        j                  j	                  |d      }|c|j
                  t        j                  k(  rt        j                  | d      }nt        j                  |dk(   d      }|j                  |d      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }|j                  dd      S )aY  
        Compute convolution module.

        Args:
            hidden_states (`torch.Tensor` of shape `(batch, time, channels)`): Input tensor.
            attention_mask (`torch.Tensor` of shape `(batch, 1, time, time)`): Attention mask.

        Returns:
            `torch.Tensor`: Output tensor of shape `(batch, time, channels)`.

        r   r   rV           )r^   r   r   r   glurH   r/   boolallmasked_fillr   r   rz   r   )rB   rO   r*   all_masked_rowss       r4   ri   z(ParakeetEncoderConvolutionModule.forward   s     &//15 ,,];))-Q)? %##uzz1"'))^O"C"'))n.C,D!"L)55osKM ++M:		-06,,];&&q!,,r3   rj   r   ro   s   @r4   r   r      s     
4  
D"-r3   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..NrQ   r   rV   )rY   r/   cat)xx1x2s      r4   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r3   rotary_pos_embc                     |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          r4   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr3   rO   n_reprD   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)rY   rZ   rb   )rO   r   batchnum_key_value_headsslenhead_dims         r4   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr3   modulequerykeyvaluer*   scalingr   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 )Nr   r   rQ   rW   rH   r   r   )r   num_key_value_groupsr/   matmulr^   r   r   softmaxfloat32rL   rH   r   r   
contiguous)r   r   r   r   r*   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r4   eager_attention_forwardr      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$$r3   c                        e Zd ZdZdedef fdZ	 ddej                  dej                  dz  dej                  dz  d	e	e
   d
eej                  ej                  f   f
dZd Z xZS )ParakeetEncoderAttentionztMulti-head attention with relative positional encoding. See section 3.3 of https://huggingface.co/papers/1901.02860.r8   	layer_idxc                    t         |           || _        || _        t	        |d|j
                  |j                  z        | _        |j                  |j                  z  | _	        | j                  dz  | _
        |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                        | _        t        j                  |j
                  |j                  | j                  z  d      | _        t        j*                  t-        j.                  |j                  | j                              | _        t        j*                  t-        j.                  |j                  | j                              | _        y )Nr   g      Frs   )r=   r>   r8   r   r   rJ   num_attention_headsr   r   r   r   attention_dropout	is_causalr   ru   rw   q_projk_projv_projo_projrelative_k_proj	Parameterr/   zerosbias_ubias_vrB   r8   r   rC   s      r4   r>   z!ParakeetEncoderAttention.__init__  s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
  "yy););V=W=WZ^ZgZg=gnstll5;;v/I/I4==#YZll5;;v/I/I4==#YZr3   NrO   position_embeddingsr*   r   rD   c           
         |j                   d d }|\  }}||d| j                  f}| j                  |      j                  |      j	                  dd      }	| j                  |      j                  |      j	                  dd      }
| j                  |      j                  |      j	                  dd      }t        j                  | j                  j                  t              }|	| j                  j                  d| j                  j                  d| j                        z   }|	| j                  j                  d| j                  j                  d| j                        z   }| j                  |      }|j                  |d| j                  j                  | j                        }||j!                  dddd      z  }| j#                  |      }|dd |f   }|| j$                  z  }|)|j'                  |j)                         t+        d            } || f||
||| j,                  sdn| j.                  | j$                  d	|\  }} |j0                  g |d j3                         }| j5                  |      }||fS )
NrQ   r   r   r   r   .z-infr   )r   r   r   r*   r   r   )rY   r   r   viewr^   r   r   r   get_interfacer8   _attn_implementationr   r   r   r   r   permute
_rel_shiftr   masked_fill_logical_notrM   r   r   rb   r   r   )rB   rO   r   r*   r   input_shape
batch_sizerc   hidden_shapequery_statesr   r   attention_interfacequery_states_with_bias_uquery_states_with_bias_vrelative_key_states	matrix_bdr   r   s                      r4   ri   z ParakeetEncoderAttention.forward3  sj    $))#2.!,
J"JDMMB{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST(?(M(MKK,,.E)
 $0$++2B2Bt{{..4==3
 $
  $0$++2B2Bt{{..4==3
 $
  #223FG166z2t{{GfGfhlhuhuv -/B/J/J1aQRTU/VV	OOI.	c;J;./	,	% "..~/I/I/KUSY][I %8	%
*$#}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r3   c                     |j                   \  }}}}t        j                  j                  |d      }|j	                  ||d|      }|ddddddf   j	                  ||||      }|S )ztRelative position shift for Shaw et al. style attention. See appendix B of https://huggingface.co/papers/1901.02860.)r   r   )padrQ   Nr   )rY   r   r   r   r   )rB   attention_scoresr   	num_headsquery_lengthposition_lengths         r4   r   z#ParakeetEncoderAttention._rel_shiftl  st    ?O?U?U<
I|_==,,-=6,J+00YLY+Aq!"H5:::yR^`opr3   rj   )r+   r,   r-   r.   r!   intr>   r/   r0   r   r   tupleri   r   rn   ro   s   @r4   r   r     s    ~[4 [ [B /3	7)||7) #\\D07) t+	7)
 +,7) 
u||U\\)	*7)r r3   r   c                        e Zd Zdef fdZdej                  dej                  fdZ	d	dej                  dej                  fdZ
 xZS )
 ParakeetEncoderSubsamplingConv2Dr8   c                    t         |           |j                  | _        |j                  | _        |j                  | _        | j                  dz
  dz  | _        t        t        j                  |j                              | _        t        j                         | _        | j                   j#                  t        j$                  d| j                  | j                  | j
                  | j                               | j                   j#                  t        j&                                t)        | j                  dz
        D ]  }| j                   j#                  t        j$                  | j                  | j                  | j                  | j
                  | j                  | j                               | j                   j#                  t        j$                  | j                  | j                  d             | j                   j#                  t        j&                                 |j*                  | j
                  | j                  z  z  }t        j,                  |j                  |z  |j.                  d      | _        y )Nr   r   )r   r   r   )r   r   r   r   r   Trs   )r=   r>   subsampling_conv_kernel_sizer   subsampling_conv_strider   subsampling_conv_channelsr   r   r   mathlog2subsampling_factor
num_layersr   
ModuleListlayersappendConv2dReLUrangenum_mel_binsru   rJ   linear)rB   r8   i
out_lengthrC   s       r4   r>   z)ParakeetEncoderSubsamplingConv2D.__init__v  s   !>>4488((1,2dii(A(ABC mmoIIaD4D4DT[[bfbnbno	
 	2779%t*+ 	*AKK		MMMM $ 0 0;; LL==	 KKryySTUVKKrwwy)	*" ((T[[$//-IJ
ii @ @: MvOaOahlmr3   input_lengths
conv_layerc                     t        |d      rR|j                  dk7  rC|j                  }|j                  d   }|j                  d   }||d   z   |d   z   |z
  |z  dz   }|S |S )Nr   )r   r   r   r   )hasattrr   r   r   )rB   r  r	  r   r   r   output_lengthss          r4   _get_output_lengthz3ParakeetEncoderSubsamplingConv2D._get_output_length  sx    :x(Z->->&-H ((G$003K&&q)F+gaj871:ESX^^abbN!!r3   input_featuresr*   c                    |j                  d      }||j                  d      nd }| j                  D ]  } ||      }t        |t        j
                        s&|)| j                  ||      }|j                  d   }t        j                  ||j                        |d d d f   k  }||d d d d d d f   z  } |j                  dd      j                  |j                  d   |j                  d   d      }| j                  |      }|S )Nr   rQ   r   r:   r   )r   sumr   r[   r   r  r  rY   r/   rI   r;   r^   rb   r  )rB   r  r*   rO   current_lengthslayercurrent_seq_lengthchannel_masks           r4   ri   z(ParakeetEncoderSubsamplingConv2D.forward  s   &0034B4N.,,R0TX[[ 
	@E!-0M %+0J"&"9"9/5"Q%2%8%8%;"LL!3N<Q<QRUdefhlelUmm  aq$.>!??
	@ &//15==m>Q>QRS>TVcViVijkVlnpqM2r3   rj   )r+   r,   r-   r!   r>   r/   r0   r   r  r  ri   rn   ro   s   @r4   r   r   u  sI    !n4 !nF	 	")) 	ell ELL r3   r   c                        e 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j                  dz  dee	   d	ej                  f
d
Z
 xZS )ParakeetEncoderBlockNr8   r   c                    t         |           d| _        t        |      | _        t        ||      | _        t        |      | _        t        |      | _	        t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j                        | _        t        j                  |j                        | _        y )NF)r=   r>   gradient_checkpointingrq   feed_forward1r   	self_attnr   convfeed_forward2r   	LayerNormrJ   norm_feed_forward1norm_self_att	norm_convnorm_feed_forward2norm_outr   s      r4   r>   zParakeetEncoderBlock.__init__  s    &+#7?1&)D4V<	7?"$,,v/A/A"B\\&*<*<=f&8&89"$,,v/A/A"BV%7%78r3   rO   r*   r   r   rD   c                 x   |}| j                  | j                  |            }|d|z  z   }| j                  |      } | j                  d|||d|\  }}||z   }| j	                  | j                  |      |      }	||	z   }| j                  | j                  |            }
|d|
z  z   }| j                  |      }|S )Ng      ?)rO   r*   r   )r*   r2   )	r  r  r  r  r  r   r  r!  r"  )rB   rO   r*   r   r   residualnormalized_hidden_statesr   _conv_output
ff2_outputs              r4   ri   zParakeetEncoderBlock.forward  s     !**4+B+B=+QR 3#66#'#5#5m#D ' 
2) 3
 	
Q &3ii} =ni]%3''(?(?(NO
%j(88m4r3   rj   rk   )r+   r,   r-   r!   r   r>   r/   r0   r   r   ri   rn   ro   s   @r4   r  r    sx    94 9t 9$ /337	|| t+ #\\D0	
 +, 
r3   r  c                        e Zd ZU eed<   dZdZdZdZdgZ	dZ
dZdZdZdZdZeedZ ej(                          fd	       Zd
ej,                  fdZddej,                  dedz  fdZ xZS )ParakeetPreTrainedModelr8   modelr  audioTr  F)rO   
attentionsc                    t         |   |       t        | j                  dd      }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       y t	        |t              r<|j                  |j                        }t        j                  |j                  |       y y )Ninitializer_rangeg{Gz?r   )meanstd)r=   _init_weightsr   r8   r[   r   initnormal_r   r   r6   r@   copy_r7   )rB   r   r1  buffer_valuerC   s       r4   r2  z%ParakeetPreTrainedModel._init_weights  s    f%dkk#6=f67LLSc:LLSc: DE!PPQWQ^Q^_LJJv5 Fr3   r  c                    t        | j                  d| j                        }|j                  }|j                  }t	        t        j                  |j                              }|dz
  dz  dz  }||z
  }|}t        |      D ]Q  }	t        j                  |j                  t        j                        |z   |      dz   }t        j                  |      }S |j                  t        j                        S )Nencoder_configr   r   rG   rF   )r   r8   r   r   r   r   r   r   r  r/   divrL   rM   floor)
rB   r  r8  r   r   r   all_paddingsadd_padlengthsr&  s
             r4   _get_subsampling_output_lengthz6ParakeetPreTrainedModel._get_subsampling_output_length  s     .>L$AA77>#D#DEF
#aA-1,z" 	+Aii


 = GPSVVGkk'*G	+ zz		z**r3   Nr*   target_lengthc                     | j                  |j                  d            }||n|j                         }t        j                  ||j
                        |dddf   k  }|S )z
        Convert the input attention mask to its subsampled form. `target_length` sets the desired output length, useful
        when the attention mask length differs from `sum(-1).max()` (i.e., when the longest sequence in the batch is padded)
        rQ   Nr:   )r>  r  maxr/   rI   r;   )rB   r*   r?  r  
max_lengths        r4   _get_output_attention_maskz2ParakeetPreTrainedModel._get_output_attention_mask  sc    
 <<^=O=OPR=ST&3&?]^EWEWEY
j9N9NOR`abdhahRiir3   rj   )r+   r,   r-   r    r1   base_model_prefixmain_input_nameinput_modalitiessupports_gradient_checkpointing_no_split_modules_supports_flat_attention_mask_supports_sdpa_supports_flex_attn_supports_flash_attn_can_compile_fullgraph_supports_attention_backendr  r   _can_record_outputsr/   rm   r2  r0   r>  r   rC  rn   ro   s   @r4   r*  r*    s    &O&*#/0$(!N !!"&-.
 U]]_	6 	6+ELL +"	 	VY\`V` 	r3   r*  z{
    The Parakeet Encoder model, based on the [Fast Conformer architecture](https://huggingface.co/papers/2305.05084).
    c                        e Zd ZU eed<   dZdef fdZeee	e
	 	 ddej                  dej                  dz  dedee   d	ef
d
                            Z xZS )ParakeetEncoderr8   encoderc           	         t         |   |       || _        d| _        |j                  | _        |j
                  | _        |j                  | _        |j                  rt        j                  |j                        nd| _        t        |      | _        t        |      | _        t!        j"                  t%        |j&                        D cg c]  }t)        ||       c}      | _        | j-                          y c c}w )NFrF   )r=   r>   r8   r  r   dropout_positions	layerdropscale_inputr   sqrtrJ   input_scaler   subsamplingr6   encode_positionsr   r   r  num_hidden_layersr  r   	post_initr   s      r4   r>   zParakeetEncoder.__init__1  s     &+#~~!'!9!9))<B<N<N499V%7%78TW;FC DV LmmFKFLdLdFef!&)4f
 	 gs   
C:Nr  r*   output_attention_maskr   rD   c                 $   | j                  ||      }|| j                  z  }| j                  |      }t        j                  j                  || j
                  | j                        }t        j                  j                  || j                  | j                        }d}|u| j                  ||j                  d         }|j                  d      j                  d|j                  d   d      }||j                  dd      z  }|j                  d      }| j                  D ]E  }d}	| j                  r&t        j                  g       }
|
| j                   k  rd}	|	r: ||f||d	|}G t#        |||r|j%                         
      S d
      S )a  
        output_attention_mask (`bool`, *optional*, defaults to `True`):
            Whether to return the output attention mask. Only effective when `attention_mask` is provided.

        Example:

        ```python
        >>> from transformers import AutoProcessor, ParakeetEncoder
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/parakeet-ctc-1.1b"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> encoder = ParakeetEncoder.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

        >>> inputs = processor(ds[0]["audio"]["array"])
        >>> encoder_outputs = encoder(**inputs)

        >>> print(encoder_outputs.last_hidden_state.shape)
        ```
        r   Nr   r?  rQ   r   FT)r*   r   )last_hidden_stater*   )rY  rX  rZ  r   r   r   r   rT  rC  rY   r   rZ   r^   r   r/   randrU  r)   r   )rB   r  r*   r]  r   rO   r   output_maskencoder_layerto_dropdropout_probabilitys              r4   ri   zParakeetEncoder.forwardD  s   F ((H%(8(88"33MB--mt||VZVcVc-d mm334#9#9DMM 4 
 %99.XeXkXklmXn9oK(2215<<RATATUVAWY[\N+n.F.Fq!.LLN+55a8N![[ 	MG}}&+jjn#&7"G -!!#1(;! 	!	  *+0>0JOd;??,
 	
jn
 	
r3   )NT)r+   r,   r-   r!   r1   rD  r>   r   r   r   r   r/   r0   r   r   r   r   ri   rn   ro   s   @r4   rQ  rQ  (  s     "!!4 &  /3&*	B
B
 t+B
  $	B

 +,B
 
B
     B
r3   rQ  c                       e Zd ZU dZej
                  ed<   dZeej                     dz  ed<   dZ
eeej                        dz  ed<   dZeeej                        dz  ed<   y)ParakeetCTCGenerateOutputaz  
    Outputs of Parakeet CTC model generation.

    Args:
        sequences (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            The generated sequences. The second dimension (sequence_length) is either equal to `max_length` or shorter
            if all batches finished early due to the `eos_token_id`.
        logits (`tuple(torch.FloatTensor)` *optional*, returned when `output_logits=True`):
            Unprocessed prediction scores of the language modeling head (scores for each vocabulary token before SoftMax)
            at each generation step. Tuple of `torch.FloatTensor` with up to `max_new_tokens` elements (one element for
            each generated token), with each tensor of shape `(batch_size, config.vocab_size)`.
        attentions (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_attentions=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, num_heads, generated_length, sequence_length)`.
        hidden_states (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `output_hidden_states=True`):
            Tuple (one element for each generated token) of tuples (one element for each layer of the decoder) of
            `torch.FloatTensor` of shape `(batch_size, generated_length, hidden_size)`.
    	sequencesNlogitsr-  rO   )r+   r,   r-   r.   r/   
LongTensorr1   ri  r   FloatTensorr-  rO   r2   r3   r4   rg  rg    sm    & .2FE%##$t+29=JeE--./$6=<@M5u0012T9@r3   rg  c                   "     e Zd ZdZ fdZ xZS )ParakeetGenerateOutputz`
    Deprecated alias for ParakeetCTCGenerateOutput. Use ParakeetCTCGenerateOutput instead.
    c                 N    t        |   |i | t        j                  d       y )Nz`ParakeetGenerateOutput` is deprecated and removed starting from version 5.11.0; please use `ParakeetCTCGenerateOutput` instead.)r=   r>   loggerwarning_once)rB   argsr   rC   s      r4   r>   zParakeetGenerateOutput.__init__  s)    $)&) O	
r3   )r+   r,   r-   r.   r>   rn   ro   s   @r4   rm  rm    s    
 
r3   rm  zS
    Parakeet Encoder with a Connectionist Temporal Classification (CTC) head.
    c                   X    e Zd ZU eed<   def fdZee	 	 ddej                  dej                  dz  dej                  dz  de
e   def
d	              Z ej                         	 	 	 ddej                  dej                  dz  d
ededz  de
e   deej$                  z  fd       Z xZS )ParakeetForCTCr8   c                    t         |   |       t        j                  |j                        | _        t        j                  |j                  j                  |j                  d      | _
        | j                          y )Nr   r   )r=   r>   r   from_configr8  rR  r   r   rJ   
vocab_sizectc_headr\  r}   s     r4   r>   zParakeetForCTC.__init__  sY      ,,V-B-BC		&"7"7"C"CVEVEVdefr3   Nr  r*   labelsr   rD   c           
         ||j                  dd        | j                  d||d|}|j                  }| j                  |j	                  dd            j	                  dd      }d}|+|j
                  j                  d      }	|| j                  j                  k7  }
|
j                  d      }|j                  |
      }t        j                  j                  |dt        j                        j	                  d	d      }t        j                  j                   j#                  d
      5  t        j                  j%                  |||	|| j                  j                  | j                  j&                  | j                  j(                        }ddd       t+        |||j,                  |j.                        S # 1 sw Y   ,xY w)a  
        Example:

        ```python
        >>> from transformers import AutoProcessor, ParakeetForCTC
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/parakeet-ctc-1.1b"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = ParakeetForCTC.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

        >>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
        >>> outputs = model(**inputs)

        >>> print(outputs.loss)
        ```Nr]  Tr  r*   r   r   rQ   r   r   F)rU   )blank	reductionzero_infinity)lossri  rO   r-  r2   )
setdefaultrR  r`  rw  r^   r*   r  r8   pad_token_idmasked_selectr   r   log_softmaxr/   r   backendscudnnflagsctc_lossctc_loss_reductionctc_zero_infinityr   rO   r-  )rB   r  r*   rx  r   encoder_outputsrO   ri  r~  encoder_lengthslabels_masktarget_lengthsflattened_targets	log_probss                 r4   ri   zParakeetForCTC.forward  s   : 5t<&$,, 
))
 
 (99}66q!<=GG1M-<<@@DO !DKK$<$<<K(__R0N & 4 4[ A 11&b1V``abdefI%%++E+: 	}}--%#"++22"kk<<"&++"?"? . 	 )77&11	
 	
	 	s   ,A#F::Greturn_dict_in_generatecompile_configc                 r   || j                  |      n| j                  }d|d<    |d	||d|}|j                  j                  d      }|:| j	                  ||j
                  d         }| j                  j                  || <   |r-t        ||j                  |j                  |j                        S |S )
a  
        compile_config ([`~generation.CompileConfig`], *optional*):
            If provided, `torch.compile` will be applied to the forward calls in the decoding loop.

        Example:

        ```python
        >>> from transformers import AutoProcessor, ParakeetForCTC
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/parakeet-ctc-1.1b"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = ParakeetForCTC.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

        >>> inputs = processor(ds[0]["audio"]["array"], text=ds[0]["text"])
        >>> predicted_ids = model.generate(**inputs)
        >>> transcription = processor.batch_decode(predicted_ids, skip_special_tokens=True)

        >>> print(transcription)
        ```
        Treturn_dictrz  rQ   rV   r   r_  )rh  ri  r-  rO   r2   )get_compiled_call__call__ri  argmaxrC  rY   r8   r  rg  r-  rO   )	rB   r  r*   r  r  r   model_forwardoutputsrh  s	            r4   generatezParakeetForCTC.generate  s    B CQB\..~>bfbobo $}"/ #
))#
 #
 NN))b)1	 %!<<^[d[j[jkl[m<nN)-)A)AI~o&",#~~"--%33	  r3   rk   )NFN)r+   r,   r-   r    r1   r>   r   r   r/   r0   r   r   r   ri   rm   r   r	   rg  rj  r  rn   ro   s   @r4   rs  rs    s    0   /3&*	B
B
 t+B
 t#	B

 +,B
 
B
  B
H U]]_ /3(-/399 t+9 "&	9
 &,9 +,9 
#U%5%5	59 9r3   rs  c                   n     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
 xZS )
ParakeetRNNTDecoderz'LSTM-based prediction network For RNN-Tr8   c                 x   t         |           |j                  | _        t        j                  |j
                  |j                        | _        t        j                  |j                  |j                  |j                  d      | _
        t        j                  |j                  |j                        | _        y )NT)
input_sizerJ   r   batch_first)r=   r>   blank_token_idr   	Embeddingrv  decoder_hidden_size	embeddingLSTMnum_decoder_layerslstmru   decoder_projectorr}   s     r4   r>   zParakeetRNNTDecoder.__init__K  s    $33f&7&79S9STGG112200	
	 "$6+E+EvGaGa!br3   N	input_idscacherD   c                    |>|d d df   | j                   k(  }|j                  r|j                         r|j                  S | j	                  |      }|8|j                  }|s|j                  |       |j                  |j                  f}nd }| j                  ||      \  }\  }}	| j                  |      }
|(r nd }|j                  |
||	|       |j                  S |
S )NrQ   )mask)r  is_initializedr   r  r  lazy_initializationhidden_state
cell_stater  r  update)rB   r  r  
blank_mask
embeddingswas_initializedhidden_cell_stateslstm_outputr  r  decoder_outputr  s               r4   ri   zParakeetRNNTDecoder.forwardW  s    
 "1b5)T-@-@@J##
(8{{"^^I.
 #22O"))*5"'"4"4e6F6F!G!%26))JHZ2[//lJ//<"1J;tDLLzLM;;r3   rj   )r+   r,   r-   r.   r"   r>   r/   rj  r$   r0   ri   rn   ro   s   @r4   r  r  H  sJ    1
c1 
c 26## ($. 
	r3   r  c                        e Zd ZdZdef fdZdej                  dej                  deej                  ej                  f   fdZ	 xZ
S )ParakeetRNNTJointNetworkzPJoint network that combines encoder and decoder outputs to predict token logits.r8   c                     t         |           t        |j                     | _        t        j                  |j                  |j                        | _	        |j                  | _        y rj   )
r=   r>   r   ry   rz   r   ru   r  rv  headr}   s     r4   r>   z!ParakeetRNNTJointNetwork.__init__{  sK     !2!23IIf88&:K:KL	 ++r3   decoder_hidden_statesencoder_hidden_statesrD   c                 L    | j                  ||z         }| j                  |      S rj   )rz   r  )rB   r  r  joint_outputs       r4   ri   z ParakeetRNNTJointNetwork.forward  s(    
 '<?T'TUyy&&r3   )r+   r,   r-   r.   r"   r>   r/   r0   r   ri   rn   ro   s   @r4   r  r  x  sN    Z,1 ,'$||'  %||' 
u||U\\)	*	'r3   r  c                   v    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<   y)ParakeetRNNTOutputa  
    Output of the Parakeet RNN-T forward pass.

    Args:
        loss (`torch.FloatTensor`, *optional*):
            RNN-T loss, returned when `labels` are provided.
        logits (`torch.FloatTensor`):
            Joint token logits. Shape is `(batch, T, U+1, vocab)` for training
            or `(batch, 1, 1, vocab)` for single-step inference.
        decoder_cache (`ParakeetRNNTDecoderCache`, *optional*):
            Decoder LSTM cache containing hidden state, cell state, and last output.
    Nr~  ri  decoder_cache)r+   r,   r-   r.   r~  r/   rk  r1   ri  r  r$   r2   r3   r4   r  r    sC     &*D%

d
")'+FE$+59M+d29r3   r  z?
    Parakeet Encoder with an RNN-T (RNN Transducer) head.
    c                       e Zd ZU eed<   dgZej                  gZdef fdZ	e
	 ddej                  dej                  dz  dee   defd	       Zee
	 	 	 	 	 	 	 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eej,                     z  dz  dej                  dz  dee   defd              Z xZS )ParakeetForRNNTr8   r  c                 `   t         |   |       t        j                  |j                        | _        t        j                  |j                  j                  |j                        | _
        t        |      | _        t        |      | _        |j                  | _        | j!                          y rj   )r=   r>   r   ru  r8  rR  r   ru   rJ   r  encoder_projectorr  decoderr  jointmax_symbols_per_stepr\  r}   s     r4   r>   zParakeetForRNNT.__init__  s}      ,,V-B-BC!#6+@+@+L+LfNhNh!i*62-f5
$*$?$?!r3   Nr  r*   r   rD   c                 p     | j                   d||d|}| j                  |j                        |_        |S )Nrz  r2   )rR  r  r`  pooler_output)rB   r  r*   r   r  s        r4   get_audio_featuresz"ParakeetForRNNT.get_audio_features  sJ     '$,, 
))
 

 )-(>(>?`?`(a%r3   decoder_input_idsr  use_decoder_cacher  rx  c           
         | | j                   d	||d|}|r|t        | j                        }| j                  ||      }	| j	                  |j
                  dddddddf   |	dddddddf         j                  d      }
d}||j                  j                  d      } | j                  d	|
dddt        |j                               f   |||| j                  j                  k7  j                  d      | j                  j                  d|}t        ||
|j                  |j
                  |j                  |j                   |      S )
a?  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
            Decoder input token ids for single-step inference.
        decoder_cache (`ParakeetRNNTDecoderCache`, *optional*):
            Decoder LSTM cache. When provided and initialized, the cached `decoder_output` is reused
            (e.g. during blank-skipping) instead of running the decoder. When `input_ids` is provided,
            the decoder runs and the cache is updated in-place.
        use_decoder_cache (`bool`, *optional*):
            Whether to use a decoder cache. When `True` and `decoder_cache` is `None`, a new cache
            is created automatically during the forward pass.
        encoder_outputs (`tuple(torch.FloatTensor)`, *optional*):
            Pre-computed encoder outputs (last_hidden_state, pooler_output, hidden_states, attentions, attention_mask).
            Can be a tuple or `ParakeetEncoderModelOutput`.

        Example:

        ```python
        >>> from transformers import AutoProcessor, ParakeetForRNNT
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/parakeet-rnnt-0.6b"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = ParakeetForRNNT.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

        >>> inputs = processor(ds[0]["audio"]["array"])
        >>> outputs = model(**inputs)
        ```
        Nrz  r  r  r  r   rQ   )ri  rx  logit_lengthslabel_lengthsr  r~  ri  r`  r  rO   r-  r  r2   )r  r$   r8   r  r  r  squeezer*   r  loss_functionr   rA  r  r  r`  rO   r-  )rB   r  r*   r  r  r  r  rx  r   r  ri  r~  r  s                r4   ri   zParakeetForRNNT.forward  sv   X "5d55 -- O !64T[[AM $->m T"1"?"?1dA"N"74A"F  
 '!* 	
 +::>>rBM%4%% a!;3}'8'8':#;!;;<+%)C)CCHHL#{{99 D "-??)77)77&11'
 	
r3   rj   NNNNNNN)r+   r,   r-   r"   r1   rH  r   GREEDY_SEARCH_supported_generation_modesr>   r   r/   r0   r   r   r)   r  r   rj  r$   r   r   rk  r  ri   rn   ro   s   @r4   r  r    sc    ./#1#?#?"@1   /3 t+ +,	
 
$   /3.2599=)-X\&*N
t+N
 t+N
 !++d2	N

 0$6N
  $;N
 4eE<M<M6NNQUUN
 t#N
 +,N
 
N
  N
r3   r  c                   (     e Zd ZdZdef fdZ xZS )ParakeetTDTJointNetworka
  Extends the RNN-T joint network with a duration head.

    The only difference from [`ParakeetRNNTJointNetwork`] is the output width of `head`: it grows from
    `vocab_size` to `vocab_size + len(durations)` so the network jointly predicts tokens and durations.
    r8   c                     t         |   |       t        j                  |j                  |j
                  t        |j                        z         | _        y rj   )	r=   r>   r   ru   r  rv  len	durationsr  r}   s     r4   r>   z ParakeetTDTJointNetwork.__init__  s?     IIf88&:K:KcRXRbRbNc:cd	r3   )r+   r,   r-   r.   r#   r>   rn   ro   s   @r4   r  r    s    e0 e er3   r  zG
    Parakeet Encoder with a TDT (Token Duration Transducer) head.
    c                        e Zd ZU eed<   def fdZee	 	 	 	 	 	 	 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eej                     z  dz  d
ej                  dz  dee   defd              Z xZS )ParakeetForTDTr8   c                 d    t         |   |       t        |      | _        | j	                          y rj   )r=   r>   r  r  r\  r}   s     r4   r>   zParakeetForTDT.__init__(  s&     ,V4
r3   Nr  r*   r  r  r  r  rx  r   rD   c                    | | j                   d
||d|}|r|t        | j                        }| j                  ||      }	| j	                  |j
                  dddddddf   |	dddddddf         j                  d      }
d}| | j                  d
|
dd| j                  j                  f   |
d| j                  j                  df   ||j                  j                  d      || j                  j                  k7  j                  d      | j                  j                  | j                  j                  d|}t        ||
|j                  |j
                  |j                   |j"                  |	      S )a?  
        decoder_input_ids (`torch.LongTensor` of shape `(batch_size, 1)`, *optional*):
            Decoder input token ids for single-step inference.
        decoder_cache (`ParakeetRNNTDecoderCache`, *optional*):
            Decoder LSTM cache. When provided and initialized, the cached `decoder_output` is reused
            (e.g. during blank-skipping) instead of running the decoder. When `input_ids` is provided,
            the decoder runs and the cache is updated in-place.
        use_decoder_cache (`bool`, *optional*):
            Whether to use a decoder cache. When `True` and `decoder_cache` is `None`, a new cache
            is created automatically during the forward pass.
        encoder_outputs (`tuple(torch.FloatTensor)`, *optional*):
            Pre-computed encoder outputs (last_hidden_state, pooler_output, hidden_states, attentions, attention_mask).
            Can be a tuple or `ParakeetEncoderModelOutput`.

        Example:

        ```python
        >>> from transformers import AutoProcessor, ParakeetForTDT
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/parakeet-tdt-0.6b-v3"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = ParakeetForTDT.from_pretrained(model_id)

        >>> ds = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation")
        >>> ds = ds.cast_column("audio", Audio(sampling_rate=processor.feature_extractor.sampling_rate))

        >>> inputs = processor(ds[0]["audio"]["array"])
        >>> outputs = model(**inputs)
        ```
        Nrz  r  r  r   .rQ   )token_logitsduration_logitsrx  r  r  r  r  r  r2   )r  r$   r8   r  r  r  r  r  rv  r*   r  r  r  r  r  r`  rO   r-  )rB   r  r*   r  r  r  r  rx  r   r  ri  r~  s               r4   ri   zParakeetForTDT.forward.  s   X "5d55 -- O !64T[[AM $->m T"1"?"?1dA"N"74A"F  
 '!* 	
 %4%% 	#C)A4;;+A+A)A$AB &sDKK,B,B,D'D E-<<@@D%)A)AAFFrJ#{{99++//	 	D "-??)77)77&11'
 	
r3   r  )r+   r,   r-   r#   r1   r>   r   r   r/   r0   rj  r$   r   r)   r   rk  r   r   r  ri   rn   ro   s   @r4   r  r     s     0   /3.2599=)-X\&*O
t+O
 t+O
 !++d2	O

 0$6O
  $;O
 4eE<M<M6NNQUUO
 t#O
 +,O
 
O
  O
r3   r  )rs  r  r  rQ  r*  )r   )r   )Rr   collections.abcr   dataclassesr   r/   r    r   r3  activationsr   
generationr	   r
   r   integrationsr   r   modeling_layersr   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   r   utils.genericr   r   utils.output_capturingr   autor   configuration_parakeetr    r!   r"   r#   generation_parakeetr$   r%   r&   
get_loggerr+   ro  r)   Moduler6   rq   r   r   r   r0   r   r   rM   r   r   r   r  r*  rQ  rg  rm  rs  r  r  r  r  r  r  __all__r2   r3   r4   <module>r     s$  *  $ !   & ! H H I 9 [ [ F & _ _ G 5  s s r r 
		H	%  
/!; 
/ 
//7299 /7d E-ryy E-P( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*_ ryy _  +_ DBryy BJ,5 ,^ ;o ; ;| 
]
- ]

]
@ A A A4 	
6 	
 	
 
K,o K
K\-")) -`'ryy '$ :3 : :& 
n
-/J n

n
b	e6 	e 
Z
/ Z

Z
z pr3   