a
    PSic%                  
   @   s  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 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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+ ddl,m-Z-m.Z. ddl/m0Z0 g dZ1G dd dej2Z3G dd dej2Z4G dd dej2Z5G dd dej2Z6G d d! d!eZ7e#d"e7j8fd#e&j9fd$dd%de&j9dd&ee7 e:ee; ee& ee; ee6d'd(d)Z<dd*l"m=Z= e=d+e7j8j>iZ?dS ),    N)OrderedDict)partial)AnyCallableDictListTupleOptional)nnTensor   )sigmoid_focal_lossgeneralized_box_iou_loss)boxes)misc)LastLevelP6P7)ObjectDetection)_log_api_usage_once   )WeightsEnumWeights)_COCO_CATEGORIES)handle_legacy_interface_ovewrite_value_param)ResNet50_Weightsresnet50   )_utils)AnchorGenerator)_resnet_fpn_extractor_validate_trainable_layers)GeneralizedRCNNTransform)FCOSFCOS_ResNet50_FPN_Weightsfcos_resnet50_fpnc                       s   e Zd ZdZdejiZdeeeee dd fddZ	e
eeef  eeef e
e e
e eeef dd	d
Ze
e eeef dddZ  ZS )FCOSHeadaT  
    A regression and classification head for use in FCOS.

    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
        num_convs (Optional[int]): number of conv layer of head. Default: 4.
    	box_coder   N)in_channelsnum_anchorsnum_classes	num_convsreturnc                    s:   t    tjdd| _t||||| _t|||| _d S )NTnormalize_by_size)	super__init__	det_utilsBoxLinearCoderr&   FCOSClassificationHeadclassification_headFCOSRegressionHeadregression_head)selfr(   r)   r*   r+   	__class__ ]/var/www/html/django/DPS/env/lib/python3.9/site-packages/torchvision/models/detection/fcos.pyr0   0   s    
zFCOSHead.__init__)targetshead_outputsanchorsmatched_idxsr,   c                    sR  |d }|d }|d }g }g }	t ||D ]\}
}t|
d dkrn|
d t|f}|
d t|df}n(|
d |jdd }|
d |jdd }d	||dk < || |	| q*t|}|dk}|  }t	|}d
|||| f< t
||dd} fddt ||D }tt||  t|	| dd} fddt ||	D }tj|dd}t|dkr|| d d	 }nz|d d d d ddgf }|d d d d ddgf }t|jd	dd |jd	dd  |jd	dd |jd	dd   }|jdd}tjj|| || dd}|td| |td| |td| dS )N
cls_logitsbbox_regressionbbox_ctrnesslabelsr   r   r'   )min      ?sum)	reductionc                    s   g | ]\}} j ||qS r:   )r&   decode_single).0anchors_per_imagebbox_regression_per_imager7   r:   r;   
<listcomp>[   s   z)FCOSHead.compute_loss.<locals>.<listcomp>c                    s   g | ]\}} j ||qS r:   )r&   encode_single)rJ   rK   Zboxes_targets_per_imagerM   r:   r;   rN   g   s   dimr   r   r   )classificationrA   rB   )ziplen	new_zerosclipappendtorchstackrG   item
zeros_liker   r   floatsizesqrtrD   maxsqueezer
   
functional binary_cross_entropy_with_logits)r7   r<   r=   r>   r?   r@   rA   rB   Zall_gt_classes_targetsZall_gt_boxes_targetstargets_per_imagematched_idxs_per_imageZgt_classes_targetsZgt_boxes_targetsZforegroud_maskZnum_foregroundZloss_cls
pred_boxesZloss_bbox_regZbbox_reg_targetsZgt_ctrness_targetsZ
left_rightZ
top_bottomZpred_centernessZloss_bbox_ctrnessr:   rM   r;   compute_loss6   sb    




zFCOSHead.compute_lossxr,   c                 C   s$   |  |}| |\}}|||dS )N)r@   rA   rB   )r4   r6   )r7   rh   r@   rA   rB   r:   r:   r;   forward   s    
zFCOSHead.forward)r'   )__name__
__module____qualname____doc__r1   r2   __annotations__intr	   r0   r   r   strr   rf   ri   __classcell__r:   r:   r8   r;   r%   !   s    

Jr%   c                
       sV   e Zd ZdZdeeeeeeedej	f  dd fddZ
ee ed	d
dZ  ZS )r3   a  
    A classification head for use in FCOS.

    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.
        num_convs (Optional[int]): number of conv layer. Default: 4.
        prior_probability (Optional[float]): probability of prior. Default: 0.01.
        norm_layer: Module specifying the normalization layer to use.
    r'   {Gz?N.)r(   r)   r*   r+   prior_probability
norm_layerr,   c           
   
      s  t    || _|| _|d u r*ttjd}g }t|D ]:}|tj	||dddd ||| |t
  q6tj| | _| j D ]6}	t|	tj	rtjjj|	jdd tjj|	jd qtj	||| dddd| _tjjj| jjdd tjj| jjtd| |   d S )N    r   r   kernel_sizestridepaddingrr   stdr   )r/   r0   r*   r)   r   r
   	GroupNormrangerW   Conv2dReLU
Sequentialconvchildren
isinstancerX   initnormal_weight	constant_biasr@   mathlog)
r7   r(   r)   r*   r+   rs   rt   r   _layerr8   r:   r;   r0      s$    	
zFCOSClassificationHead.__init__rg   c           	      C   s~   g }|D ]f}|  |}| |}|j\}}}}||d| j||}|ddddd}||d| j}|| qtj	|ddS )NrE   r   r   r'   r   r   rP   )
r   r@   shapeviewr*   permutereshaperW   rX   cat)	r7   rh   Zall_cls_logitsfeaturesr@   Nr   HWr:   r:   r;   ri      s    

zFCOSClassificationHead.forward)r'   rr   N)rj   rk   rl   rm   ro   r\   r	   r   r
   Moduler0   r   r   ri   rq   r:   r:   r8   r;   r3      s      !r3   c                       sX   e Zd ZdZdeeeeedejf  d fddZ	e
e eeef dd	d
Z  ZS )r5   a  
    A regression head for use in FCOS, which combines regression branch and center-ness branch.
    This can obtain better performance.

    Reference: `FCOS: A simple and strong anchor-free object detector <https://arxiv.org/abs/2006.09214>`_.

    Args:
        in_channels (int): number of channels of the input feature
        num_anchors (int): number of anchors to be predicted
        num_convs (Optional[int]): number of conv layer. Default: 4.
        norm_layer: Module specifying the normalization layer to use.
    r'   N.)r(   r)   r+   rt   c              
      s   t    |d u rttjd}g }t|D ]:}|tj||dddd ||| |t  q*tj	| | _
tj||d dddd| _tj||d dddd| _| j| jfD ](}tjjj|jdd tjj|j q| j
 D ]4}t|tjrtjjj|jdd tjj|j qd S )Nru   r   r   rv   r'   rr   rz   )r/   r0   r   r
   r|   r}   rW   r~   r   r   r   bbox_regrB   rX   r   r   r   zeros_r   r   r   )r7   r(   r)   r+   rt   r   r   r   r8   r:   r;   r0      s$    
zFCOSRegressionHead.__init__rg   c                 C   s   g }g }|D ]}|  |}tj| |}| |}|j\}}	}
}||dd|
|}|ddddd}|	|dd}|
| ||dd|
|}|ddddd}|	|dd}|
| qtj|ddtj|ddfS )NrE   r'   r   r   r   r   rP   )r   r
   ra   relur   rB   r   r   r   r   rW   rX   r   )r7   rh   Zall_bbox_regressionZall_bbox_ctrnessr   Zbbox_featurerA   rB   r   r   r   r   r:   r:   r;   ri      s     


zFCOSRegressionHead.forward)r'   N)rj   rk   rl   rm   ro   r	   r   r
   r   r0   r   r   r   ri   rq   r:   r:   r8   r;   r5      s     r5   c                       sn  e Zd ZdZdejiZdeje	e	e	e
ee  e
ee  e
e e
ej eeee	e	d fddZejjeeef eeeef  eeeef eeeef  f dddZeeeef  eeef ee ee	 eeef dddZeeee f eee  eee	e	f  eeeef  dddZdee e
eeeef   eeeef eeeef  f dddZ  ZS )r"   a  
    Implements FCOS.

    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
          ``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, regression
    and centerness 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. For FCOS, only set one anchor for per position of each level, the width and height equal to
            the stride of feature map, and set aspect ratio = 1.0, so the center of anchor is equivalent to the point
            in FCOS paper.
        head (nn.Module): Module run on top of the feature pyramid.
            Defaults to a module containing a classification and regression module.
        center_sampling_radius (int): radius of the "center" of a groundtruth box,
            within which all anchor points are labeled positive.
        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.
        topk_candidates (int): Number of best detections to keep before NMS.

    Example:

        >>> import torch
        >>> import torchvision
        >>> from torchvision.models.detection import FCOS
        >>> 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
        >>> # FCOS 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=((8,), (16,), (32,), (64,), (128,)),
        >>>     aspect_ratios=((1.0,),)
        >>> )
        >>>
        >>> # put the pieces together inside a FCOS model
        >>> model = FCOS(
        >>>     backbone,
        >>>     num_classes=80,
        >>>     anchor_generator=anchor_generator,
        >>> )
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
    r&      5  N      ?皙?333333?d     )backboner*   min_sizemax_size
image_mean	image_stdanchor_generatorheadcenter_sampling_radiusscore_thresh
nms_threshdetections_per_imgtopk_candidatesc                    s0  t    t|  t|ds$td|| _t|ttd fsNt	dt| |d u rpd}dt
| }t||}|| _| j d dkrtd| d  |d u rt|j| d |}|| _tjd	d
| _|d u rg d}|d u rg d}t||||fi || _|	| _|
| _|| _|| _|| _d| _d S )Nout_channelszbackbone should contain an attribute out_channels specifying the number of output channels (assumed to be the same for all the levels)zIanchor_generator should be of type AnchorGenerator or None, instead  got ))   )   )ru   )@   )   ))rF   r   r   zFanchor_generator.num_anchors_per_location()[0] should be 1 instead of Tr-   )g
ףp=
?gv/?gCl?)gZd;O?gy&1?g?F)r/   r0   r   hasattr
ValueErrorr   r   r   type	TypeErrorrT   r   num_anchors_per_locationr%   r   r   r1   r2   r&   r!   	transformr   r   r   r   r   _has_warned)r7   r   r*   r   r   r   r   r   r   r   r   r   r   r   kwargsanchor_sizesaspect_ratiosr8   r:   r;   r0   j  sF    


zFCOS.__init__)losses
detectionsr,   c                 C   s   | j r
|S |S )N)training)r7   r   r   r:   r:   r;   eager_outputs  s    zFCOS.eager_outputs)r<   r=   r>   num_anchors_per_levelr,   c              	   C   s  g }t ||D ]t\}}|d  dkrN|tj|dfdtj|jd q|d }|d d d df |d d dd f  d }	|d d d df |d d dd f  d }
|d d df |d d df  }|
d d d d d f |	d d d d d f   j	ddj
| j|d d d f  k }|
jddjdd\}}|jddjdd\}}}}tj|| || || || gdd}||jddj
dkM }|d }d|d |d < |d	 }td
||d  d < |j	ddj
}|||d d d f k||d d d f k @ M }|d d df |d d df  |d d df |d d df   }|tjd|d d d f   }|j	dd\}}d||dk < || q| j||||S )Nr   r   rE   )dtypedevicer   rP   r   r'   r   infr   g    חAgh㈵>)rS   numelrW   rX   fullr]   int64r   abs_r_   valuesr   	unsqueezeunbindrY   rD   r\   tofloat32r   rf   )r7   r<   r=   r>   r   r?   rK   rc   gt_boxesZ
gt_centersZanchor_centersr   Zpairwise_matchrh   yx0y0x1y1Zpairwise_distlower_boundupper_boundZgt_areasZ
min_valuesZmatched_idxr:   r:   r;   rf     s@    ,, 0&,@ zFCOS.compute_loss)r=   r>   image_shapesr,   c                    s  |d }|d }|d }t |}g }t|D ]  fdd|D }	 fdd|D }
 fdd|D }|  |   }}g }g }g }t|	|
||D ]\}}}}|jd }tt|t|  }|| jk}|| }t	|d	 }t
|| jd	}||\}}|| }tj||d
d}|| }| j|| || }t||}|| || || qtj|d	d}tj|d	d}tj|d	d}t|||| j}|d | j }||| || || d q,|S )Nr@   rA   rB   c                    s   g | ]}|  qS r:   r:   )rJ   brindexr:   r;   rN         z/FCOS.postprocess_detections.<locals>.<listcomp>c                    s   g | ]}|  qS r:   r:   )rJ   clr   r:   r;   rN     r   c                    s   g | ]}|  qS r:   r:   )rJ   bcr   r:   r;   rN     r   rE   r   floor)rounding_moderP   )r   scoresrC   )rT   r}   rS   r   rX   r^   sigmoidflattenr   wherer1   	_topk_minr   topkdivr&   rI   box_opsclip_boxes_to_imagerW   r   batched_nmsr   r   )r7   r=   r>   r   class_logitsbox_regressionZbox_ctrness
num_imagesr   Zbox_regression_per_imageZlogits_per_imageZbox_ctrness_per_imagerK   image_shapeZimage_boxesZimage_scoresZimage_labelsbox_regression_per_levelZlogits_per_levelZbox_ctrness_per_levelZanchors_per_levelr*   Zscores_per_levelZ	keep_idxsZ	topk_idxsZnum_topkidxsZanchor_idxsZlabels_per_levelZboxes_per_levelkeepr:   r   r;   postprocess_detections  s^    



zFCOS.postprocess_detections)imagesr<   r,   c              	      s  | j rp|du rtdd nT|D ]N}|d }tt|tjd tt|jdko^|jd dkd	|j d
 q g }|D ]L}|jdd }tt|dkd|jdd   ||d |d f qx| ||\}}|durjt	|D ]\}}|d }|ddddf |ddddf k}	|	
 rt|	j
ddd d }
||
  }tdd| d| d
 q| |j}t|tjrtd|fg}t| }| |}| ||}dd |D  i }g }| j r|du rtdd n| ||| }n^i }|D ] }t|| j dd||< q 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   rE   r'   z:Expected target boxes to be a tensor of shape [N, 4], got .zJexpecting the last two dimensions of the Tensor to be H and W instead got r   r   rP   zLAll bounding boxes should have positive height and width. Found invalid box z for target at index 0c                 S   s    g | ]}| d | d qS )r   r   )r]   )rJ   rh   r:   r:   r;   rN   o  r   z FCOS.forward.<locals>.<listcomp>c                    s   g | ]}t | qS r:   )listsplit)rJ   ar   r:   r;   rN   ~  r   z=FCOS always returns a (Losses, Detections) tuple in scriptingT)r   rX   _assertr   r   rT   r   rW   r   	enumerateanyr   tolistr   tensorsr   r   r   r   r   rf   r   r   image_sizespostprocessjitis_scriptingr   warningswarnr   )r7   r   r<   targetr   original_image_sizesimgval
target_idxdegenerate_boxesbb_idxdegen_bbr   r=   r>   r   r   Zsplit_head_outputskZsplit_anchorsr:   r   r;   ri   +  sn    

(


zFCOS.forward)r   r   NNNNr   r   r   r   r   )N)rj   rk   rl   rm   r1   r2   rn   r
   r   ro   r	   r   r\   r   r0   rX   r   unusedr   rp   r   r   r   rf   r   ri   rq   r:   r:   r8   r;   r"     s`   W	           

B


2&H r"   c                
   @   s4   e Zd Zedededddddiidd	d
ZeZdS )r#   zGhttps://download.pytorch.org/models/fcos_resnet50_fpn_coco-99b0c9b7.pthi e)r   r   zShttps://github.com/pytorch/vision/tree/main/references/detection#fcos-resnet-50-fpnzCOCO-val2017box_mapgC@zSThese weights were produced by following a similar training recipe as on the paper.)
num_params
categoriesr   recipe_metrics_docs)url
transformsmetaN)rj   rk   rl   r   r   r   COCO_V1DEFAULTr:   r:   r:   r;   r#     s   r#   
pretrainedpretrained_backbone)weightsweights_backboneT)r  progressr*   r  trainable_backbone_layers)r  r  r*   r  r  r   r,   c           
      K   s   t | } t|}| dur6d}t|t| jd }n|du rBd}| dupP|du}t||dd}|rjtjnt	j
}t|||d}t||g dtddd	}t||fi |}	| dur|	| j|d
 |	S )a  
    Constructs a FCOS model with a ResNet-50-FPN backbone.

    .. betastatus:: detection module

    Reference: `FCOS: Fully Convolutional One-Stage Object Detection <https://arxiv.org/abs/1904.01355>`_.
               `FCOS: A simple and strong anchor-free object detector <https://arxiv.org/abs/2006.09214>`_.

    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
          ``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.fcos_resnet50_fpn(weights=FCOS_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.FCOS_ResNet50_FPN_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.detection.FCOS_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
        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) resnet 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. Default: None
        **kwargs: parameters passed to the ``torchvision.models.detection.FCOS``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/fcos.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.detection.FCOS_ResNet50_FPN_Weights
        :members:
    Nr  [      r   )r  r  rt   )r   r   r'      )returned_layersextra_blocks)r  )r#   verifyr   r   rT   r  r    misc_nn_opsFrozenBatchNorm2dr
   BatchNorm2dr   r   r   r"   load_state_dictget_state_dict)
r  r  r*   r  r  r   
is_trainedrt   r   modelr:   r:   r;   r$     s$    K

r$   )
_ModelURLsZfcos_resnet50_fpn_coco)@r   r  collectionsr   	functoolsr   typingr   r   r   r   r   r	   rX   r
   r   opsr   r   r   r   r   r$  Zops.feature_pyramid_networkr   Ztransforms._presetsr   utilsr   _apir   r   _metar   r   r   r   resnetr   r    r1   anchor_utilsr   backbone_utilsr   r    r   r!   __all__r   r%   r3   r5   r"   r#   r  IMAGENET1K_V1boolro   r$   r+  r  
model_urlsr:   r:   r:   r;   <module>   sh    i@E    a