a
    áñhß:  ã                   @   s¾   d dl Z d dlmZ d dl mZmZ d dlZd dlmZ	 ddl
mZ ddlmZ d dlmZmZmZmZ dd	lmZ e jjd
d„ ƒZG dd„ dejƒZdd„ Zdd„ ZG dd„ de jjƒZdS )é    N)Ú
functional)ÚnnÚTensor)Úboxesé   )Ú_utils)Ú	ImageList)ÚListÚOptionalÚDictÚTuple)ÚAnchorGeneratorc                 C   sL   ddl m} | | ¡d  d¡}t t tj|g|jd�|fd¡¡}||fS )Nr   )Ú	operatorsr   ©Údtype)	Z
torch.onnxr   Zshape_as_tensorZ	unsqueezeÚtorchÚminÚcatZtensorr   )ÚobZorig_pre_nms_top_nr   Únum_anchorsÚpre_nms_top_n© r   ú`/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/models/detection/rpn.pyÚ'_onnx_get_num_anchors_and_pre_nms_top_n   s    ÿþr   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )ÚRPNHeadzÙ
    Adds a simple RPN Head with classification and regression heads

    Arguments:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
    c                    sˆ   t t| ƒ ¡  tj||dddd�| _tj||ddd�| _tj||d ddd�| _|  ¡ D ]*}t	jj
j|jdd� t	jj
 |jd¡ qXd S )	Né   r   )Úkernel_sizeÚstrideÚpadding)r   r   é   g{®Gáz„?)Zstdr   )Úsuperr   Ú__init__r   ZConv2dÚconvÚ
cls_logitsÚ	bbox_predÚchildrenr   ÚinitZnormal_ZweightZ	constant_Zbias)ÚselfZin_channelsr   Úlayer©Ú	__class__r   r   r!   '   s    
ÿÿzRPNHead.__init__c                 C   sJ   g }g }|D ]4}t  |  |¡¡}| |  |¡¡ | |  |¡¡ q||fS )N)ÚFZrelur"   Úappendr#   r$   )r'   ÚxZlogitsZbbox_regÚfeatureÚtr   r   r   Úforward5   s    zRPNHead.forward)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r!   r0   Ú__classcell__r   r   r)   r   r      s   r   c                 C   s6   |   |d|||¡} |  ddddd¡} |  |d|¡} | S )Néÿÿÿÿr   r   r   r   é   )ÚviewZpermuteÚreshape)r(   ÚNÚAÚCÚHÚWr   r   r   Úpermute_and_flatten@   s    r?   c                 C   s°   g }g }t | |ƒD ]h\}}|j\}}}}	|jd }
|
d }|| }t||||||	ƒ}| |¡ t|||d||	ƒ}| |¡ qtj|dd� dd¡} tj|dd� dd¡}| |fS )Nr   r   ©Zdimr   éþÿÿÿr6   )ÚzipÚshaper?   r,   r   r   Úflattenr9   )Zbox_clsZbox_regressionZbox_cls_flattenedZbox_regression_flattenedZbox_cls_per_levelZbox_regression_per_levelr:   ZAxCr=   r>   ZAx4r;   r<   r   r   r   Úconcat_box_prediction_layersH   s(    ÿ
ÿ
ÿrE   c                       s€   e Zd ZdZejejejee	e
f ee	e
f dœZ‡ fdd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Zdd„ Zddd„Z‡  ZS )ÚRegionProposalNetworkac  
    Implements Region Proposal Network (RPN).

    Arguments:
        anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
            maps.
        head (nn.Module): module that computes the objectness and regression deltas
        fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
            considered as positive during training of the RPN.
        bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
            considered as negative during training of the RPN.
        batch_size_per_image (int): number of anchors that are sampled during training of the RPN
            for computing the loss
        positive_fraction (float): proportion of positive anchors in a mini-batch during training
            of the RPN
        pre_nms_top_n (Dict[int]): number of proposals to keep before applying NMS. It should
            contain two fields: training and testing, to allow for different values depending
            on training or evaluation
        post_nms_top_n (Dict[int]): number of proposals to keep after applying NMS. It should
            contain two fields: training and testing, to allow for different values depending
            on training or evaluation
        nms_thresh (float): NMS threshold used for postprocessing the RPN proposals

    )Ú	box_coderÚproposal_matcherÚfg_bg_samplerr   Úpost_nms_top_nc
           
         sl   t t| ƒ ¡  || _|| _tjdd�| _tj	| _
tj||dd�| _t ||¡| _|| _|| _|	| _d| _d S )N)ç      ð?rK   rK   rK   )ÚweightsT)Zallow_low_quality_matchesgü©ñÒMbP?)r    rF   r!   Úanchor_generatorÚheadÚ	det_utilsÚBoxCoderrG   Úbox_opsZbox_iouÚbox_similarityÚMatcherrH   ÚBalancedPositiveNegativeSamplerrI   Ú_pre_nms_top_nÚ_post_nms_top_nÚ
nms_threshÚmin_size)
r'   rM   rN   Zfg_iou_threshZbg_iou_threshZbatch_size_per_imageZpositive_fractionr   rJ   rW   r)   r   r   r!   ‰   s"    ýÿzRegionProposalNetwork.__init__c                 C   s   | j r| jd S | jd S ©NÚtrainingZtesting)rZ   rU   ©r'   r   r   r   r   ¨   s    
z#RegionProposalNetwork.pre_nms_top_nc                 C   s   | j r| jd S | jd S rY   )rZ   rV   r[   r   r   r   rJ   ­   s    
z$RegionProposalNetwork.post_nms_top_nc                 C   sæ   g }g }t ||ƒD ]Ê\}}|d }| ¡ dkrd|j}tj|jtj|d�}	tj|jd ftj|d�}
nd|  ||¡}|  |¡}||j	dd� }	|dk}
|
j
tjd�}
|| jjk}d|
|< || jjk}d|
|< | |
¡ | |	¡ q||fS )Nr   r   ©r   Údevice)r   r   g        g      ð¿)rB   Únumelr]   r   ÚzerosrC   Úfloat32rR   rH   ÚclampÚtoZBELOW_LOW_THRESHOLDZBETWEEN_THRESHOLDSr,   )r'   ÚanchorsÚtargetsÚlabelsÚmatched_gt_boxesZanchors_per_imageZtargets_per_imageZgt_boxesr]   Zmatched_gt_boxes_per_imageZlabels_per_imageZmatch_quality_matrixZmatched_idxsZ
bg_indicesZinds_to_discardr   r   r   Úassign_targets_to_anchors²   s(    

z/RegionProposalNetwork.assign_targets_to_anchorsc           
      C   s„   g }d}|  |d¡D ]`}t ¡ r4t||  ¡ ƒ\}}n|jd }t|  ¡ |ƒ}|j|dd�\}}	| |	| ¡ ||7 }qt	j
|dd�S )Nr   r   r@   )ÚsplitÚtorchvisionZ_is_tracingr   r   rC   r   Ztopkr,   r   r   )
r'   Ú
objectnessÚnum_anchors_per_levelÚrÚoffsetr   r   r   Ú_Ú	top_n_idxr   r   r   Ú_get_top_n_idxÖ   s    

z$RegionProposalNetwork._get_top_n_idxc                    sP  |j d }|j‰ | ¡ }| |d¡}‡ fdd„t|ƒD ƒ}t |d¡}| dd¡ |¡}|  ||¡}tj	|ˆ d�}|d d …d f }	||	|f }||	|f }||	|f }g }
g }t
||||ƒD ]Š\}}}}t ||¡}t || j¡}|| || ||   }}}t |||| j¡}|d |  ¡ … }|| ||  }}|
 |¡ | |¡ q¼|
|fS )Nr   r6   c                    s&   g | ]\}}t j|f|t jˆ d �‘qS )r\   )r   ÚfullÚint64)Ú.0ÚidxÚn©r]   r   r   Ú
<listcomp>í   s   ÿz:RegionProposalNetwork.filter_proposals.<locals>.<listcomp>r   rv   )rC   r]   Údetachr9   Ú	enumerater   r   Z	expand_asrp   ZarangerB   rQ   Zclip_boxes_to_imageZremove_small_boxesrX   Zbatched_nmsrW   rJ   r,   )r'   Ú	proposalsrj   Zimage_shapesrk   Ú
num_imagesÚlevelsro   Zimage_rangeZ	batch_idxZfinal_boxesZfinal_scoresr   ÚscoresZlvlZ	img_shapeZkeepr   rv   r   Úfilter_proposalså   s6    

þ
z&RegionProposalNetwork.filter_proposalsc           
      C   s²   |   |¡\}}t tj|dd�¡d }t tj|dd�¡d }tj||gdd�}| ¡ }tj|dd�}tj|dd�}tj|| || ddd�| ¡  }t 	|| || ¡}	|	|fS )a  
        Arguments:
            objectness (Tensor)
            pred_bbox_deltas (Tensor)
            labels (List[Tensor])
            regression_targets (List[Tensor])

        Returns:
            objectness_loss (Tensor)
            box_loss (Tensor)
        r   r@   gÇqÇq¼?F)ÚbetaZsize_average)
rI   r   Úwherer   rD   rO   Zsmooth_l1_lossr^   r+   Z binary_cross_entropy_with_logits)
r'   rj   Úpred_bbox_deltasre   Úregression_targetsZsampled_pos_indsZsampled_neg_indsZsampled_indsZbox_lossZobjectness_lossr   r   r   Úcompute_loss  s&    üûÿz"RegionProposalNetwork.compute_lossNc                 C   sè   t | ¡ ƒ}|  |¡\}}|  ||¡}t|ƒ}dd„ |D ƒ}dd„ |D ƒ}	t||ƒ\}}| j | ¡ |¡}
|
 	|dd¡}
|  
|
||j|	¡\}}i }| jrà|dus¤J ‚|  ||¡\}}| j ||¡}|  ||||¡\}}||dœ}||fS )a:  
        Arguments:
            images (ImageList): images for which we want to compute the predictions
            features (OrderedDict[Tensor]): features computed from the images that are
                used for computing the predictions. Each tensor in the list
                correspond to different feature levels
            targets (List[Dict[Tensor]]): ground-truth boxes present in the image (optional).
                If provided, each element in the dict should contain a field `boxes`,
                with the locations of the ground-truth boxes.

        Returns:
            boxes (List[Tensor]): the predicted boxes from the RPN, one Tensor per
                image.
            losses (Dict[Tensor]): the losses for the model during training. During
                testing, it is an empty dict.
        c                 S   s   g | ]}|d  j ‘qS )r   )rC   )rs   Úor   r   r   rw   O  ó    z1RegionProposalNetwork.forward.<locals>.<listcomp>c                 S   s$   g | ]}|d  |d  |d  ‘qS )r   r   r7   r   )rs   Úsr   r   r   rw   P  r…   r6   r   N)Úloss_objectnessÚloss_rpn_box_reg)ÚlistÚvaluesrN   rM   ÚlenrE   rG   Údecoderx   r8   r~   Zimage_sizesrZ   rg   Úencoderƒ   )r'   ZimagesÚfeaturesrd   rj   r�   rc   r{   Z#num_anchors_per_level_shape_tensorsrk   rz   r   r}   Zlossesre   rf   r‚   r‡   rˆ   r   r   r   r0   3  s.    ÿÿþzRegionProposalNetwork.forward)N)r1   r2   r3   r4   rO   rP   rS   rT   r   ÚstrÚintÚ__annotations__r!   r   rJ   rg   rp   r~   rƒ   r0   r5   r   r   r)   r   rF   h   s    

û$() ýrF   )r   Ztorch.nnr   r+   r   r   ri   Ztorchvision.opsr   rQ   Ú r   rO   Z
image_listr   Ztorch.jit.annotationsr	   r
   r   r   Zanchor_utilsr   ZjitZunusedr   ÚModuler   r?   rE   rF   r   r   r   r   Ú<module>   s   
" 