a
    áñhëk  ã                   @   s*  d dl Z d dlmZ d dlZd dlZd dlmZ d dlmZ d dlm	Z	m
Z
mZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddgZe
e edœdd„ZG dd„ dejƒZ G dd„ dejƒZ!G dd„ dejƒZ"G dd„ dejƒZ#ddiZ$d"d!d„Z%dS )#é    N)ÚOrderedDict)ÚTensor)ÚDictÚListÚTupleé   )Úload_state_dict_from_urlé   )Ú_utils)ÚAnchorGenerator)ÚGeneralizedRCNNTransform)Úresnet_fpn_backboneé   )ÚLastLevelP6P7)Úsigmoid_focal_loss)ÚboxesÚ	RetinaNetÚretinanet_resnet50_fpn)ÚxÚreturnc                 C   s&   | d }| dd … D ]}|| }q|S )Nr   r	   © )r   ÚresÚir   r   úf/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/models/detection/retinanet.pyÚ_sum   s    
r   c                       s0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )ÚRetinaNetHeada  
    A regression and classification head for use in RetinaNet.

    Arguments:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
        num_classes (int): number of classes to be predicted
    c                    s(   t ƒ  ¡  t|||ƒ| _t||ƒ| _d S ©N)ÚsuperÚ__init__ÚRetinaNetClassificationHeadÚclassification_headÚRetinaNetRegressionHeadÚregression_head)ÚselfÚin_channelsÚnum_anchorsÚnum_classes©Ú	__class__r   r   r   +   s    
zRetinaNetHead.__init__c                 C   s$   | j  |||¡| j ||||¡dœS )N)ZclassificationÚbbox_regression)r    Úcompute_lossr"   )r#   ÚtargetsÚhead_outputsÚanchorsÚmatched_idxsr   r   r   r*   0   s    þzRetinaNetHead.compute_lossc                 C   s   |   |¡|  |¡dœS )N)Ú
cls_logitsr)   )r    r"   )r#   r   r   r   r   Úforward7   s    þzRetinaNetHead.forward©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r*   r0   Ú__classcell__r   r   r'   r   r   !   s   	r   c                       s2   e Zd ZdZd	‡ fdd„	Zdd„ Zdd„ Z‡  ZS )
r   a  
    A classification head for use in RetinaNet.

    Arguments:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
        num_classes (int): number of classes to be predicted
    ç{®Gáz„?c              
      s   t ƒ  ¡  g }tdƒD ],}| tj||dddd�¡ | t ¡ ¡ qtj|Ž | _| j 	¡ D ]6}t
|tjƒrZtjjj|jdd� tjj |jd¡ qZtj||| dddd�| _tjjj| jjdd� tjj | jjt d| | ¡ ¡ || _|| _tjj| _d S )Né   r   r	   ©Zkernel_sizeZstrideÚpaddingr7   ©Zstdr   )r   r   ÚrangeÚappendÚnnÚConv2dÚReLUÚ
SequentialÚconvÚchildrenÚ
isinstanceÚtorchÚinitÚnormal_ÚweightZ	constant_Úbiasr/   ÚmathÚlogr&   r%   Ú	det_utilsÚMatcherÚBETWEEN_THRESHOLDS)r#   r$   r%   r&   Zprior_probabilityrB   Ú_Úlayerr'   r   r   r   I   s     
$z$RetinaNetClassificationHead.__init__c                 C   s–   g }|d }t |||ƒD ]l\}}}|dk}	|	 ¡ }
t |¡}d||	|d ||	  f< || jk}| t|| || dd�td|
ƒ ¡ qt|ƒt	|ƒ S )Nr/   r   ç      ð?ÚlabelsÚsum)Z	reductionr	   )
ÚziprS   rE   Z
zeros_likerN   r=   r   Úmaxr   Úlen)r#   r+   r,   r.   Úlossesr/   Útargets_per_imageZcls_logits_per_imageÚmatched_idxs_per_imageÚforeground_idxs_per_imageÚnum_foregroundZgt_classes_targetZvalid_idxs_per_imager   r   r   r*   c   s*    
ýÿÿ
ýüz(RetinaNetClassificationHead.compute_lossc           	      C   s~   g }|D ]f}|   |¡}|  |¡}|j\}}}}| |d| j||¡}| ddddd¡}| |d| j¡}| |¡ qtj	|dd�S )Néÿÿÿÿr   r   r8   r	   r   ©Zdim)
rB   r/   ÚshapeÚviewr&   ÚpermuteÚreshaper=   rE   Úcat)	r#   r   Zall_cls_logitsÚfeaturesr/   ÚNrO   ÚHÚWr   r   r   r0   †   s    

z#RetinaNetClassificationHead.forward)r7   r1   r   r   r'   r   r   ?   s   	#r   c                       s:   e Zd ZdZdejiZ‡ fdd„Zdd„ Zdd„ Z	‡  Z
S )	r!   zÁ
    A regression head for use in RetinaNet.

    Arguments:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
    Ú	box_coderc              
      sä   t ƒ  ¡  g }tdƒD ],}| tj||dddd�¡ | t ¡ ¡ qtj|Ž | _tj||d dddd�| _	t
jjj| j	jdd� t
jj | j	j¡ | j ¡ D ]4}t|tjƒrœt
jjj|jdd� t
jj |j¡ qœtjdd�| _d S )	Nr8   r   r	   r9   r7   r;   ©rQ   rQ   rQ   rQ   ©Úweights)r   r   r<   r=   r>   r?   r@   rA   rB   Úbbox_regrE   rF   rG   rH   Zzeros_rI   rC   rD   rL   ÚBoxCoderrg   )r#   r$   r%   rB   rO   rP   r'   r   r   r   ¥   s    
z RetinaNetRegressionHead.__init__c                 C   sÄ   g }|d }t ||||ƒD ]’\}}}	}
|d |
jdd� }|
dk}| ¡ }||d d …f }||d d …f }|	|d d …f }	| j ||	¡}| tjjj	||dd�t
d|ƒ ¡ qt|ƒt
dt|ƒƒ S )Nr)   r   r   )ÚminF)Zsize_averager	   )rT   ÚclamprS   rg   Zencode_singler=   rE   r>   Z
functionalZl1_lossrU   r   rV   )r#   r+   r,   r-   r.   rW   r)   rX   Zbbox_regression_per_imageÚanchors_per_imagerY   Zmatched_gt_boxes_per_imagerZ   r[   Ztarget_regressionr   r   r   r*   ¹   s&    ÿýüz$RetinaNetRegressionHead.compute_lossc           	      C   sz   g }|D ]b}|   |¡}|  |¡}|j\}}}}| |dd||¡}| ddddd¡}| |dd¡}| |¡ qtj|dd�S )Nr\   r8   r   r   r	   r   r]   )	rB   rk   r^   r_   r`   ra   r=   rE   rb   )	r#   r   Zall_bbox_regressionrc   r)   rd   rO   re   rf   r   r   r   r0   á   s    

zRetinaNetRegressionHead.forward)r2   r3   r4   r5   rL   rl   Ú__annotations__r   r*   r0   r6   r   r   r'   r   r!   ™   s   ÿ(r!   c                       sZ   e Zd ZdZejejdœZd‡ fd
d„	Ze	j
jdd„ ƒZdd„ Zdd„ Zddd„Z‡  ZS )r   a¼  
    Implements RetinaNet.

    The input to the model is expected to be a list of tensors, each of shape [C, H, W], one for each
    image, and should be in 0-1 range. Different images can have different sizes.

    The behavior of the model changes depending if it is in training or evaluation mode.

    During training, the model expects both the input tensors, as well as a targets (list of dictionary),
    containing:
        - boxes (FloatTensor[N, 4]): the ground-truth boxes in [x1, y1, x2, y2] format, with values
          between 0 and H and 0 and W
        - labels (Int64Tensor[N]): the class label for each ground-truth box

    The model returns a Dict[Tensor] during training, containing the classification and regression
    losses.

    During inference, the model requires only the input tensors, and returns the post-processed
    predictions as a List[Dict[Tensor]], one for each input image. The fields of the Dict are as
    follows:
        - boxes (FloatTensor[N, 4]): the predicted boxes in [x1, y1, x2, y2] format, with values between
          0 and H and 0 and W
        - labels (Int64Tensor[N]): the predicted labels for each image
        - scores (Tensor[N]): the scores for each prediction

    Arguments:
        backbone (nn.Module): the network used to compute the features for the model.
            It should contain an out_channels attribute, which indicates the number of output
            channels that each feature map has (and it should be the same for all feature maps).
            The backbone should return a single Tensor or an OrderedDict[Tensor].
        num_classes (int): number of output classes of the model (excluding the background).
        min_size (int): minimum size of the image to be rescaled before feeding it to the backbone
        max_size (int): maximum size of the image to be rescaled before feeding it to the backbone
        image_mean (Tuple[float, float, float]): mean values used for input normalization.
            They are generally the mean values of the dataset on which the backbone has been trained
            on
        image_std (Tuple[float, float, float]): std values used for input normalization.
            They are generally the std values of the dataset on which the backbone has been trained on
        anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
            maps.
        head (nn.Module): Module run on top of the feature pyramid.
            Defaults to a module containing a classification and regression module.
        score_thresh (float): Score threshold used for postprocessing the detections.
        nms_thresh (float): NMS threshold used for postprocessing the detections.
        detections_per_img (int): Number of best detections to keep after NMS.
        fg_iou_thresh (float): minimum IoU between the anchor and the GT box so that they can be
            considered as positive during training.
        bg_iou_thresh (float): maximum IoU between the anchor and the GT box so that they can be
            considered as negative during training.

    Example:

        >>> import torch
        >>> import torchvision
        >>> from torchvision.models.detection import RetinaNet
        >>> from torchvision.models.detection.anchor_utils import AnchorGenerator
        >>> # load a pre-trained model for classification and return
        >>> # only the features
        >>> backbone = torchvision.models.mobilenet_v2(pretrained=True).features
        >>> # RetinaNet needs to know the number of
        >>> # output channels in a backbone. For mobilenet_v2, it's 1280
        >>> # so we need to add it here
        >>> backbone.out_channels = 1280
        >>>
        >>> # let's make the network generate 5 x 3 anchors per spatial
        >>> # location, with 5 different sizes and 3 different aspect
        >>> # ratios. We have a Tuple[Tuple[int]] because each feature
        >>> # map could potentially have different sizes and
        >>> # aspect ratios
        >>> anchor_generator = AnchorGenerator(
        >>>     sizes=((32, 64, 128, 256, 512),),
        >>>     aspect_ratios=((0.5, 1.0, 2.0),)
        >>> )
        >>>
        >>> # put the pieces together inside a RetinaNet model
        >>> model = RetinaNet(backbone,
        >>>                   num_classes=2,
        >>>                   anchor_generator=anchor_generator)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
    )rg   Úproposal_matcheré   é5  Nçš™™™™™©?ç      à?é,  çš™™™™™Ù?c                    s
  t ƒ  ¡  t|dƒstdƒ‚|| _t|ttd ƒfƒs8J ‚|d u rhtdd„ dD ƒƒ}dt	|ƒ }t||ƒ}|| _
|d u rŒt|j| ¡ d |ƒ}|| _|	d u rªtj||dd	�}	|	| _tjd
d�| _|d u rÎg d¢}|d u rÞg d¢}t||||ƒ| _|
| _|| _|| _d| _d S )NÚout_channelsz†backbone should contain an attribute out_channels specifying the number of output channels (assumed to be the same for all the levels)c                 s   s(   | ] }|t |d  ƒt |d ƒfV  qdS )g‹r�ù¢(ô?g<n=¥þeù?N)Úint)Ú.0r   r   r   r   Ú	<genexpr>c  ó    z%RetinaNet.__init__.<locals>.<genexpr>)é    é@   é€   é   i   ))ru   rQ   g       @r   T)Zallow_low_quality_matchesrh   ri   )g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?)gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?F)r   r   ÚhasattrÚ
ValueErrorÚbackbonerD   r   ÚtypeÚtuplerV   Úanchor_generatorr   rx   Znum_anchors_per_locationÚheadrL   rM   rq   rl   rg   r   Ú	transformÚscore_threshÚ
nms_threshÚdetections_per_imgÚ_has_warned)r#   rƒ   r&   Úmin_sizeÚmax_sizeZ
image_meanZ	image_stdr†   r‡   rq   r‰   rŠ   r‹   Zfg_iou_threshZbg_iou_threshZanchor_sizesZaspect_ratiosr'   r   r   r   L  sD    

ÿÿýzRetinaNet.__init__c                 C   s   | j r
|S |S r   )Útraining)r#   rW   Ú
detectionsr   r   r   Úeager_outputs…  s    zRetinaNet.eager_outputsc                 C   sr   g }t ||ƒD ]P\}}|d  ¡ dkr>| tjdtjd�¡ qt |d |¡}| |  |¡¡ q| j	 
||||¡S )Nr   r   )r   )Zdtype)rT   Znumelr=   rE   ÚemptyÚint32Úbox_opsZbox_iourq   r‡   r*   )r#   r+   r,   r-   r.   ro   rX   Zmatch_quality_matrixr   r   r   r*   �  s    zRetinaNet.compute_lossc              	      s†  |  d¡}|  d¡}|}|j}|jd }t |¡}	tj||d�}
|
 dd¡ |	¡}
tj 	t
tttf  g ¡}tt||	|
||ƒƒD �]þ\‰ \}}}}}| j ||¡}t ||¡}‡ fdd„| ¡ D ƒ}g }g }g }tj 	ttt
t f i ¡}t|ƒD �]*}t |d d …|f | j¡‰|ˆ |ˆ|f |ˆ|f   }}}‡fdd„|D ƒ}tj|d	d
�‰|ˆ |ˆ |ˆ   }}}‡fdd„|D ƒ}t ||| j¡‰ˆd | j… ‰|ˆ |ˆ |ˆ   }}}‡fdd„|D ƒ}| |¡ | |¡ | |¡ |D ]*\}}||v�rg ||< ||  |¡ �qòqò| tj|dd�tj|dd�tj|dd�dœ¡ | ¡ D ]&\}}|d  |tj|dd�i¡ �qXq€|S )Nr/   r)   r\   )Údevicer	   c                    s   g | ]\}}||ˆ  f‘qS r   r   ©rz   ÚkÚv)Úindexr   r   Ú
<listcomp>³  r|   z4RetinaNet.postprocess_detections.<locals>.<listcomp>c                    s   g | ]\}}||ˆ  f‘qS r   r   r–   )Úindsr   r   rš   ¿  r|   r7   )r�   c                    s   g | ]\}}||ˆ  f‘qS r   r   r–   ©Úkeepr   r   rš   Å  r|   c                    s   g | ]\}}||ˆ  f‘qS r   r   r–   rœ   r   r   rš   Î  r|   r   r]   )r   ÚscoresrR   )Úpopr•   r^   rE   ZsigmoidZaranger_   Z	expand_asÚjitÚannotater   r   Ústrr   Ú	enumeraterT   rg   Zdecode_singler”   Zclip_boxes_to_imageÚitemsr<   Úgtr‰   Zremove_small_boxesZnmsrŠ   r‹   r=   rb   Úupdate)r#   r,   r-   Zimage_shapesZclass_logitsZbox_regressionZother_outputsr•   r&   rž   rR   r�   Zbox_regression_per_imageZscores_per_imageZlabels_per_imagero   Zimage_shapeZboxes_per_imageZother_outputs_per_imageZimage_boxesZimage_scoresZimage_labelsZimage_other_outputsZclass_indexZboxes_per_classZscores_per_classZlabels_per_classZother_outputs_per_classr—   r˜   r   )r™   r›   r�   r   Úpostprocess_detectionsš  s^    



ÿÿÿÿ



ý"z RetinaNet.postprocess_detectionsc                 C   sd  | j r|du rtdƒ‚| j r†|dus(J ‚|D ]X}|d }t|tjƒrrt|jƒdks`|jd dkr„td |j¡ƒ‚q,td t|ƒ¡ƒ‚q,tj	 
ttttf  g ¡}|D ]8}|jd	d… }t|ƒdksÆJ ‚| |d
 |d f¡ q¤|  ||¡\}}|du�r|t|ƒD ]z\}}|d }|dd…dd…f |dd…dd…f k}	|	 ¡ �r t |	jdd�¡d
 d
 }
||
  ¡ }td ||¡ƒ‚�q |  |j¡}t|tjƒ�r¤td|fgƒ}t| ¡ ƒ}|  |¡}|  ||¡}i }tj	 
ttttf  g ¡}| j �r
|du�súJ ‚|  |||¡}n"|  |||j¡}| j  ||j|¡}tj	 !¡ �rX| j"�sPt# $d¡ d| _"||fS |  %||¡S )a  
        Arguments:
            images (list[Tensor]): images to be processed
            targets (list[Dict[Tensor]]): ground-truth boxes present in the image (optional)

        Returns:
            result (list[BoxList] or dict[Tensor]): the output from the model.
                During training, it returns a dict[Tensor] which contains the losses.
                During testing, it returns list[BoxList] contains additional fields
                like `scores`, `labels` and `mask` (for Mask R-CNN models).

        Nz*In training mode, targets should be passedr   r   r\   r8   z=Expected target boxes to be a tensorof shape [N, 4], got {:}.z4Expected target boxes to be of type Tensor, got {:}.éþÿÿÿr   r	   r]   zfAll bounding boxes should have positive height and width. Found invalid box {} for target at index {}.Ú0zBRetinaNet always returns a (Losses, Detections) tuple in scriptingT)&r�   r‚   rD   rE   r   rV   r^   Úformatr„   r    r¡   r   r   ry   r=   rˆ   r£   ÚanyÚwhereÚtolistrƒ   Ztensorsr   ÚlistÚvaluesr‡   r†   r   r¢   r*   r§   Zimage_sizesÚpostprocessZis_scriptingrŒ   ÚwarningsÚwarnr‘   )r#   Zimagesr+   Útargetr   Zoriginal_image_sizesÚimgÚvalZ
target_idxZdegenerate_boxesZbb_idxZdegen_bbrc   r,   r-   rW   r�   r   r   r   r0   ä  sb    þÿ
(
þ


zRetinaNet.forward)rr   rs   NNNNNrt   ru   rv   ru   rw   )N)r2   r3   r4   r5   rL   rl   rM   rp   r   rE   r    Zunusedr‘   r*   r§   r0   r6   r   r   r'   r   r   ô   s$   Sþ        ö9
JÚretinanet_resnet50_fpn_cocozLhttps://download.pytorch.org/models/retinanet_resnet50_fpn_coco-eeacb38b.pthFTé[   c                 K   sV   | rd}t d|g d¢tddƒd�}t||fi |¤Ž}| rRttd |d�}| |¡ |S )aá  
    Constructs a RetinaNet model with a ResNet-50-FPN backbone.

    The input to the model is expected to be a list of tensors, each of shape ``[C, H, W]``, one for each
    image, and should be in ``0-1`` range. Different images can have different sizes.

    The behavior of the model changes depending if it is in training or evaluation mode.

    During training, the model expects both the input tensors, as well as a targets (list of dictionary),
    containing:
        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with values
          between ``0`` and ``H`` and ``0`` and ``W``
        - labels (``Int64Tensor[N]``): the class label for each ground-truth box

    The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
    losses.

    During inference, the model requires only the input tensors, and returns the post-processed
    predictions as a ``List[Dict[Tensor]]``, one for each input image. The fields of the ``Dict`` are as
    follows:
        - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with values between
          ``0`` and ``H`` and ``0`` and ``W``
        - labels (``Int64Tensor[N]``): the predicted labels for each image
        - scores (``Tensor[N]``): the scores or each prediction

    Example::

        >>> model = torchvision.models.detection.retinanet_resnet50_fpn(pretrained=True)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)

    Arguments:
        pretrained (bool): If True, returns a model pre-trained on COCO train2017
        progress (bool): If True, displays a progress bar of the download to stderr
    FZresnet50)r   r   r8   r€   )Zreturned_layersZextra_blocksr¶   )Úprogress)r   r   r   r   Ú
model_urlsZload_state_dict)Z
pretrainedr¸   r&   Zpretrained_backboneÚkwargsrƒ   ÚmodelZ
state_dictr   r   r   r   B  s    &ÿÿ
)FTr·   T)&rJ   Úcollectionsr   r±   rE   Ztorch.nnr>   r   Ztorch.jit.annotationsr   r   r   Úutilsr   Ú r
   rL   Zanchor_utilsr   rˆ   r   Zbackbone_utilsr   Zops.feature_pyramid_networkr   Úopsr   r   r”   Ú__all__r   ÚModuler   r   r!   r   r¹   r   r   r   r   r   Ú<module>   s:   ÿZ[  Kþ  ÿ