
    ^j-~                        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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 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%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z-  G d dej\                        Z/ G d dej\                        Z0d Z1 ed      dBd       Z2dejf                  de4d ejf                  fd!Z5	 dCd"ej\                  d#ejf                  d$ejf                  d%ejf                  d&ejf                  dz  d'e6d(e6d)ee!   fd*Z7 ee2       G d+ d,ej\                               Z8 G d- d.ej\                        Z9 G d/ d0ej\                        Z: G d1 d2e      Z;e" G d3 d4e             Z< e"d56      e G d7 d8e                    Z= e"d96       G d: d;e<             Z>e G d< d=e              Z? e"d>6       G d? d@e<e             Z@g dAZAy)D    )Callable)	dataclass)OptionalN)nn   )ACT2FN)CompileConfigGenerationMixin)use_kernel_func_from_hubuse_kernelized_func)create_bidirectional_mask)GradientCheckpointingLayer)BaseModelOutputWithPoolingCausalLMOutput)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ModelOutputTransformersKwargsauto_docstringcan_return_tuple)maybe_autocastmerge_with_config_defaults)capture_outputs   )	AutoModel   )LasrCTCConfigLasrEncoderConfigc                   \     e Zd Zdef fdZdej                  dej                  fdZ xZS )LasrEncoderSubsamplingconfigc                 (   t         |           t        j                  |j                  |j
                        | _        t        j                  |j
                  |j
                  |j                  |j                        | _
        t        j                  |j
                  |j                  |j                  |j                        | _        t        j                  |j                  |j
                        | _        t        j                         | _        y )N)kernel_sizestride)super__init__r   Linearnum_mel_binshidden_sizedense_0Conv1dsubsampling_conv_kernel_sizesubsampling_conv_strideconv_0subsampling_conv_channelsconv_1dense_1ReLUact_fnselfr$   	__class__s     q/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/lasr/modeling_lasr.pyr)   zLasrEncoderSubsampling.__init__-   s    yy!4!4f6H6HIii;;11	
 ii,,;;11	
 yy!A!A6CUCUVggi    input_featuresreturnc                 ,   | j                  | j                  |            }|j                  dd      }| j                  | j                  |            }| j                  | j	                  |            }|j                  dd      }| j                  |      S )Nr   r   )r6   r-   	transposer1   r3   r4   )r8   r<   hidden_statess      r:   forwardzLasrEncoderSubsampling.forward?   sz    DLL$@A%//15DKK$>?DKK$>?%//15||M**r;   )	__name__
__module____qualname__r!   r)   torchTensorrA   __classcell__r9   s   @r:   r#   r#   ,   s+     0  $+ell +u|| +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 )LasrEncoderRotaryEmbeddinginv_freqNr$   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defaultrK   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr$   rope_parametersrM   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r8   r$   devicerope_init_fnrK   r9   s        r:   r)   z#LasrEncoderRotaryEmbedding.__init__K   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr;   rY   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_dimNg      ?r   r   dtype)rY   r`   )	rT   getattrr,   num_attention_headsrE   arangeint64tofloat)r$   rY   r[   basedimattention_factorrK   s          r:   rU   z:LasrEncoderRotaryEmbedding.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   r   mpscpuF)device_typeenabledr   rh   r_   )rK   rf   expandshapere   rY   
isinstancetypestrr   r?   rE   catcosrV   sinr`   )
r8   xposition_idsinv_freq_expandedposition_ids_expandedrn   freqsembrw   rx   s
             r:   rA   z"LasrEncoderRotaryEmbedding.forwardy   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$N)NNN)rB   rC   rD   rE   rF   __annotations__r!   r)   staticmethodr   inttuplerf   rU   no_gradr   rA   rG   rH   s   @r:   rJ   rJ   H   s    llV0 V  +/+/"*!D(*(* t* 
~u$	%	* *: U]]_<  <r;   rJ   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..Nrk   r   rp   )rr   rE   rv   )ry   x1x2s      r:   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r;   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krw   rx   unsqueeze_dimq_embedk_embeds          r:   apply_rotary_pos_embr      sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr;   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)rr   rq   reshape)r@   r   batchnum_key_value_headsslenr^   s         r:   	repeat_kvr      so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr;   modulequerykeyvalueattention_maskscaling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 )Nr   r   rk   rh   r`   ptrainingr   )r   num_key_value_groupsrE   matmulr?   r   
functionalsoftmaxfloat32re   r`   r   r   
contiguous)r   r   r   r   r   r   r   r   
key_statesvalue_statesattn_weightsattn_outputs               r:   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$$r;   c                        e Zd ZdZdedef fdZ	 	 ddej                  de	ej                  ej                  f   dz  dej                  dz  d	e
e   d
e	ej                  ej                  f   f
dZ xZS )LasrEncoderAttentionz=Multi-headed attention from 'Attention Is All You Need' paperr$   	layer_idxc                 d   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                        | _        y )Nr^   g      Fbias)r(   r)   r$   r   ra   r,   rb   r^   r   r   r   attention_dropout	is_causalr   r*   attention_biasq_projk_projv_projo_projr8   r$   r   r9   s      r:   r)   zLasrEncoderAttention.__init__   sM   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r;   Nr@   position_embeddingsr   r   r=   c                    |j                   d d }g |d| j                  }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }| j                  |      j                  |      j	                  dd      }	|\  }
}t        |||
|      \  }}t        j                  | j                  j                  t              } || |||	|f| j                  sdn| j                  | j                  d|\  }} |j                   g |d j#                         }| j%                  |      }||fS )Nrk   r   r           )r   r   )rr   r^   r   viewr?   r   r   r   r   get_interfacer$   _attn_implementationr   r   r   r   r   r   r   )r8   r@   r   r   r   input_shapehidden_shapequery_statesr   r   rw   rx   attention_interfacer   r   s                  r:   rA   zLasrEncoderAttention.forward   sk    $))#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(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r;   NN)rB   rC   rD   __doc__r!   r   r)   rE   rF   r   r   r   rA   rG   rH   s   @r:   r   r      s    G
0 
S 
4 IM.2	")||") #5<<#=>E") t+	")
 +,") 
u||U\\)	*")r;   r   c                   .     e Zd Zddef fdZddZ xZS )LasrEncoderConvolutionModuler$   c           	      V   t         |           |j                  }|&|j                  }t        t        |dd         | _        n#|d   }t        |j                  dd         | _        d| _        t        j                  |d|z  ddd	|j                  
      | _        t        j                  |||d| j                  ||j                        | _        t        j                  |j                  |j                        | _        t        j                  ||ddd	|j                  
      | _        y)z
        Args:
            config (LasrEncoderConfig): Configuration for the model.
            module_config (dict): Configuration for the module (e.g., encoder or decoder).
        N
hidden_actsilur&   
activationsamer   r   r   )r&   r'   paddingr   )r'   r   groupsr   )momentum)r(   r)   r,   conv_kernel_sizer   ra   r   getr   r   r.   convolution_biaspointwise_conv1depthwise_convBatchNorm1dbatch_norm_momentumnormpointwise_conv2)r8   r$   module_configchannelsr&   r9   s        r:   r)   z%LasrEncoderConvolutionModule.__init__  s	    	%%  11K$WV\6%JKDO'6K$]%6%6|V%LMDO!yya(l!QVMdMd 
 !iiLL((
 NN6#5#5@Z@Z[	!yyhAaI`I` 
r;   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   rp   r   )r?   r   r   r   glur`   rE   boolallmasked_fillr   r   r   r   )r8   r@   r   all_masked_rowss       r:   rA   z$LasrEncoderConvolutionModule.forward2  s     &//15 ,,];))-Q)? %##uzz1"'))^O"C"'))n.C,D!"L)55osKM ++M:		-06,,];&&q!,,r;   r   rB   rC   rD   r!   r)   rA   rG   rH   s   @r:   r   r     s     
0  
D"-r;   r   c                   *     e Zd Zdef fdZd Z xZS )LasrEncoderFeedForwardr$   c                 `   t         |           t        j                  |j                  |j
                  |j                        | _        t        |j                     | _
        t        j                  |j
                  |j                  |j                        | _        |j                  | _        y )Nr   )r(   r)   r   r*   r,   intermediate_sizer   linear1r   r   r   linear2activation_dropoutr7   s     r:   r)   zLasrEncoderFeedForward.__init__X  s|    yy!3!3V5M5MTZTiTij !2!23yy!9!96;M;MTZTiTij"(";";r;   c                     | j                  | j                  |            }t        j                  j	                  || j
                  | j                        }| j                  |      }|S )Nr   )r   r   r   r   r   r   r   r   )r8   r@   s     r:   rA   zLasrEncoderFeedForward.forward_  sU    ](CD--mt?V?Vaeanan-o]3r;   r   rH   s   @r:   r   r   W  s    <0 <r;   r   c                        e 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j                  f
d
Z
 xZS )LasrEncoderBlockr$   r   c                    t         |           d| _        t        |      | _        t        ||      | _        t        |      | _        t        |      | _	        t        j                  |j                  |j                  d      | _        t        j                  |j                  |j                  d      | _        t        j                  |j                  |j                  d      | _        t        j                  |j                  |j                  d      | _        t        j                  |j                  |j                  d      | _        |j&                  | _        |j(                  | _        y )NFr   )r(   r)   gradient_checkpointingr   feed_forward1r   	self_attnr   convfeed_forward2r   	LayerNormr,   layer_norm_epsnorm_feed_forward1norm_self_att	norm_convnorm_feed_forward2norm_outfeed_forward_residual_weightsconv_residual_weightsr   s      r:   r)   zLasrEncoderBlock.__init__g  s   &+#3F;-fi@08	3F;"$,,v/A/A6CXCX_d"e\\&*<*<f>S>SZ_`f&8&8&:O:OV[\"$,,v/A/A6CXCX_d"eV%7%79N9NUZ[-3-Q-Q*%+%A%A"r;   Nr@   r   r   r   r=   c                 0   |}| j                  | j                  |            }| j                  d   |z  | j                  d   |z  z   }| j                  |      } | j                  d|||d|\  }}||z   }| j                  | j                  |      |      }	| j                  d   |z  | j                  d   |	z  z   }|}| j                  | j                  |            }| j                  d   |z  | j                  d   |z  z   }| j                  |      }|S )Nr   r   )r@   r   r   )r    )r   r   r   r   r   r   r   r   r   r   r   )
r8   r@   r   r   r   residualnormalized_hidden_statesr   _conv_outputs
             r:   rA   zLasrEncoderBlock.forwardy  sJ    !**4+B+B=+QR..q1H<t?a?abc?dgt?tt 	 $(#5#5m#D ' 
2) 3
 	
Q &3ii} =ni]2215EHbHbcdHehsHss **4+B+B=+QR..q1H<t?a?abc?dgt?tt 	 m4r;   r   )rB   rC   rD   r!   r   r)   rE   rF   r   r   rA   rG   rH   s   @r:   r   r   f  sw    B0 BS B* /337	!||! t+! #\\D0	!
 +,! 
!r;   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d	ej(                  fd
Zddej(                  dedz  fdZy)LasrPreTrainedModelr$   modelr<   audioTr   F)r@   
attentionsinput_lengthsc                     t        | j                  t              r| j                  j                  n| j                  }|j                  }|j
                  }d}t        |      D ]  }||z
  |z  dz   } |S )Nr   r   )rs   r$   r    encoder_configr/   r0   range)r8   r  r  r&   r'   
num_layersr  s          r:   _get_subsampling_output_lengthz2LasrPreTrainedModel._get_subsampling_output_length  st    7A$++}7]33cgcncn$AA77
z" 	HA*[8VCaGM	H r;   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)
        rk   NrY   )r  summaxrE   rc   rY   )r8   r   r  output_lengths
max_lengths        r:   _get_output_attention_maskz.LasrPreTrainedModel._get_output_attention_mask  sc    
 <<^=O=OPR=ST&3&?]^EWEWEY
j9N9NOR`abdhahRiir;   r   )rB   rC   rD   r    r   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_outputsrE   rF   r  r   r  r  r;   r:   r  r    s    &O&*#+,$(!N !!"&)*
	ELL 		 	VY\`V` 	r;   r  z
    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)LasrEncoderModelOutputa  
    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**.
    Nr   )rB   rC   rD   r   r   rE   rF   r   r  r;   r:   r'  r'    s     +/NELL4'.r;   r'  zh
    The LasrEncoder model, based on the Conformer architecture](https://arxiv.org/abs/2005.08100).
    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z  dee   d	ef
d
                            Z xZS )LasrEncoderr$   encoderc           	         t         |   |       d| _        |j                  | _        |j                  | _        |j
                  | _        t        |      | _        t        |      | _	        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        j                   |j"                  |j$                  d      | _        | j)                          y c c}w )NF)epsr   )r(   r)   r   r   dropout_positions	layerdropr#   
subsamplerrJ   
rotary_embr   
ModuleListr  num_hidden_layersr   layersr   r,   r   out_norm	post_initr   s      r:   r)   zLasrEncoder.__init__  s     &+#~~!'!9!9))084V<mmBGH`H`BabYfi0b
 V%7%7V=R=RY^_	 cs   C2Nr<   r   output_attention_maskr   r=   c                    | j                  |      }| j                  |t        j                  |j                  d   |j
                        j                  d            \  }}t        j                  j                  || j                  | j                        }t        j                  j                  || j                  | j                        }t        j                  j                  || j                  | j                        }d}|"| j                  ||j                  d         }|}t        | j                  ||      }| j                  D ]G  }	d}
| j                  r&t        j                   g       }|| j"                  k  rd	}
|
r: |	|f|||fd
|}I | j%                  |      }t'        ||r||j)                               S d      S )a;  
        output_attention_mask (`bool`, *optional*):
            Whether to return the output attention mask.

        Example:

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

        >>> model_id = "google/medasr"
        >>> 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   r  r   r   Nr  )r$   inputs_embedsr   FT)r   r   )last_hidden_stater   )r/  r0  rE   rc   rr   rY   r   r   r   r   r   r-  r  r   r$   r3  randr.  r4  r'  r   )r8   r<   r   r6  r   r@   rw   rx   output_maskencoder_layerto_dropdropout_probabilitys               r:   rA   zLasrEncoder.forward  s   F 7??5<<(;(;A(>}G[G[\ffghi
S --mt||VZVcVc-dmm##C4+A+ADMM#Zmm##C4+A+ADMM#Z%99.XeXkXklmXn9oK(N2;;')
 "[[ 	MG}}&+jjn#&7"G -!!#1),c
! 	!	  m4%+0E+Ja;??,
 	
gk
 	
r;   r   )rB   rC   rD   r!   r   r  r)   r   r   r   r   rE   rF   r   r   r   r'  rA   rG   rH   s   @r:   r)  r)    s     !0 "  /3-1	H
H
 t+H
  $d{	H

 +,H
 
 H
     H
r;   r)  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)LasrCTCGenerateOutputav  
    Outputs of Lasr 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
  r@   )rB   rC   rD   r   rE   
LongTensorr   rC  r   FloatTensorr
  r@   r  r;   r:   rA  rA  H  sm    & .2FE%##$t+29=JeE--./$6=<@M5u0012T9@r;   rA  zO
    Lasr 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 )
LasrForCTCr$   c                    t         |   |       t        j                  |j                        | _        t        j                  |j                  j                  |j                  d      | _
        | j                          y )Nr   )r&   )r(   r)   r   from_configr  r*  r   r.   r,   
vocab_sizectc_headr5  r7   s     r:   r)   zLasrForCTC.__init__k  sY      ,,V-B-BC		&"7"7"C"CVEVEVdefr;   Nr<   r   labelsr   r=   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, LasrForCTC
        >>> from datasets import load_dataset, Audio

        >>> model_id = "nvidia/lasr-ctc-1.1b"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = LasrForCTC.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)
        ```Nr6  Tr<   r   r   r   rk   r   r   F)ro   )blank	reductionzero_infinity)lossrC  r@   r
  r  )
setdefaultr*  r:  rK  r?   r   r  r$   pad_token_idmasked_selectr   r   log_softmaxrE   r   backendscudnnflagsctc_lossctc_loss_reductionctc_zero_infinityr   r@   r
  )r8   r<   r   rL  r   encoder_outputsr@   rC  rR  encoder_lengthslabels_masktarget_lengthsflattened_targets	log_probss                 r:   rA   zLasrForCTC.forwards  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   
        Example:

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

        >>> model_id = "google/medasr"
        >>> processor = AutoProcessor.from_pretrained(model_id)
        >>> model = LasrForCTC.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_dictrN  rk   rp   r   r8  )rB  rC  r
  r@   r  )get_compiled_call__call__rC  argmaxr  rr   r$   rT  rA  r
  r@   )	r8   r<   r   rc  rd  r   model_forwardoutputsrB  s	            r:   generatezLasrForCTC.generate  s    < CQB\..~>bfbobo $}"/ #
))#
 #
 NN))b)1	 %!<<^[d[j[jkl[m<nN)-)A)AI~o&"(#~~"--%33	  r;   r   )NFN)rB   rC   rD   r    r   r)   r   r   rE   rF   r   r   r   rA   r   r   r	   rA  rD  rl  rG   rH   s   @r:   rG  rG  c  s    }   /3&*	B
B
 t+B
 t#	B

 +,B
 
B
  B
H U]]_ /3(-/366 t+6 "&	6
 &,6 +,6 
!1!1	16 6r;   rG  )rG  r)  r  )r   )r   )Bcollections.abcr   dataclassesr   typingr   rE   r   activationsr   
generationr	   r
   integrationsr   r   masking_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   utils.output_capturingr   autor   configuration_lasrr    r!   Moduler#   rJ   r   r   rF   r   r   rf   r   r   r   r   r   r  r'  r)  rA  rG  __all__r  r;   r:   <module>r     s<  * % !    ! 8 I 6 9 J K F & V V G 5  @+RYY +8>< ><B( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*<)299 <) +<)~E-299 E-PRYY 41 4n */ * *Z  
/7 
/ 
/ 
a
% a

a
H AK A A4 
H$o H
HV ?r;   