U
    (df                  
   @   s  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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m Z m!Z!m"Z" dddddgZ#G dd deZ$G dd dej%Z&G dd dej%Z'eddZ(G dd deZ)G dd deZ*ede)j+fd ej,fd!d"d#d"ej,d"d$ee) e-ee. ee ee. ee$d%d&dZ/d"d#d"d"d"d$ee* e-ee. ee ee. ee$d%d'dZ0dd(lm1Z1 e1d)e)j+j2iZ3d"S )*    )OrderedDict)AnyCallableOptional)nn)MultiScaleRoIAlign   )misc)ObjectDetection   )WeightsEnumWeights)_COCO_CATEGORIES)handle_legacy_interface_ovewrite_value_param)ResNet50_Weightsresnet50   )overwrite_eps)_resnet_fpn_extractor_validate_trainable_layers)
FasterRCNNFastRCNNConvFCHeadRPNHead_default_anchorgenMaskRCNNMaskRCNN_ResNet50_FPN_Weights MaskRCNN_ResNet50_FPN_V2_Weightsmaskrcnn_resnet50_fpnmaskrcnn_resnet50_fpn_v2c                       s"   e Zd ZdZd fdd	Z  ZS )r   a!  
    Implements Mask R-CNN.

    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
        - masks (UInt8Tensor[N, H, W]): the segmentation binary masks for each instance

    The model returns a Dict[Tensor] during training, containing the classification and regression
    losses for both the RPN and the R-CNN, and the mask loss.

    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 or each prediction
        - masks (UInt8Tensor[N, 1, H, W]): the predicted masks for each instance, in 0-1 range. In order to
          obtain the final segmentation masks, the soft masks can be thresholded, generally
          with a value of 0.5 (mask >= 0.5)

    Args:
        backbone (nn.Module): the network used to compute the features for the model.
            It should contain a 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 and OrderedDict[Tensor].
        num_classes (int): number of output classes of the model (including the background).
            If box_predictor is specified, num_classes should be None.
        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
        rpn_anchor_generator (AnchorGenerator): module that generates the anchors for a set of feature
            maps.
        rpn_head (nn.Module): module that computes the objectness and regression deltas from the RPN
        rpn_pre_nms_top_n_train (int): number of proposals to keep before applying NMS during training
        rpn_pre_nms_top_n_test (int): number of proposals to keep before applying NMS during testing
        rpn_post_nms_top_n_train (int): number of proposals to keep after applying NMS during training
        rpn_post_nms_top_n_test (int): number of proposals to keep after applying NMS during testing
        rpn_nms_thresh (float): NMS threshold used for postprocessing the RPN proposals
        rpn_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.
        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.
        rpn_batch_size_per_image (int): number of anchors that are sampled during training of the RPN
            for computing the loss
        rpn_positive_fraction (float): proportion of positive anchors in a mini-batch during training
            of the RPN
        rpn_score_thresh (float): during inference, only return proposals with a classification score
            greater than rpn_score_thresh
        box_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
            the locations indicated by the bounding boxes
        box_head (nn.Module): module that takes the cropped feature maps as input
        box_predictor (nn.Module): module that takes the output of box_head and returns the
            classification logits and box regression deltas.
        box_score_thresh (float): during inference, only return proposals with a classification score
            greater than box_score_thresh
        box_nms_thresh (float): NMS threshold for the prediction head. Used during inference
        box_detections_per_img (int): maximum number of detections per image, for all classes.
        box_fg_iou_thresh (float): minimum IoU between the proposals and the GT box so that they can be
            considered as positive during training of the classification head
        box_bg_iou_thresh (float): maximum IoU between the proposals and the GT box so that they can be
            considered as negative during training of the classification head
        box_batch_size_per_image (int): number of proposals that are sampled during training of the
            classification head
        box_positive_fraction (float): proportion of positive proposals in a mini-batch during training
            of the classification head
        bbox_reg_weights (Tuple[float, float, float, float]): weights for the encoding/decoding of the
            bounding boxes
        mask_roi_pool (MultiScaleRoIAlign): the module which crops and resizes the feature maps in
             the locations indicated by the bounding boxes, which will be used for the mask head.
        mask_head (nn.Module): module that takes the cropped feature maps as input
        mask_predictor (nn.Module): module that takes the output of the mask_head and returns the
            segmentation mask logits

    Example::

        >>> import torch
        >>> import torchvision
        >>> from torchvision.models.detection import MaskRCNN
        >>> 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
        >>> # MaskRCNN 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 RPN 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),))
        >>>
        >>> # let's define what are the feature maps that we will
        >>> # use to perform the region of interest cropping, as well as
        >>> # the size of the crop after rescaling.
        >>> # if your backbone returns a Tensor, featmap_names is expected to
        >>> # be ['0']. More generally, the backbone should return an
        >>> # OrderedDict[Tensor], and in featmap_names you can choose which
        >>> # feature maps to use.
        >>> roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
        >>>                                                 output_size=7,
        >>>                                                 sampling_ratio=2)
        >>>
        >>> mask_roi_pooler = torchvision.ops.MultiScaleRoIAlign(featmap_names=['0'],
        >>>                                                      output_size=14,
        >>>                                                      sampling_ratio=2)
        >>> # put the pieces together inside a MaskRCNN model
        >>> model = MaskRCNN(backbone,
        >>>                  num_classes=2,
        >>>                  rpn_anchor_generator=anchor_generator,
        >>>                  box_roi_pool=roi_pooler,
        >>>                  mask_roi_pool=mask_roi_pooler)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
    N   5      ffffff?333333?         ?        皙?d            ?c!           '         s   t |ttd fs$tdt| |d k	r<| d k	r<td|j}"|d kr`tddddgddd	}|d kr|d
}#d}$t|"|#|$}| d krd}%d}&t|%|&|} t j	|||||||||	|
|||||||||||||||||||f|! || j
_|| j
_| | j
_d S )NzFmask_roi_pool should be of type MultiScaleRoIAlign or None instead of z;num_classes should be None when mask_predictor is specified0123   r   )Zfeatmap_namesZoutput_sizeZsampling_ratio)r&   r&   r&   r&   r   r&   )
isinstancer   type	TypeError
ValueErrorout_channelsMaskRCNNHeadsMaskRCNNPredictorsuper__init__Z	roi_headsmask_roi_pool	mask_headmask_predictor)'selfbackbonenum_classesmin_sizemax_sizeZ
image_meanZ	image_stdrpn_anchor_generatorrpn_headZrpn_pre_nms_top_n_trainZrpn_pre_nms_top_n_testZrpn_post_nms_top_n_trainZrpn_post_nms_top_n_testZrpn_nms_threshZrpn_fg_iou_threshZrpn_bg_iou_threshZrpn_batch_size_per_imageZrpn_positive_fractionZrpn_score_threshZbox_roi_poolbox_headZbox_predictorZbox_score_threshZbox_nms_threshZbox_detections_per_imgZbox_fg_iou_threshZbox_bg_iou_threshZbox_batch_size_per_imageZbox_positive_fractionZbbox_reg_weightsr;   r<   r=   kwargsr6   Zmask_layersZmask_dilationZmask_predictor_in_channelsZmask_dim_reduced	__class__ J/tmp/pip-unpacked-wheel-vx7f76es/torchvision/models/detection/mask_rcnn.pyr:      sl    )!$zMaskRCNN.__init__)Nr    r!   NNNNr"   r#   r"   r#   r$   r$   r%   r&   r'   r(   NNNr)   r'   r*   r'   r'   r+   r,   NNNN)__name__
__module____qualname____doc__r:   __classcell__rI   rI   rG   rJ   r      sD    
                               c                       sB   e Zd ZdZd	eedejf  d fddZ fddZ	  Z
S )
r7   r   N.
norm_layerc           	         s   g }|}|D ]&}| tj||dd|||d |}qt j|  |  D ]<}t|tjrHtj	j
|jddd |jdk	rHtj	|j qHdS )a0  
        Args:
            in_channels (int): number of input channels
            layers (list): feature dimensions of each FCN layer
            dilation (int): dilation rate of kernel
            norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None
        r   r   )Zkernel_sizeZstridepaddingdilationrQ   fan_outrelumodeZnonlinearityN)appendmisc_nn_opsZConv2dNormActivationr9   r:   modulesr2   r   Conv2dinitkaiming_normal_weightbiasZzeros_)	r>   in_channelsZlayersrS   rQ   blocksZnext_featureZlayer_featuresZlayerrG   rI   rJ   r:     s*    
zMaskRCNNHeads.__init__c              	      s   | dd }|d ks|dk r|t| }	t|	D ]N}
dD ]D}| d|
d  d| }| |
 d| }||kr4||||< q4q,t ||||||| d S )Nversionr   )r^   r_   Zmask_fcnr   .z.0.)getlenrangepopr9   _load_from_state_dict)r>   Z
state_dictprefixZlocal_metadatastrictZmissing_keysZunexpected_keysZ
error_msgsrb   Z
num_blocksir3   Zold_keyZnew_keyrG   rI   rJ   rh   .  s$    
z#MaskRCNNHeads._load_from_state_dict)N)rK   rL   rM   _versionr   r   r   Moduler:   rh   rO   rI   rI   rG   rJ   r7     s   "r7   c                       s   e Zd Z fddZ  ZS )r8   c                    sv   t  tdt||dddfdtjddfdt||dddfg |  D ]"\}}d	|krNtjj	|d
dd qNd S )NZ
conv5_maskr   r   rU   T)ZinplaceZmask_fcn_logitsr   r^   rT   rV   )
r9   r:   r   r   ZConvTranspose2dZReLUr[   Znamed_parametersr\   r]   )r>   r`   Zdim_reducedr@   nameparamrG   rI   rJ   r:   O  s    
zMaskRCNNPredictor.__init__)rK   rL   rM   r:   rO   rI   rI   rG   rJ   r8   N  s   r8   )r   r   )
categoriesrA   c                
   @   s6   e Zd Zedeeddddddidd	d
ZeZdS )r   zKhttps://download.pytorch.org/models/maskrcnn_resnet50_fpn_coco-bf2d0c1e.pthizKhttps://github.com/pytorch/vision/tree/main/references/detection#mask-r-cnnCOCO-val2017g33333B@gLA@Zbox_mapZmask_mapzSThese weights were produced by following a similar training recipe as on the paper.Z
num_paramsZrecipeZ_metricsZ_docsurlZ
transformsmetaNrK   rL   rM   r   r
   _COMMON_METACOCO_V1DEFAULTrI   rI   rI   rJ   r   g  s   c                
   @   s6   e Zd Zedeeddddddidd	d
ZeZdS )r   zNhttps://download.pytorch.org/models/maskrcnn_resnet50_fpn_v2_coco-73cbd019.pthiqcz+https://github.com/pytorch/vision/pull/5773rq   g33333G@gfffffD@rr   zZThese weights were produced using an enhanced training recipe to boost the model accuracy.rs   rt   Nrw   rI   rI   rI   rJ   r   {  s   Z
pretrainedZpretrained_backbone)weightsweights_backboneNT)r{   progressr@   r|   trainable_backbone_layers)r{   r}   r@   r|   r~   rF   returnc           
      K   s   t | } t|}| dk	r6d}t|t| jd }n|dkrBd}| dk	pP|dk	}t||dd}|rjtjnt	j
}t|||d}t||}t|fd|i|}	| dk	r|	| j|d | t jkrt|	d	 |	S )
a@  Mask R-CNN model with a ResNet-50-FPN backbone from the `Mask R-CNN
    <https://arxiv.org/abs/1703.06870>`_ paper.

    .. betastatus:: detection module

    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
        - masks (``UInt8Tensor[N, H, W]``): the segmentation binary masks for each instance

    The model returns a ``Dict[Tensor]`` during training, containing the classification and regression
    losses for both the RPN and the R-CNN, and the mask loss.

    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 detected instances:

        - 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 instance
        - scores (``Tensor[N]``): the scores or each instance
        - masks (``UInt8Tensor[N, 1, H, W]``): the predicted masks for each instance, in ``0-1`` range. In order to
          obtain the final segmentation masks, the soft masks can be thresholded, generally
          with a value of 0.5 (``mask >= 0.5``)

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

    Mask R-CNN is exportable to ONNX for a fixed batch size with inputs images of fixed size.

    Example::

        >>> model = torchvision.models.detection.maskrcnn_resnet50_fpn(weights=MaskRCNN_ResNet50_FPN_Weights.DEFAULT)
        >>> model.eval()
        >>> x = [torch.rand(3, 300, 400), torch.rand(3, 500, 400)]
        >>> predictions = model(x)
        >>>
        >>> # optionally, if you want to export the model to ONNX:
        >>> torch.onnx.export(model, x, "mask_rcnn.onnx", opset_version = 11)

    Args:
        weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): 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.mask_rcnn.MaskRCNN``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/mask_rcnn.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_Weights
        :members:
    Nrp   [      r   )r{   r}   rQ   r@   r}   r(   )r   verifyr   r   re   rv   r   rY   ZFrozenBatchNorm2dr   BatchNorm2dr   r   r   load_state_dictget_state_dictry   r   )
r{   r}   r@   r|   r~   rF   
is_trainedrQ   r?   modelrI   rI   rJ   r     s$    R




c                 K   s  t | } t|}| dk	r6d}t|t| jd }n|dkrBd}| dk	pP|dk	}t||dd}t||d}t||t	j
d}t }t|j| d d	d
}	t|jddfddddgdgt	j
d}
t|jddddgdt	j
d}t|f|||	|
|d|}| dk	r|| j|d |S )a  Improved Mask R-CNN model with a ResNet-50-FPN backbone from the `Benchmarking Detection Transfer
    Learning with Vision Transformers <https://arxiv.org/abs/2111.11429>`_ paper.

    .. betastatus:: detection module

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

    Args:
        weights (:class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights`, optional): The
            pretrained weights to use. See
            :class:`~torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights` below for
            more details, and possible values. By default, no pre-trained
            weights are used.
        progress (bool, optional): 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.mask_rcnn.MaskRCNN``
            base class. Please refer to the `source code
            <https://github.com/pytorch/vision/blob/main/torchvision/models/detection/mask_rcnn.py>`_
            for more details about this class.

    .. autoclass:: torchvision.models.detection.MaskRCNN_ResNet50_FPN_V2_Weights
        :members:
    Nrp   r   r   r   )r{   r}   rP   r   r   )Z
conv_depth   r&   i   r   )r@   rC   rD   rE   r<   r   )r   r   r   r   re   rv   r   r   r   r   r   r   r   r6   Znum_anchors_per_locationr   r7   r   r   r   )r{   r}   r@   r|   r~   rF   r   r?   rC   rD   rE   r<   r   rI   rI   rJ   r     sD    &


 
  

)
_ModelURLsZmaskrcnn_resnet50_fpn_coco)4collectionsr   typingr   r   r   Ztorchr   Ztorchvision.opsr   opsr	   rY   Ztransforms._presetsr
   Z_apir   r   Z_metar   _utilsr   r   Zresnetr   r   r   Zbackbone_utilsr   r   Zfaster_rcnnr   r   r   r   __all__r   Z
Sequentialr7   r8   rx   r   r   ry   ZIMAGENET1K_V1boolintr   r   r   ru   Z
model_urlsrI   rI   rI   rJ   <module>   s   	 rBiK 