a
    –¥»aÂ3  ã                   @   s4   d dl Zd dlmZmZmZmZ G dd„ deƒZdS )é    N)ÚbrewÚcoreÚmodel_helperÚ	recurrentc                   @   sd   e Zd Zddd„Zddd„Zddd„Zdd	„ Zdd
d„Zdd„ Zdd„ Z	e
dd„ ƒZe
dd„ ƒZdS )ÚCRFWithLossNc                 C   s\   || _ || _|d | _|sB| j jjg t d¡g| j| jgddd�}|| _| j j 	| j¡ d S )Né   Zcrf_transitionsg      ð¿g      ð?)ÚshapeÚminÚmax)
ÚmodelÚnum_classesÚnum_classes_paddedÚparam_init_netZUniformFillr   ÚScopedBlobReferenceÚtransitionsÚparamsÚappend)Úselfr   r   Ztransitions_blob© r   úK/home/yuhw/wc/pochoir/venv/lib/python3.9/site-packages/caffe2/python/crf.pyÚ__init__   s    


ûzCRFWithLoss.__init__c                 C   s4  | j j | jt d¡¡}|  ||| j¡}t 	|| j j
| j j| j¡}t || j j
| j j| j¡}|  |||¡}| j j ||gt d¡¡}| j j
jg dgdd�}| j jj||gt d¡dd�}	| j jj|gddd	d
�\}
}| j jj|
gt d¡dgd�}
| j j |t d¡¡}|  |
|	|¡}| j j ||gt d¡¡}|S )NÚtransitions_snapshotZ
path_totalé   r   ©r   ÚvalueZrnn_initialT©Zdense_gradientr   )Úpadding_widthÚend_padding_widthÚoutputsZrnn_input_data©ÚdimsÚtransitions_copyÚcrf_loss)r   ÚnetZCopyr   r   r   Ú_gather_entries_sumr   r   Úpad_predictionsr   Ú
pad_labelsÚ_path_binary_scoresÚAddÚConstantFillÚGatherÚRemovePaddingÚ
ExpandDimsÚ_crf_forwardÚSub)r   ÚpredictionsÚlabelsÚseq_lengthsr   Zpath_unary_scoreZpath_binary_scoreZpath_total_scoreÚ
zero_indexÚinitial_stateZ
input_dataÚ_r!   Zall_paths_scoresZlossr   r   r   r"       sR    ÿÿÿÿÿþý
ÿ
ÿ
ÿÿÿzCRFWithLoss.crf_lossc                 C   s¤   | j jj|gdddd�\}}| j jj|gdddd�\}}| j jj|g| jd�}| j j ||g¡}| j j ||g¡}| j j |g¡}	| j jj|	|gdd�}
| j  	|
¡S )Nr   r   r   )r   r   r   ©r   Tr   )
r   r#   r+   r)   r   ZMulr(   ÚFlattenToVecr*   ÚReduceFrontSum)r   r0   r   r1   Z
column_idsr4   Zrow_idsZnum_columns_blobZflattened_idsZflattened_transitionsÚentriesr   r   r   r'   T   s     
ÿ

ÿ
ÿÿzCRFWithLoss._path_binary_scoresc           
      C   s~   | j jj|gdd�}| j jjg dg|d�}| j j ||g¡}| j j |¡}| j j |¡}| j j ||g¡}| j j |g¡}	|	S )NÚint64©Útor   r   )	r   r#   ÚCastr   r)   ZOneHotr6   Z
DotProductr7   )
r   Zin_dataÚindicesZ
index_sizeZindex_size_blobZquery_one_hotZflattend_queryZflattend_dataZquery_scoresZ	final_sumr   r   r   r$   i   s    ÿzCRFWithLoss._gather_entries_sumc           	      C   sx   |   |||¡}| jjj|gd| jfd�\}}| jjjg d| jgtjj	d�}| jj 
||g¡}| jjj|ddd�\}}|S )Nr   )r   r   r   ©r   r   Údtyper   )Úbuild_crf_netr   r#   ÚReshaper   r   r)   r   ÚDataTypeÚINT32ÚSortedSegmentRangeLogSumExp)	r   Ú
input_blobr3   r!   r1   Úout_lastr4   Úzero_segment_idZaccum_scorer   r   r   r-   u   s    ÿ
ÿÿzCRFWithLoss._crf_forwardc              	      s€  d‰ ‡ fdd„}t jd| jd�}|j t d¡t d¡|¡\}}}|jjg |dƒgd	| j	gtj
jd
�}	|j |	¡ tj|||dƒgdd�}
|jj|
|dƒg| j	dd�}|jj||dƒg| j	dd�}|j ||g|dƒg¡}|jj||g|dƒgddd�}|jj||dƒ|dƒg| j	| j	fd�\}}|j ||	g|dƒg¡}|j |¡ |}tj| jj|j||fg||fg||iˆ dd�\}}|S )a©  
            Adds the crf_net recurrent operator to the model.

            model: model_helper.ModelHelper object new operators would be added
            to

            input_blob: the input sequence in a format T x N x D
            where T is sequence size, N - batch size and D - input dimension
            ##Only supports batch-size 1##

            seq_lengths: blob containing sequence lengths (unused)
            Zcrf_netc                    s   d  tˆ ƒt| ƒ¡S )Ú z{}/{})ÚformatÚstr)Úname©Úscoper   r   Ús˜   s    z$CRFWithLoss.build_crf_net.<locals>.sZcrf_step)rK   Zparam_modelÚinput_tÚcell_t_prevrG   r   r>   Úprev_transpose)r   r   r   )ZaxesÚ
prev_tiledr   )ZtilesÚaxisÚinput_t_tiledr   Úinput_with_prevZprev_with_transitions)Ú	broadcastZuse_grad_hackÚall_with_transitions_reshapedZall_with_transitions_orig)r   Úcell_t)r   )r#   Zcell_netÚinputsZinitial_cell_inputsÚlinksrM   Zoutputs_with_grads)r   ZModelHelperr   r#   ZAddExternalInputsr   r   r   r)   r   rB   rC   ZAddExternalOutputr   Z	transposeZTiler(   rA   rD   ZAddExternalOutputsr   Zrecurrent_net)r   rE   r3   r   rN   Z
step_modelrO   rP   r4   rG   rQ   rR   rT   rU   Zall_with_transitionsrW   rX   Zcell_input_blobZout_allrF   r   rL   r   r@   ˆ   sl    ý
û	ÿÿÿÿü
ý
ÿù
	zCRFWithLoss.build_crf_netc                 C   sF   dd„ }t  || jj| jj| j¡}| jj |¡|| jgt 	d¡ƒ}|S )Nc                 S   s’  | d j }| d j }| d j }| d j}|d  |¡ t |¡}tj|tjd�}|d |d< td|d ƒD ]D}t ||d  d¡| }|| t |d¡ ||< t 	|d¡||< qjt 	|d ¡g}	t
|dd … ƒD ]}
|	 |
|	d  ¡ qÐ|	 ¡  t |¡}g }t|ƒD ]T\}}|| ||< t 	|¡}| |¡ || ||	|   ||	| < ||< |||< �q|dd…dd…f }|d  |j¡ ||d j d< d S )Nr   r   )r?   éÿÿÿÿéþÿÿÿ.)Údatar   ZreshapeÚnpÚzerosÚint32ÚrangeZexpand_dimsr
   ZargmaxÚreversedr   ÚreverseÚ	enumerate)rY   r   r/   r   Zpredictions_shapeZtrellisZbackpointersÚtÚvZviterbiZbpZnew_predictionsZ	old_bestsÚiZw_predictionsZold_bestZorig_predictionsr   r   r   Úcrf_update_predictions_opÙ   s:    








þzACRFWithLoss.update_predictions.<locals>.crf_update_predictions_opZpost_crf_classes)
r   r%   r   r   r#   r   ÚPythonr   r   r   )r   Úclassesrh   Zpadded_classesZnew_classesr   r   r   Úupdate_predictionsØ   s    +ÿþzCRFWithLoss.update_predictionsc           
      C   s^   |}|d }|j g dg|d�}|j g dg|d�}|j| gdd�} |j|| |gddd�\}}	|S )Nr   r   r9   r:   r   r   )rS   r   )r)   r<   ÚConcat)
r0   Úinit_netr#   r   Zbos_iZeos_iZbos_i_bZeos_i_bZpadded_labelsr4   r   r   r   r&     s    zCRFWithLoss.pad_labelsc                 C   s  d}t  |g| d|g g¡ t j¡}t  |g| |dg g¡ t j¡}|jg dd|d g|d�}|jg dd|d g|d�}|jg dgdd�}| | | g¡|g¡}|j|d	d
�}| 	|¡}	|j|	g|d�}
|j
|
dgd�}
|j| |
|
gddd�\}}|j|||gddd�\}}|S )Ng     @�Àr   Úb_scoresr   r   )r   ÚvaluesÚe_scoresr   r`   r:   r5   r   )r   rS   )r^   ÚarrayZastypeÚfloat32ZGivenTensorFillr)   r*   ZShaper<   ZLengthsRangeFillr,   rl   )r/   rm   r#   r   Z	low_scorern   rp   r2   ÚlengthZt_rangeÚpaddingZpadded_predictionsr4   Zpadded_predictions_concatr   r   r   r%     s4    ÿÿÿÿ
ÿ
ÿ
zCRFWithLoss.pad_predictions)N)N)N)N)Ú__name__Ú
__module__Ú__qualname__r   r"   r'   r$   r-   r@   rk   Ústaticmethodr&   r%   r   r   r   r   r      s   

4
 ÿ
P5
	r   )	Únumpyr^   Zcaffe2.pythonr   r   r   r   Úobjectr   r   r   r   r   Ú<module>   s   
