U
    ­Ê¹j¿�  ã                   @   sr  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	m
Z
mZmZ d dlZd dlmZ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mZmZ ddl m!Z! ddl"m#Z#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/m0Z0 ddl1m2Z2 dddddgZ3e
e edœdd„Z4dd„ Z5d d!„ Z6G d"d#„ d#ej7ƒZ8G d$d%„ d%ej7ƒZ9G d&d'„ d'ej7ƒZ:G d(d„ dej7ƒZ;e!d)d*œZ<G d+d„ deƒZ=G d,d„ deƒZ>eƒ e$d-e=j?fd.e'j@fd/�dd0de'j@dd1œee= eAeeB ee' eeB ee;d2œd3d„ƒƒZCeƒ e$d-e>j?fd.e'j@fd/�dd0dddd1œee> eAeeB ee' eeB ee;d2œd4d„ƒƒZDdS )5é    N)ÚOrderedDict)Úpartial)ÚAnyÚCallableÚDictÚListÚOptionalÚTuple)ÚnnÚTensoré   )ÚboxesÚmiscÚsigmoid_focal_loss)ÚLastLevelP6P7)ÚObjectDetection)Ú_log_api_usage_onceé   )Úregister_modelÚWeightsÚWeightsEnum)Ú_COCO_CATEGORIES)Ú_ovewrite_value_paramÚhandle_legacy_interface)Úresnet50ÚResNet50_Weightsé   )Ú_utils)Ú	_box_lossÚoverwrite_eps)ÚAnchorGenerator)Ú_resnet_fpn_extractorÚ_validate_trainable_layers)ÚGeneralizedRCNNTransformÚ	RetinaNetÚRetinaNet_ResNet50_FPN_WeightsÚ!RetinaNet_ResNet50_FPN_V2_WeightsÚretinanet_resnet50_fpnÚretinanet_resnet50_fpn_v2)ÚxÚreturnc                 C   s&   | d }| dd … D ]}|| }q|S )Nr   r   © )r)   ÚresÚir+   r+   úe/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torchvision/models/detection/retinanet.pyÚ_sum"   s    
r/   c                 C   s^   t dƒD ]P}dD ]F}|› dd| › d|› �}|› d|› d|› �}|| kr|  |¡| |< qqd S )Né   )ÚweightÚbiaszconv.r   Ú.z.0.)ÚrangeÚpop)Ú
state_dictÚprefixr-   ÚtypeÚold_keyZnew_keyr+   r+   r.   Ú_v1_to_v2_weights)   s    r:   c                  C   s,   t dd„ dD ƒƒ} dt| ƒ }t| |ƒ}|S )Nc                 s   s(   | ] }|t |d  ƒt |d ƒfV  qdS )g‹r�ù¢(ô?g<n=¥þeù?N)Úint©Ú.0r)   r+   r+   r.   Ú	<genexpr>3   s     z%_default_anchorgen.<locals>.<genexpr>)é    é@   é€   é   i   ))ç      à?ç      ð?g       @)ÚtupleÚlenr    )Zanchor_sizesZaspect_ratiosÚanchor_generatorr+   r+   r.   Ú_default_anchorgen2   s    
rH   c                       sF   e Zd ZdZdeedejf  dœ‡ fdd„Zdd„ Z	d	d
„ Z
‡  ZS )ÚRetinaNetHeadau  
    A regression and classification head for use in RetinaNet.

    Args:
        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
        norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
    N.©Ú
norm_layerc                    s0   t ƒ  ¡  t||||d�| _t|||d�| _d S )NrJ   )ÚsuperÚ__init__ÚRetinaNetClassificationHeadÚclassification_headÚRetinaNetRegressionHeadÚregression_head)ÚselfÚin_channelsÚnum_anchorsÚnum_classesrK   ©Ú	__class__r+   r.   rM   D   s    
   ÿzRetinaNetHead.__init__c                 C   s$   | j  |||¡| j ||||¡dœS )N)ZclassificationÚbbox_regression)rO   Úcompute_lossrQ   )rR   ÚtargetsÚhead_outputsÚanchorsÚmatched_idxsr+   r+   r.   rY   K   s    þzRetinaNetHead.compute_lossc                 C   s   |   |¡|  |¡dœS )N)Ú
cls_logitsrX   )rO   rQ   )rR   r)   r+   r+   r.   ÚforwardR   s    zRetinaNetHead.forward)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r
   ÚModulerM   rY   r_   Ú__classcell__r+   r+   rV   r.   rI   9   s   
"rI   c                       sV   e Zd ZdZdZdeedejf  dœ‡ fdd„Z	‡ fd	d
„Z
dd„ Zdd„ Z‡  ZS )rN   af  
    A classification head for use in RetinaNet.

    Args:
        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
        norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
    r   ç{®Gáz„?N.rJ   c           	         sø   t ƒ  ¡  g }tdƒD ]}| tj|||d�¡ qtj|Ž | _| j 	¡ D ]@}t
|tjƒrHtjjj|jdd� |jd k	rHtjj |jd¡ qHt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 )	Nr0   rJ   rf   ©Zstdr   r   r   ©Zkernel_sizeZstrideÚpadding)rL   rM   r4   ÚappendÚmisc_nn_opsÚConv2dNormActivationr
   Ú
SequentialÚconvÚmodulesÚ
isinstanceÚConv2dÚtorchÚinitÚnormal_r1   r2   Z	constant_r^   ÚmathÚlogrU   rT   Ú	det_utilsÚMatcherÚBETWEEN_THRESHOLDS)	rR   rS   rT   rU   Zprior_probabilityrK   rn   Ú_ÚlayerrV   r+   r.   rM   d   s     

$z$RetinaNetClassificationHead.__init__c           	   	      sB   |  dd ¡}|d ks|dk r&t||ƒ tƒ  |||||||¡ d S ©NÚversionr   ©Úgetr:   rL   Ú_load_from_state_dict©	rR   r6   r7   Zlocal_metadataÚstrictZmissing_keysZunexpected_keysZ
error_msgsr}   rV   r+   r.   r€   …   s    

ùz1RetinaNetClassificationHead._load_from_state_dictc                 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   rD   ÚlabelsÚsum)Z	reductionr   )
Úzipr„   rr   Z
zeros_likery   rj   r   Úmaxr/   rF   )rR   rZ   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.   rY   ž   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   r0   r   r   ©Údim)
rn   r^   ÚshapeÚviewrU   ÚpermuteÚreshaperj   rr   Úcat)	rR   r)   Zall_cls_logitsÚfeaturesr^   ÚNrz   ÚHÚWr+   r+   r.   r_   ¿   s    

z#RetinaNetClassificationHead.forward)rf   N)r`   ra   rb   rc   Ú_versionr   r   r
   rd   rM   r€   rY   r_   re   r+   r+   rV   r.   rN   W   s   
  úú!!rN   c                       s`   e Zd ZdZdZdejiZdee	de
jf  dœ‡ fdd„Z‡ fd	d
„Zdd„ Zdd„ Z‡  ZS )rP   a%  
    A regression head for use in RetinaNet.

    Args:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
        norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
    r   Ú	box_coderN.rJ   c                    sâ   t ƒ  ¡  g }tdƒD ]}| tj|||d�¡ 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 ]>}t|tj	ƒrŠtjjj|jdd� |jd k	rŠtjj |j¡ qŠtjdd	�| _d
| _d S )Nr0   rJ   r   r   rh   rf   rg   ©rD   rD   rD   rD   ©ÚweightsÚl1)rL   rM   r4   rj   rk   rl   r
   rm   rn   rq   Úbbox_regrr   rs   rt   r1   Zzeros_r2   ro   rp   rw   ÚBoxCoderr™   Ú
_loss_type)rR   rS   rT   rK   rn   rz   r{   rV   r+   r.   rM   â   s    

z RetinaNetRegressionHead.__init__c           	   	      sB   |  dd ¡}|d ks|dk r&t||ƒ tƒ  |||||||¡ d S r|   r~   r�   rV   r+   r.   r€   ÷   s    

ùz-RetinaNetRegressionHead._load_from_state_dictc              	   C   s¬   g }|d }t ||||ƒD ]z\}}}	}
t |
dk¡d }| ¡ }|d |
|  }||d d …f }|	|d d …f }	| t| j| j|	||ƒtd|ƒ ¡ qt	|ƒtdt
|ƒƒ S )NrX   r   r   r   )r…   rr   ÚwhereÚnumelrj   r   r    r™   r†   r/   rF   )rR   rZ   r[   r\   r]   r‡   rX   rˆ   Zbbox_regression_per_imageÚanchors_per_imager‰   rŠ   r‹   Zmatched_gt_boxes_per_imager+   r+   r.   rY     s2       ÿûùÿ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Œ   r0   r   r   r   r   r�   )	rn   rž   r�   r�   r‘   r’   rj   rr   r“   )	rR   r)   Zall_bbox_regressionr”   rX   r•   rz   r–   r—   r+   r+   r.   r_   0  s    

zRetinaNetRegressionHead.forward)N)r`   ra   rb   rc   r˜   rw   rŸ   Ú__annotations__r   r   r
   rd   rM   r€   rY   r_   re   r+   r+   rV   r.   rP   Ò   s   	 ÿ" rP   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 on if it is in training or evaluation mode.

    During training, the model expects both the input tensors and targets (list of dictionary),
    containing:
        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - 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
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - labels (Int64Tensor[N]): the predicted labels for each image
        - scores (Tensor[N]): the scores for each prediction

    Args:
        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 (including 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.
        topk_candidates (int): Number of best detections to keep before NMS.

    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(weights=MobileNet_V2_Weights.DEFAULT).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)
    )r™   Úproposal_matcheré   é5  Nçš™™™™™©?rC   é,  çš™™™™™Ù?éè  c                    s  t ƒ  ¡  t| ƒ t|dƒs$tdƒ‚|| _t|ttd ƒfƒsNt	dt|ƒ› �ƒ‚|d kr\t
ƒ }|| _|d kr€t|j| ¡ d |ƒ}|| _|	d kržtj||dd�}	|	| _tjdd�| _|d krÄd	d
dg}|d krÖdddg}t||||f|Ž| _|
| _|| _|| _|| _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)zFanchor_generator should be of type AnchorGenerator or None instead of r   T)Zallow_low_quality_matchesrš   r›   g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?F)rL   rM   r   ÚhasattrÚ
ValueErrorÚbackbonerp   r    r8   Ú	TypeErrorrH   rG   rI   r¬   Únum_anchors_per_locationÚheadrw   rx   r¥   rŸ   r™   r#   Ú	transformÚscore_threshÚ
nms_threshÚdetections_per_imgÚtopk_candidatesÚ_has_warned)rR   r¯   rU   Úmin_sizeÚmax_sizeZ
image_meanZ	image_stdrG   r²   r¥   r´   rµ   r¶   Zfg_iou_threshZbg_iou_threshr·   ÚkwargsrV   r+   r.   rM   �  sF    

ÿÿý

zRetinaNet.__init__c                 C   s   | j r
|S |S )N)Útraining)rR   r‡   Ú
detectionsr+   r+   r.   Úeager_outputsâ  s    zRetinaNet.eager_outputsc              	   C   s€   g }t ||ƒD ]^\}}|d  ¡ dkrL| tj| d¡fdtj|jd�¡ qt 	|d |¡}| |  
|¡¡ q| j ||||¡S )Nr   r   rŒ   )ZdtypeÚdevice)r…   r¢   rj   rr   ÚfullÚsizeZint64r¿   Úbox_opsZbox_iour¥   r²   rY   )rR   rZ   r[   r\   r]   r£   rˆ   Zmatch_quality_matrixr+   r+   r.   rY   ê  s    ÿzRetinaNet.compute_lossc                    s¨  |d }|d }t |ƒ}g }t|ƒD �]|‰ ‡ fdd„|D ƒ}‡ fdd„|D ƒ}	|ˆ  |ˆ   }
}g }g }g }t||	|
ƒD ]À\}}}|jd }t |¡ ¡ }|| jk}|| }t |¡d }t	 
|| jd¡}| |¡\}}|| }tj||dd	�}|| }| j || || ¡}t ||¡}| |¡ | |¡ | |¡ qxtj|dd
�}tj|dd
�}tj|dd
�}t |||| j¡}|d | j… }| || || || dœ¡ q$|S )Nr^   rX   c                    s   g | ]}|ˆ  ‘qS r+   r+   )r=   Úbr©Úindexr+   r.   Ú
<listcomp>  s     z4RetinaNet.postprocess_detections.<locals>.<listcomp>c                    s   g | ]}|ˆ  ‘qS r+   r+   )r=   ÚclrÄ   r+   r.   rÆ     s     rŒ   r   Úfloor)Zrounding_moder�   )r   Zscoresrƒ   )rF   r4   r…   r�   rr   ZsigmoidÚflattenr´   r¡   rw   Z	_topk_minr·   ZtopkÚdivr™   Zdecode_singlerÂ   Zclip_boxes_to_imagerj   r“   Zbatched_nmsrµ   r¶   )rR   r[   r\   Zimage_shapesZclass_logitsZbox_regressionZ
num_imagesr½   Zbox_regression_per_imageZlogits_per_imager£   Zimage_shapeZimage_boxesZimage_scoresZimage_labelsZbox_regression_per_levelZlogits_per_levelZanchors_per_levelrU   Zscores_per_levelZ	keep_idxsZ	topk_idxsZnum_topkZidxsZanchor_idxsZlabels_per_levelZboxes_per_levelZkeepr+   rÄ   r.   Úpostprocess_detectionsù  s\      ÿ

 ÿ

ýÿz RetinaNet.postprocess_detectionsc              	      sÆ  | j rf|dkrt dd¡ nJ|D ]D}|d }t t|tjƒd¡ t t|jƒdko^|jd dkd	¡ q g }|D ]L}|jd
d… }t t|ƒdkd|jd
d… › �¡ | |d |d f¡ qn|  ||¡\}}|dk	�r`t	|ƒD ]€\}}|d }|dd…dd…f |dd…dd…f k}	|	 
¡ rÞt |	j
dd�¡d d }
||
  ¡ }t dd|› d|› d�¡ qÞ|  |j¡}t|tjƒ�rˆtd|fgƒ}t| ¡ ƒ}|  |¡}|  ||¡}i }g }| j �râ|dk�rÒt dd¡ n|  |||¡}n¬dd„ |D ƒ‰d}ˆD ]}||7 }�qø|d  d¡}|| ‰ ‡ fdd„ˆD ƒ‰i }|D ] }t|| jˆdd�ƒ||< �q8‡fdd„|D ƒ}|  |||j¡}| j ||j|¡}tj ¡ �rº| j�s²t d¡ d| _||fS |  ||¡S )a  
        Args:
            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).

        NFz0targets should not be none when in training moder   z+Expected target boxes to be of type Tensor.r   rŒ   r0   z5Expected target boxes to be a tensor of shape [N, 4].éþÿÿÿzJexpecting the last two dimensions of the Tensor to be H and W instead got r   r   r�   zLAll bounding boxes should have positive height and width. Found invalid box z for target at index r3   Ú0c                 S   s    g | ]}|  d ¡|  d¡ ‘qS )r   r   )rÁ   r<   r+   r+   r.   rÆ   ˆ  s     z%RetinaNet.forward.<locals>.<listcomp>r^   c                    s   g | ]}|ˆ  ‘qS r+   r+   )r=   Zhw)ÚAr+   r.   rÆ   Ž  s     c                    s   g | ]}t | ˆ ¡ƒ‘qS r+   )ÚlistÚsplit)r=   Úa)Únum_anchors_per_levelr+   r.   rÆ   ”  s     zBRetinaNet always returns a (Losses, Detections) tuple in scriptingT) r¼   rr   Z_assertrp   r   rF   r�   rj   r³   Ú	enumerateÚanyr¡   Útolistr¯   Ztensorsr   rÏ   Úvaluesr²   rG   rY   rÁ   rÐ   rË   Zimage_sizesÚpostprocessÚjitZis_scriptingr¸   ÚwarningsÚwarnr¾   )rR   ZimagesrZ   Útargetr   Zoriginal_image_sizesZimgÚvalZ
target_idxZdegenerate_boxesZbb_idxZdegen_bbr”   r[   r\   r‡   r½   ZHWÚvZHWAZsplit_head_outputsÚkZsplit_anchorsr+   )rÎ   rÒ   r.   r_   9  sz    þ
þ
(þ


zRetinaNet.forward)r¦   r§   NNNNNr¨   rC   r©   rC   rª   r«   )N)r`   ra   rb   rc   rw   rŸ   rx   r¤   rM   rr   rØ   Zunusedr¾   rY   rË   r_   re   r+   r+   rV   r.   r$   C  s.   Uþ
             îE
@)r   r   )Ú
categoriesr¹   c                   @   s8   e Zd Zedeedddddiiddd	d
œ–d�ZeZdS )r%   zLhttps://download.pytorch.org/models/retinanet_resnet50_fpn_coco-eeacb38b.pthizJhttps://github.com/pytorch/vision/tree/main/references/detection#retinanetúCOCO-val2017Úbox_mapg333333B@gáz®Gñb@g�•C‹H`@zSThese weights were produced by following a similar training recipe as on the paper.©Z
num_paramsZrecipeZ_metricsZ_opsÚ
_file_sizeZ_docs©ÚurlZ
transformsÚmetaN©r`   ra   rb   r   r   Ú_COMMON_METAÚCOCO_V1ÚDEFAULTr+   r+   r+   r.   r%   ¨  s"    ÿÿõýc                   @   s8   e Zd Zedeedddddiiddd	d
œ–d�ZeZdS )r&   zOhttps://download.pytorch.org/models/retinanet_resnet50_fpn_v2_coco-5905b1c5.pthi—ÞFz+https://github.com/pytorch/vision/pull/5756rà   rá   g     ÀD@gV-²�c@gw¾Ÿ/Ab@zZThese weights were produced using an enhanced training recipe to boost the model accuracy.râ   rä   Nrç   r+   r+   r+   r.   r&   ½  s"    ÿÿõýZ
pretrainedZpretrained_backbone)rœ   Úweights_backboneT)rœ   ÚprogressrU   rë   Útrainable_backbone_layers)rœ   rì   rU   rë   rí   r»   r*   c           
      K   sÞ   t  | ¡} t |¡}| dk	r8d}td|t| jd ƒƒ}n|dkrDd}| dk	pR|dk	}t||ddƒ}|rltjnt	j
}t|||d�}t||ddd	gtd
d
ƒd�}t||f|Ž}	| dk	rÚ|	 | j|dd�¡ | t jkrÚt|	dƒ |	S )aœ  
    Constructs a RetinaNet model with a ResNet-50-FPN backbone.

    .. betastatus:: detection module

    Reference: `Focal Loss for Dense Object Detection <https://arxiv.org/abs/1708.02002>`_.

    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 on if it is in training or evaluation mode.

    During training, the model expects both the input tensors and targets (list of dictionary),
    containing:

        - boxes (``FloatTensor[N, 4]``): the ground-truth boxes in ``[x1, y1, x2, y2]`` format, with
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - 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, where ``N`` is the number of detections:

        - boxes (``FloatTensor[N, 4]``): the predicted boxes in ``[x1, y1, x2, y2]`` format, with
          ``0 <= x1 < x2 <= W`` and ``0 <= y1 < y2 <= H``.
        - labels (``Int64Tensor[N]``): the predicted labels for each detection
        - scores (``Tensor[N]``): the scores of each detection

    For more details on the output, you may refer to :ref:`instance_seg_output`.

    Example::

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

    Args:
        weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights`
            below for more details, and possible values. By default, no
            pre-trained weights are used.
        progress (bool): If True, displays a progress bar of the download to stderr. Default is True.
        num_classes (int, optional): number of output classes of the model (including the background)
        weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for
            the backbone.
        trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
            Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
            passed (the default) this value is set to 3.
        **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_Weights
        :members:
    NrU   rß   é[   é   r   )rœ   rì   rK   r   r0   rB   ©Zreturned_layersZextra_blocksT©rì   Z
check_hashg        )r%   Úverifyr   r   rF   ræ   r"   rk   ZFrozenBatchNorm2dr
   ZBatchNorm2dr   r!   r   r$   Úload_state_dictÚget_state_dictré   r   )
rœ   rì   rU   rë   rí   r»   Ú
is_trainedrK   r¯   Úmodelr+   r+   r.   r'   Ò  s.    K

   ÿ

c                 K   sò   t  | ¡} t |¡}| dk	r8d}td|t| jd ƒƒ}n|dkrDd}| dk	pR|dk	}t||ddƒ}t||d�}t||ddd	gt	d
dƒd�}t
ƒ }t|j| ¡ d |ttjdƒd�}	d|	j_t||f||	dœ|—Ž}
| dk	rî|
 | j|dd�¡ |
S )aÎ  
    Constructs an improved RetinaNet model with a ResNet-50-FPN backbone.

    .. betastatus:: detection module

    Reference: `Bridging the Gap Between Anchor-based and Anchor-free Detection via Adaptive Training Sample Selection
    <https://arxiv.org/abs/1912.02424>`_.

    :func:`~torchvision.models.detection.retinanet_resnet50_fpn` for more details.

    Args:
        weights (:class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights`
            below for more details, and possible values. By default, no
            pre-trained weights are used.
        progress (bool): If True, displays a progress bar of the download to stderr. Default is True.
        num_classes (int, optional): number of output classes of the model (including the background)
        weights_backbone (:class:`~torchvision.models.ResNet50_Weights`, optional): The pretrained weights for
            the backbone.
        trainable_backbone_layers (int, optional): number of trainable (not frozen) layers starting from final block.
            Valid values are between 0 and 5, with 5 meaning all backbone layers are trainable. If ``None`` is
            passed (the default) this value is set to 3.
        **kwargs: parameters passed to the ``torchvision.models.detection.RetinaNet``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/retinanet.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.detection.RetinaNet_ResNet50_FPN_V2_Weights
        :members:
    NrU   rß   rî   rï   r   )rœ   rì   r   r0   i   rB   rð   r   r?   rJ   Zgiou)rG   r²   Trñ   )r&   rò   r   r   rF   ræ   r"   r   r!   r   rH   rI   r¬   r±   r   r
   Z	GroupNormrQ   r    r$   ró   rô   )rœ   rì   rU   rë   rí   r»   rõ   r¯   rG   r²   rö   r+   r+   r.   r(   9  s8    -

   ÿ

ü)Eru   rÙ   Úcollectionsr   Ú	functoolsr   Útypingr   r   r   r   r   r	   rr   r
   r   Zopsr   rÂ   r   rk   r   Zops.feature_pyramid_networkr   Ztransforms._presetsr   Úutilsr   Z_apir   r   r   Ú_metar   r   r   r   Zresnetr   r   Ú rw   r   r   Zanchor_utilsr    Zbackbone_utilsr!   r"   r³   r#   Ú__all__r/   r:   rH   rd   rI   rN   rP   r$   rè   r%   r&   ré   ZIMAGENET1K_V1Úboolr;   r'   r(   r+   r+   r+   r.   Ú<module>   sš    û		{q  bþþúøbþúø