o
    }oi$                     @   sN   d dl mZ d dlmZmZ d dlmZmZmZm	Z	 dgZ
G dd deZdS )    )nn)Loss	typecheck)ChannelType
LogitsTypeLossType
NeuralTypeSpanningLossc                       sF   e Zd ZdZedd Zedd Z fddZe dd	 Z	  Z
S )
r	   zN
    implements start and end loss of a span e.g. for Question Answering.
    c                 C   s,   t dt t tdt t tdt dS )z3Returns definitions of module input ports.
        )BTDr
   )logitsstart_positionsend_positions)r   r   tupler   self r   `/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/common/losses/spanning_loss.pyinput_types   s   
zSpanningLoss.input_typesc                 C   s$   t t dt dt t dt dS )z4Returns definitions of module output ports.
        )elements_type)r
   r   )lossstart_logits
end_logits)r   r   r   r   r   r   r   output_types&   s   


zSpanningLoss.output_typesc                    s   t    d S )N)super__init__r   	__class__r   r   r   0   s   zSpanningLoss.__init__c                 C   s   |j ddd\}}|d}|d}t| dkr |d}t| dkr-|d}|d}|d| |d| tj|d}|||}|||}	||	 d }
|
||fS )a0  
        Args:
            logits: Output of question answering head, which is a token classfier.
            start_positions: Ground truth start positions of the answer w.r.t.
                input sequence. If question is unanswerable, this will be
                pointing to start token, e.g. [CLS], of the input sequence.
            end_positions: Ground truth end positions of the answer w.r.t.
                input sequence. If question is unanswerable, this will be
                pointing to start token, e.g. [CLS], of the input sequence.
           )dimr   )ignore_index   )splitsqueezelensizeclamp_r   CrossEntropyLoss)r   r   r   r   r   r   ignored_indexloss_fct
start_lossend_loss
total_lossr   r   r   forward3   s   







zSpanningLoss.forward)__name__
__module____qualname____doc__propertyr   r   r   r   r/   __classcell__r   r   r   r   r	      s    
	
	N)torchr   nemo.core.classesr   r   nemo.core.neural_typesr   r   r   r   __all__r	   r   r   r   r   <module>   s
   