o
    }oi                      @   s  g d Z ddlZddlZddlmZmZmZmZmZ ddl	Z
ddlZddlm  mZ ddlmZ ddlmZ ddlmZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZ ddlm Z  ddl!m"Z" d4dee#e$f dee% dej&fddZ'dee# de$fddZ(dedeee#e)f  fddZ*			d5dee# dee# de$dee$e#f de%de$fd d!Z+dee# dee# de$fd"d#Z,d6d$d%Z-d&d' Z.d(d) Z/d7d*e$d+e%d,e%defd-d.Z0d/ed0ed1ee$ejf fd2d3Z1dS )8)torch_dtype_from_precisionlist2strtensor2listplot_confusion_matrixget_classification_reportload_state_dict_helper    N)CallableDictListOptionalUnion)Trainer)pyplot)
DictConfig)classification_reportconfusion_matrix)Tensor)ApproxGELUActivationerf_gelu)openai_gelu)squared_relu)logging	precisionmegatron_amp_O2returnc                 C   sP   |dur|du rt jS | dv rt jS | dv rt jS | dv r t jS td|  d)zMMapping from PTL precision types to corresponding PyTorch parameter datatype.NF)bf16z
bf16-mixed)   16z16-mixed)    32z32-truez"Could not parse the precision of `z` to a valid torch.dtype)torchfloat32bfloat16float16
ValueError)r   r    r%   Z/home/ubuntu/.local/lib/python3.10/site-packages/nemo/collections/nlp/parts/utils_funcs.pyr   +   s   r   lc                 C   s   d dd | D S )zConverts list to a string c                 S   s   g | ]}t |qS r%   str).0xr%   r%   r&   
<listcomp><       zlist2str.<locals>.<listcomp>)join)r'   r%   r%   r&   r   :   s   r   tensorc                 C   s   |     S )zConverts tensor to a list)detachcputolist)r0   r%   r%   r&   r   ?   s   r   F labelspreds
graph_fold	label_ids	normalizeprefixc                    s  du rt | || dS t| t|B fdd D fddD   fddt D }d}t| |}|r`|jdd	ddtjf }	t	|	d
kd|	}	|
d|	 }d| }t }
|
d}||}|tdt| |tdt| |jdg| dd |dg|  |d |d tj|dd |
| ||  }tj||d td }t| t !d|  dS )aQ  
    Plot confusion matrix.
    Args:
      labels: ground truth labels
      preds: model predictions
      graph_fold: path to a folder to store confusion matrix plot
      label_ids: str label to id map, for example: {'O': 0, 'LOC': 1}
      normalize: whether to normalize confusion matrix
      prefix: prefix for the plot name
    Nc                    s"   i | ]\}}|v r| | qS r%   r%   r+   kv)r8   used_labelsr%   r&   
<dictcomp>\   s   " z)plot_confusion_matrix.<locals>.<dictcomp>c                    s   i | ]} | |qS r%   r%   )r+   r<   )r8   r%   r&   r?   ^   s    c                    s   g | ]} | qS r%   r%   )r+   id)ids_to_labelsr%   r&   r-   _   r.   z)plot_confusion_matrix.<locals>.<listcomp>Confusion_matrix   )axisr   floatNormalized_o   r4   Z   )rotationTrue	PredictedTexist_ok_%Y%m%d-%H%M%SzConfusion matrix saved to )"_plot_confusion_matrixsetitemssortedvaluesr   sumnpnewaxiswhereastypepltfigureadd_subplotmatshow
set_xticksarangelen
set_yticksset_xticklabelsset_yticklabels
set_ylabel
set_xlabelosmakedirscolorbarstrippathr/   timestrftimesavefigr   info)r5   r6   r7   r8   r9   r:   classestitlecmsumsfigaxcaxfig_namer%   )rA   r8   r>   r&   r   D   s8   






r   c                 C   s   t | |}td|  t }|d}||}td || t	d t
d tj|dd ttj|td d	S )
z
    Plot confusion matrix
    Args:
        labels: ground truth labels
        preds: model predictions
        graph_fold: path to a folder to store confusion matrix plot
    zConfusion matrix:
rG   z"Confusion matrix of the classifierrL   rK   TrM   rP   N)r   r   ro   r[   r\   r]   r^   rq   ri   xlabelylabelrg   rh   rn   rk   r/   rl   rm   )r5   r6   r7   rr   rt   ru   rv   r%   r%   r&   rQ   ~   s   






rQ   c                    sD   t | t |B   fddt| dd dD }t| ||d|dS )z'
    Returns classification report
    c                    s,   g | ]\}}| v r|d  t | d qS )z (label id: )r)   r;   r>   r%   r&   r-      s
    z-get_classification_report.<locals>.<listcomp>c                 S   s   | d S NrC   r%   )itemr%   r%   r&   <lambda>   s    z+get_classification_report.<locals>.<lambda>)key   )target_namesdigitsoutput_dict)rR   rT   rS   r   )r5   r6   r8   r   labels_namesr%   r{   r&   r      s
   
r   c                   C   s   t j t j d kS r|   )r    distributedget_rankget_world_sizer%   r%   r%   r&   is_last_rank   s   r   c                   C   s   t j d S r|   )r    r   r   r%   r%   r%   r&   get_last_rank   s   r   
activationr   	onnx_safec                 C   s   g d}| |vrt d|  d| d|rt}|S | dv r"tj}|S |r(t}|S | dv r1tj}|S | dv r:tj}|S | dkrBt}|S | d	krHt}|S )
a  Converts an activation function represented as a string to a function.

    Args:
        activation (str): string representation of an activation function, typically gotten from the model config.
        openai_gelu (bool): whether to use the OpenAI GELU implementation. Used with HF compatibility.
        onnx_safe (bool): whether to use the ONNX-compatible implementation of GELU.

    Returns:
        Callable: the activation function.
    )	gelugegluregluswiglusquared-relu
fast-geglufast-swiglu
fast-regluapprox-geluzUnsupported activation z. Supported activations: r(   )r   r   r   )r   r   )r   r   r   r   )	r$   openai_gelu_funcFr   r   relusilur   r   )r   r   r   supported_activationsactivation_funcr%   r%   r&   activation_to_func   s0   	r   cfgtrainer
state_dictc                 C   sj   | ||}|j |dd\}}|r%dd |D }|r%td td| |r3td td| |S )	zILoad state_dict for converted community, for example, HuggingFace models.F)strictc                 S   s   g | ]	}| d s|qS )_extra_state)endswith)r+   r   r%   r%   r&   r-      s    z*load_state_dict_helper.<locals>.<listcomp>zOMissing keys were detected during the load, something has gone wrong. Aborting.zMissing keys: 
z@Unexpected keys were detected which should not happen. Aborting.zUnexpected keys: 
)load_state_dictr   criticalRuntimeError)clsr   r   r   modelmissing_keysunexpected_keysmissing_keys_non_extrar%   r%   r&   r      s   


r   )N)NFr4   )F)FF)2__all__rg   rl   typingr   r	   r
   r   r   numpyrW   r    torch.nn.functionalnn
functionalr   !lightning.pytorch.trainer.trainerr   
matplotlibr   r[   omegaconf.dictconfigr   sklearn.metricsr   r   r   2nemo.collections.nlp.modules.common.megatron.utilsr   r   r   r   r   
nemo.utilsr   intr*   booldtyper   r   rE   r   r   rQ   r   r   r   r   r   r%   r%   r%   r&   <module>   sR   	&	

:
$0