o
    }oi"                     @   s   d dl mZ d dlmZmZmZ d dl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 G d	d
 d
ejjZG dd deeZG dd deeZdS )    )abstractmethod)AnyOptionalTupleN)
DictConfig)CtcTopologyCompilerRnntTopologyCompiler)
CtcK2MixinRnntK2Mixin)get_tot_objf_and_finite_maskinvert_permutation)k2c                       s   e Zd ZdZe			ddedededee d	ed
e	f fddZ
dejdejdejdejdedeejf f
ddZdddedejdeejejf fddZdejdejdejdejdeejejf f
ddZ  ZS )MLLossa  
    Maximum Likelihood criterion.
    It implements Connectionist Temporal Classification (CTC) loss,
    but can be extended to support other loss functions (ASG, HMM, RNNT, ...).
    
    Based on https://github.com/k2-fsa/snowfall/blob/master/snowfall/objectives/ctc.py
    
    cfg takes precedence over all optional parameters
    We keep explicit parameter setting to be able to create an instance without the need of a config.
    NdefaultTnum_classesblank	reductioncfg	topo_typetopo_with_self_loopsc                    s\   t    |d ur|d|}|d|}|| _|| _|| _|| _|| _|dk| _d | _	d S )Nr   r   compact)
super__init__getr   r   r   r   r   
pad_fsavecgraph_compilerselfr   r   r   r   r   r   	__class__ Y/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/asr/parts/k2/ml_loss.pyr   5   s   



zMLLoss.__init__	log_probstargetsinput_lengthstarget_lengthsreturnzk2.DenseFsaVecc           	      C   s   |  ||||\}}}}| ||dddf jtjd}| ||}~|j| jjkr2| j|j |dddf jtjd}| j|| || }|||fS )zConverts input tensors to FST graphs:
            log_probs to supervision_graphs (DenseFsaVec)
            targets to supervision_graphs
        Can be overridden.
        Ndtyper   )	_prepare_log_probs_and_targets_maybe_normalize_gradientstotorchlong_prepare_emissions_graphsdevicer   compile)	r   r"   r#   r$   r%   supervisionsemissions_graphsordersupervision_graphsr    r    r!    _prepare_graphs_for_intersectionK   s   "
z'MLLoss._prepare_graphs_for_intersectionr3   r5   r2   c                 C   s   t ||ttjjd }~|jddd}~|t|dddf jtj	d }t
|| j\}}| jdkr<||  |fS | |fS )	zvIntersects emissions_graphs with supervision_graphs and calculates lattice scores.
        Can be overridden.
        
   TF)log_semiringuse_double_scoresNr   r(   none)r   intersect_denser-   finfofloat32maxget_tot_scoresr   r,   r.   r   r   )r   r3   r5   r2   latsnum_tot_scores
tot_scores
valid_maskr    r    r!   _intersect_calc_scorese   s   ""zMLLoss._intersect_calc_scoresc           
      C   s>   | j d usJ | ||||\}}}| |||\}}	||	fS )N)r   r6   rD   )
r   r"   r#   r$   r%   r3   r5   r2   scoresmaskr    r    r!   forwardt   s   
zMLLoss.forwardNr   T)__name__
__module____qualname____doc__r   intstrr   r   boolr   r-   Tensorr   r   r6   rD   rG   __classcell__r    r    r   r!   r   )   sd    

r   c                       sF   e Zd ZdZ			ddedededee d	ed
ef fddZ	  Z
S )CtcLossa  Regular CTC loss with custom topologies.
    Available topologies:
        -   `default`, with or without self-loops
        -   `compact`, with or without self-loops
        -   `shared_blank`, with or without self-loops
        -   `minimal`, without self-loops
    cfg takes precedence over all optional parameters
    We keep explicit parameter setting to be able to create an instance without the need of a config.
    Nr   Tr   r   r   r   r   r   c                    s4   t  j||||||d t| j| j| j| j| _d S )Nr   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   r    r!   r      s   	
zCtcLoss.__init__rH   )rI   rJ   rK   rL   rM   rN   r   r   rO   r   rQ   r    r    r   r!   rR      s$    rR   c                       s   e Zd ZdZ					ddeded	ed
ee dedededef fddZ	de
jde
jde
jde
jdee
je
jf f
 fddZ  ZS )RnntLossa  RNNT loss with the `minimal` topology.
    If predictor_window_size is not provided, this loss works as regular RNNT.
    With predictor_window_size provided, it applies uniform pruning when compiling Emission FSAs
    to reduce memory and compute consumption.
    cfg takes precedence over all optional parameters
    We keep explicit parameter setting to be able to create an instance without the need of a config.
    NminimalTr      r   r   r   r   r   r   predictor_window_sizepredictor_step_sizec	           	         s   t  j||||||d |d ur"|d|}|d|}|d|}|dkr*td|| _|| _t| j| j| j	| j
| jd| _d S )NrS   r   rW   rX   rU   z4Only topo_type=`minimal` is supported at the moment.)max_adapter_length)r   r   r   NotImplementedErrorrW   rX   r   r   r   r   r   r   )	r   r   r   r   r   r   r   rW   rX   r   r    r!   r      s.   zRnntLoss.__init__r"   r#   r$   r%   r&   c                    s6   | j dks|d| j d ksJ t j||||dS )Nr      rV   )r"   r#   r$   r%   )rW   sizer   rG   )r   r"   r#   r$   r%   r   r    r!   rG      s   "zRnntLoss.forward)NrU   Tr   rV   )rI   rJ   rK   rL   rM   rN   r   r   rO   r   r-   rP   r   rG   rQ   r    r    r   r!   rT      sF    	#rT   )abcr   typingr   r   r   r-   	omegaconfr   -nemo.collections.asr.parts.k2.graph_compilersr   r   )nemo.collections.asr.parts.k2.loss_mixinsr	   r
   #nemo.collections.asr.parts.k2.utilsr   r   nemo.core.utils.k2_guardr   nnModuler   rR   rT   r    r    r    r!   <module>   s   [!