Ë
    þÍ:j¡‘  ã                   ó€  — 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
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,m-Z- ddl.m/Z/ g d¢Z0de1e   defd„Z2d„ Z3d„ Z4 G d„ dejj                  «      Z6 G d„ dejj                  «      Z7 G d „ d!ejj                  «      Z8 G d"„ d#ejj                  «      Z9ed$d%œZ: G d&„ d'e«      Z; G d(„ d)e«      Z< e«        e!d*e;jz                  fd+e$j|                  f¬,«      dd-de$j|                  dd.œd/e	e;   d0e?d1e	e@   d2e	e$   d3e	e@   d4ede9fd5„«       «       ZA e«        e!d*e<jz                  fd+e$j|                  f¬,«      dd-dddd.œd/e	e<   d0e?d1e	e@   d2e	e$   d3e	e@   d4ede9fd6„«       «       ZBy)7é    N)ÚOrderedDict)Úpartial)ÚAnyÚCallableÚOptional)Ú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                 ó.   — | d   }| dd  D ]  }||z   }Œ	 |S )Nr   r   © )r'   ÚresÚis      ú{/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/torchvision/models/detection/retinanet.pyÚ_sumr.   "   s.   € Ø
ˆA‰$€CØˆqˆrˆUò ˆØ�A‰g‰ðà€Jó    c                 ó’   — t        d«      D ]9  }dD ]2  }|› dd|z  › d|› �}|› d|› d|› �}|| v sŒ| j                  |«      | |<   Œ4 Œ; y )Né   )ÚweightÚbiaszconv.r   ú.z.0.)ÚrangeÚpop)Ú
state_dictÚprefixr,   ÚtypeÚold_keyÚnew_keys         r-   Ú_v1_to_v2_weightsr<   )   so   € Ü�1‹Xò >ˆØ&ò 	>ˆDØ˜  a¨¡c U¨!¨D¨6Ð2ˆGØ˜  a S¨¨D¨6Ð2ˆGØ˜*Ò$Ø&0§n¡n°WÓ&=�
˜7Ò#ñ		>ñ>r/   c                  ó^   — t        d„ dD «       «      } dt        | «      z  }t        | |«      }|S )Nc              3   óV   K  — | ]!  }|t        |d z  «      t        |dz  «      f–— Œ# y­w)g‹r�ù¢(ô?g<n=¥þeù?N)Úint)Ú.0r'   s     r-   ú	<genexpr>z%_default_anchorgen.<locals>.<genexpr>3   s,   è ø€ ÒpÐST˜!œS  ^Ñ!3Ó4´c¸!¸nÑ:LÓ6MÔNÑpùs   ‚'))é    é@   é€   é   i   ))ç      à?ç      ð?g       @)ÚtupleÚlenr   )Úanchor_sizesÚaspect_ratiosÚanchor_generators      r-   Ú_default_anchorgenrM   2   s5   € ÜÑpÐXoÔpÓp€LØ&¬¨\Ó):Ñ:€MÜ& |°]ÓCÐØÐr/   c                   óZ   ‡ — e Zd ZdZddeedej                  f      fˆ fd„Zd„ Z	d„ Z
ˆ x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
    Ú
norm_layer.c                 óp   •— t         ‰| �  «        t        ||||¬«      | _        t	        |||¬«      | _        y )N©rP   )ÚsuperÚ__init__ÚRetinaNetClassificationHeadÚclassification_headÚRetinaNetRegressionHeadÚregression_head)ÚselfÚin_channelsÚnum_anchorsÚnum_classesrP   Ú	__class__s        €r-   rT   zRetinaNetHead.__init__D   s8   ø€ Ü‰ÑÔÜ#>Ø˜ k¸jô$
ˆÔ ô  7°{ÀKÐ\fÔgˆÕr/   c                 óz   — | j                   j                  |||«      | j                  j                  ||||«      dœS )N)ÚclassificationÚbbox_regression)rV   Úcompute_lossrX   )rY   ÚtargetsÚhead_outputsÚanchorsÚmatched_idxss        r-   ra   zRetinaNetHead.compute_lossK   sC   € ð #×6Ñ6×CÑCÀGÈ\Ð[gÓhØ#×3Ñ3×@Ñ@ÀÈ,ÐX_ÐamÓnñ
ð 	
r/   c                 óH   — | j                  |«      | j                  |«      dœS )N)Ú
cls_logitsr`   )rV   rX   )rY   r'   s     r-   ÚforwardzRetinaNetHead.forwardR   s$   € à"×6Ñ6°qÓ9Èd×NbÑNbÐcdÓNeÑfÐfr/   ©N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   ÚModulerT   ra   rh   Ú__classcell__©r]   s   @r-   rO   rO   9   s9   ø„ ññhÈ(ÐS[Ð\_Ðac×ajÑajÐ\jÑSkÑJlõ hò
ögr/   rO   c                   ól   ‡ — e Zd ZdZdZ	 	 d	deedej                  f      fˆ fd„Z	ˆ fd„Z
d„ Zd„ Zˆ xZS )
rU   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   rP   .c                 óî  •— t         ‰	| �  «        g }t        d«      D ])  }|j                  t	        j
                  |||¬«      «       Œ+ t        j                  |Ž | _        | j                  j                  «       D ]“  }t        |t        j                  «      sŒt        j                  j                  j                  |j                  d¬«       |j                   €Œ`t        j                  j                  j#                  |j                   d«       Œ• t        j                  |||z  ddd¬«      | _        t        j                  j                  j                  | j$                  j                  d¬«       t        j                  j                  j#                  | j$                  j                   t'        j(                  d|z
  |z  «       «       || _        || _        t.        j0                  j2                  | _        y )	Nr1   rR   ç{®Gáz„?©Ústdr   r
   r   ©Úkernel_sizeÚstrideÚpadding)rS   rT   r5   ÚappendÚmisc_nn_opsÚConv2dNormActivationr   Ú
SequentialÚconvÚmodulesÚ
isinstanceÚConv2dÚtorchÚinitÚnormal_r2   r3   Ú	constant_rg   ÚmathÚlogr\   r[   Ú	det_utilsÚMatcherÚBETWEEN_THRESHOLDS)
rY   rZ   r[   r\   Úprior_probabilityrP   r~   Ú_Úlayerr]   s
            €r-   rT   z$RetinaNetClassificationHead.__init__d   sl  ø€ ô 	‰ÑÔàˆÜ�q“ò 	kˆAØ�K‰Kœ×8Ñ8¸ÀkÐ^hÔiÕjð	kä—M‘M 4Ð(ˆŒ	à—Y‘Y×&Ñ&Ó(ò 	;ˆEÜ˜%¤§¡Õ+Ü—‘—‘×%Ñ% e§l¡l¸Ð%Ô=Ø—:‘:Ñ)Ü—H‘H—M‘M×+Ñ+¨E¯J©J¸Õ:ð		;ô Ÿ)™) K°¸{Ñ1JÐXYÐbcÐmnÔoˆŒÜ�‰�‰×Ñ˜dŸo™o×4Ñ4¸$ÐÔ?Ü�‰�‰×Ñ §¡× 4Ñ 4´t·x±xÀÐEVÑAVÐZkÑ@kÓ7lÐ6lÔmà&ˆÔØ&ˆÔô
 #,×"3Ñ"3×"FÑ"FˆÕr/   c           	      óz   •— |j                  dd «      }|�|dk  rt        ||«       t        ‰	| �  |||||||«       y ©NÚversionr   ©Úgetr<   rS   Ú_load_from_state_dict©
rY   r7   r8   Úlocal_metadataÚstrictÚmissing_keysÚunexpected_keysÚ
error_msgsr�   r]   s
            €r-   r“   z1RetinaNetClassificationHead._load_from_state_dict…   óN   ø€ ð !×$Ñ$ Y°Ó5ˆàˆ?˜g¨škÜ˜j¨&Ô1ä‰Ñ%ØØØØØØØõ	
r/   c                 ó\  — g }|d   }t        |||«      D ]  \  }}}|dk\  }	|	j                  «       }
t        j                  |«      }d||	|d   ||	      f<   || j                  k7  }|j                  t        ||   ||   d¬«      t        d|
«      z  «       Œ� t        |«      t        |«      z  S )Nrg   r   rG   ÚlabelsÚsum)Ú	reductionr   )
Úzipr�   r‚   Ú
zeros_likerŠ   rz   r   Úmaxr.   rI   )rY   rb   rc   re   Úlossesrg   Útargets_per_imageÚcls_logits_per_imageÚmatched_idxs_per_imageÚforeground_idxs_per_imageÚnum_foregroundÚgt_classes_targetÚvalid_idxs_per_images                r-   ra   z(RetinaNetClassificationHead.compute_lossž   só   € àˆà! ,Ñ/ˆ
äORÐSZÐ\fÐhtÓOuò 	ÑKÐÐ3Ð5Kà(>À!Ñ(CÐ%Ø6×:Ñ:Ó<ˆNô !&× 0Ñ 0Ð1EÓ FÐð ð Ø)Ø! (Ñ+Ð,BÐC\Ñ,]Ñ^ð`ñð $:¸T×=TÑ=TÑ#TÐ ð �M‰MÜ"Ø(Ð)=Ñ>Ø%Ð&:Ñ;Ø#ôô
 �a˜Ó(ñ)õð!	ô2 �F‹|œc '›lÑ*Ð*r/   c                 ól  — g }|D ]—  }| j                  |«      }| j                  |«      }|j                  \  }}}}|j                  |d| j                  ||«      }|j                  ddddd«      }|j                  |d| j                  «      }|j                  |«       Œ™ t        j                  |d¬«      S )Néÿÿÿÿr   r
   r1   r   r   ©Údim)
r~   rg   ÚshapeÚviewr\   ÚpermuteÚreshaperz   r‚   Úcat)	rY   r'   Úall_cls_logitsÚfeaturesrg   ÚNrŒ   ÚHÚWs	            r-   rh   z#RetinaNetClassificationHead.forward¿   s¶   € àˆàò 
	.ˆHØŸ™ 8Ó,ˆJØŸ™¨Ó4ˆJð $×)Ñ)‰JˆAˆq�!�QØ#Ÿ™¨¨B°×0@Ñ0@À!ÀQÓGˆJØ#×+Ñ+¨A¨q°!°Q¸Ó:ˆJØ#×+Ñ+¨A¨r°4×3CÑ3CÓDˆJà×!Ñ! *Õ-ð
	.ô �y‰y˜¨QÔ/Ð/r/   )rs   N)rj   rk   rl   rm   Ú_versionr   r   r   rn   rT   r“   ra   rh   ro   rp   s   @r-   rU   rU   W   sK   ø„ ñð €Hð Ø9=ñGð ˜X c¨2¯9©9 nÑ5Ñ6õGôB
ò2+öB0r/   rU   c                   ó„   ‡ — e Zd ZdZdZdej                  iZd
dee	de
j                  f      fˆ fd„Zˆ fd„Zd„ Zd	„ Zˆ xZS )rW   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_coderrP   .c                 ó   •— t         ‰| �  «        g }t        d«      D ])  }|j                  t	        j
                  |||¬«      «       Œ+ t        j                  |Ž | _        t        j                  ||dz  ddd¬«      | _
        t        j                  j                  j                  | j                  j                  d¬«       t        j                  j                  j                  | j                  j                   «       | j                  j#                  «       D ]’  }t%        |t        j                  «      sŒt        j                  j                  j                  |j                  d¬«       |j                   €Œ`t        j                  j                  j                  |j                   «       Œ” t'        j(                  d¬	«      | _        d
| _        y )Nr1   rR   r
   r   rv   rs   rt   ©rG   rG   rG   rG   ©ÚweightsÚl1)rS   rT   r5   rz   r{   r|   r   r}   r~   r�   Úbbox_regr‚   rƒ   r„   r2   Úzeros_r3   r   r€   rˆ   ÚBoxCoderrº   Ú
_loss_type)rY   rZ   r[   rP   r~   rŒ   r�   r]   s          €r-   rT   z RetinaNetRegressionHead.__init__â   s@  ø€ Ü‰ÑÔàˆÜ�q“ò 	kˆAØ�K‰Kœ×8Ñ8¸ÀkÐ^hÔiÕjð	kä—M‘M 4Ð(ˆŒ	äŸ	™	 +¨{¸Q©ÈAÐVWÐabÔcˆŒÜ�‰�‰×Ñ˜dŸm™m×2Ñ2¸ÐÔ=Ü�‰�‰×Ñ˜TŸ]™]×/Ñ/Ô0à—Y‘Y×&Ñ&Ó(ò 	5ˆEÜ˜%¤§¡Õ+Ü—‘—‘×%Ñ% e§l¡l¸Ð%Ô=Ø—:‘:Ñ)Ü—H‘H—M‘M×(Ñ(¨¯©Õ4ð		5ô #×+Ñ+Ð4HÔIˆŒØˆ�r/   c           	      óz   •— |j                  dd «      }|�|dk  rt        ||«       t        ‰	| �  |||||||«       y r�   r‘   r”   s
            €r-   r“   z-RetinaNetRegressionHead._load_from_state_dict÷   rš   r/   c           
      ó�  — g }|d   }t        ||||«      D ]Ž  \  }}}	}
t        j                  |
dk\  «      d   }|j                  «       }|d   |
|      }||d d …f   }|	|d d …f   }	|j	                  t        | j                  | j                  |	||«      t        d|«      z  «       Œ� t        |«      t        dt        |«      «      z  S )Nr`   r   r   r   )rŸ   r‚   ÚwhereÚnumelrz   r   rÃ   rº   r¡   r.   rI   )rY   rb   rc   rd   re   r¢   r`   r£   Úbbox_regression_per_imageÚanchors_per_imager¥   r¦   r§   Úmatched_gt_boxes_per_images                 r-   ra   z$RetinaNetRegressionHead.compute_loss  sþ   € àˆà&Ð'8Ñ9ˆägjØ�_ g¨|óh
ò 	ÑcÐÐ8Ð:KÐMcô ).¯©Ð4JÈaÑ4OÓ(PÐQRÑ(SÐ%Ø6×<Ñ<Ó>ˆNð *;¸7Ñ)CÐDZÐ[tÑDuÑ)vÐ&Ø(AÐB[Ò]^ÐB^Ñ(_Ð%Ø 1Ð2KÊQÐ2NÑ OÐð �M‰MÜØ—O‘OØ—N‘NØ%Ø.Ø-óô �a˜Ó(ñ)õ	ð	ô0 �F‹|œc !¤S¨£\Ó2Ñ2Ð2r/   c                 óD  — g }|D ]ƒ  }| j                  |«      }| j                  |«      }|j                  \  }}}}|j                  |dd||«      }|j	                  ddddd«      }|j                  |dd«      }|j                  |«       Œ… t        j                  |d¬«      S )Nr«   r1   r   r
   r   r   r¬   )	r~   rÀ   r®   r¯   r°   r±   rz   r‚   r²   )	rY   r'   Úall_bbox_regressionr´   r`   rµ   rŒ   r¶   r·   s	            r-   rh   zRetinaNetRegressionHead.forward0  s®   € à Ðàò 
	8ˆHØ"Ÿi™i¨Ó1ˆOØ"Ÿm™m¨OÓ<ˆOð )×.Ñ.‰JˆAˆq�!�QØ-×2Ñ2°1°b¸!¸QÀÓBˆOØ-×5Ñ5°a¸¸A¸qÀ!ÓDˆOØ-×5Ñ5°a¸¸QÓ?ˆOà×&Ñ& Õ7ð
	8ô �y‰yÐ,°!Ô4Ð4r/   ri   )rj   rk   rl   rm   r¸   rˆ   rÂ   Ú__annotations__r   r   r   rn   rT   r“   ra   rh   ro   rp   s   @r-   rW   rW   Ò   sT   ø„ ñð €Hð 	�Y×'Ñ'ð€Oñ¸XÀhÈsÐTV×T]ÑT]È~ÑF^Ñ=_õ ô*
ò23ö@5r/   rW   c                   ó¼   ‡ — e Zd ZdZej
                  ej                  dœZ	 	 	 	 	 	 	 	 	 	 	 	 	 dˆ fd„	Ze	j                  j                  d„ «       Zd„ Zd„ Zd	d„Zˆ xZS )
r"   a4  
    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): Images are rescaled before feeding them to the backbone:
            we attempt to preserve the aspect ratio and scale the shorter edge
            to ``min_size``. If the resulting longer edge exceeds ``max_size``,
            then downscale so that the longer edge does not exceed ``max_size``.
            This may result in the shorter edge beeing lower than ``min_size``.
        max_size (int): See ``min_size``.
        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_matcherc                 ó^  •— t         ‰| �  «        t        | «       t        |d«      st	        d«      ‚|| _        t        |t        t        d «      f«      st        dt        |«      › �«      ‚|€
t        «       }|| _        |€(t        |j                  |j                  «       d   |«      }|| _        |	€t!        j"                  ||d¬«      }	|	| _        t!        j&                  d¬«      | _        |€g d	¢}|€g d
¢}t+        ||||fi |¤Ž| _        |
| _        || _        || _        || _        d| _        y )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)Úallow_low_quality_matchesr¼   r½   )g
×£p=
ß?gÉv¾Ÿ/Ý?g–C‹lçûÙ?)gZd;ßOÍ?gyé&1¬Ì?gÍÌÌÌÌÌÌ?F)rS   rT   r   ÚhasattrÚ
ValueErrorÚbackboner€   r   r9   Ú	TypeErrorrM   rL   rO   rÑ   Únum_anchors_per_locationÚheadrˆ   r‰   rÏ   rÂ   rº   r!   Ú	transformÚscore_threshÚ
nms_threshÚdetections_per_imgÚtopk_candidatesÚ_has_warned)rY   rÕ   r\   Úmin_sizeÚmax_sizeÚ
image_meanÚ	image_stdrL   rØ   rÏ   rÚ   rÛ   rÜ   Úfg_iou_threshÚbg_iou_threshrÝ   Úkwargsr]   s                    €r-   rT   zRetinaNet.__init__¡  sO  ø€ ô* 	‰ÑÔÜ˜DÔ!ä�x Ô0Üð+óð ð
 !ˆŒäÐ*¬_¼dÀ4»jÐ,IÔJÜØXÔY]Ð^nÓYoÐXpÐqóð ð Ð#Ü1Ó3ÐØ 0ˆÔàˆ<Ü  ×!6Ñ!6Ð8H×8aÑ8aÓ8cÐdeÑ8fÐhsÓtˆDØˆŒ	àÐ#Ü(×0Ñ0ØØØ*.ô Ðð
 !1ˆÔä"×+Ñ+Ð4HÔIˆŒàÐÚ.ˆJØÐÚ-ˆIÜ1°(¸HÀjÐR[ÑfÐ_eÑfˆŒà(ˆÔØ$ˆŒØ"4ˆÔØ.ˆÔð !ˆÕr/   c                 ó"   — | j                   r|S |S ri   )Útraining)rY   r¢   Ú
detectionss      r-   Úeager_outputszRetinaNet.eager_outputsæ  s   € ð �=Š=ØˆMàÐr/   c           	      óª  — g }t        ||«      D ]¥  \  }}|d   j                  «       dk(  rQ|j                  t        j                  |j                  d«      fdt        j                  |j                  ¬«      «       Œmt        j                  |d   |«      }|j                  | j                  |«      «       Œ§ | j                  j                  ||||«      S )Nr   r   r«   )ÚdtypeÚdevice)rŸ   rÇ   rz   r‚   ÚfullÚsizeÚint64rì   Úbox_opsÚbox_iourÏ   rØ   ra   )rY   rb   rc   rd   re   rÉ   r£   Úmatch_quality_matrixs           r-   ra   zRetinaNet.compute_lossî  sÊ   € àˆÜ47¸ÀÓ4Iò 	MÑ0ÐÐ0Ø  Ñ)×/Ñ/Ó1°QÒ6Ø×#Ñ#Ü—J‘JÐ 1× 6Ñ 6°qÓ 9Ð;¸RÄuÇ{Á{Ð[l×[sÑ[sÔtôð ä#*§?¡?Ð3DÀWÑ3MÐO`Ó#aÐ Ø×Ñ × 5Ñ 5Ð6JÓ KÕLð	Mð �y‰y×%Ñ% g¨|¸WÀlÓSÐSr/   c                 ól  — |d   }|d   }t        |«      }g }t        |«      D �]  }|D �	cg c]  }	|	|   ‘Œ	 }
}	|D �cg c]  }||   ‘Œ	 }}||   ||   }}g }g }g }t        |
||«      D �]'  \  }}}|j                  d   }t	        j
                  |«      j                  «       }|| j                  kD  }||   }t	        j                  |«      d   }t        j                  || j                  d«      }|j                  |«      \  }}||   }t	        j                  ||d¬«      }||z  }| j                  j                  ||   ||   «      }t!        j"                  ||«      }|j%                  |«       |j%                  |«       |j%                  |«       �Œ* t	        j&                  |d¬«      }t	        j&                  |d¬«      }t	        j&                  |d¬«      }t!        j(                  |||| j*                  «      }|d | j,                   }|j%                  ||   ||   ||   dœ«       �Œ |S c c}	w c c}w )	Nrg   r`   r«   r   Úfloor)Úrounding_moder¬   )r   Úscoresrœ   )rI   r5   rŸ   r®   r‚   ÚsigmoidÚflattenrÚ   rÆ   rˆ   Ú	_topk_minrÝ   ÚtopkÚdivrº   Údecode_singlerð   Úclip_boxes_to_imagerz   r²   Úbatched_nmsrÛ   rÜ   )rY   rc   rd   Úimage_shapesÚclass_logitsÚbox_regressionÚ
num_imagesrè   ÚindexÚbrÚbox_regression_per_imageÚclÚlogits_per_imagerÉ   Úimage_shapeÚimage_boxesÚimage_scoresÚimage_labelsÚbox_regression_per_levelÚlogits_per_levelÚanchors_per_levelr\   Úscores_per_levelÚ	keep_idxsÚ	topk_idxsÚnum_topkÚidxsÚanchor_idxsÚlabels_per_levelÚboxes_per_levelÚkeeps                                  r-   Úpostprocess_detectionsz RetinaNet.postprocess_detectionsý  so  € à# LÑ1ˆØ%Ð&7Ñ8ˆä˜Ó&ˆ
à.0ˆ
ä˜:Ó&ó 3	ˆEØ<JÖ'K°b¨¨5«	Ð'KÐ$Ð'KØ4@ÖA¨b  5£	ÐAÐÐAØ-4°U©^¸\È%Ñ=P˜{ÐàˆKØˆLØˆLäQTØ(Ð*:Ð<MóRó 6ÑMÐ(Ð*:Ð<Mð /×4Ñ4°RÑ8�ô $)§=¡=Ð1AÓ#B×#JÑ#JÓ#LÐ Ø,¨t×/@Ñ/@Ñ@�	Ø#3°IÑ#>Ð Ü!ŸK™K¨	Ó2°1Ñ5�	ô %×.Ñ.¨y¸$×:NÑ:NÐPQÓR�Ø)9×)>Ñ)>¸xÓ)HÑ&Ð  $Ø% d™O�	ä#Ÿi™i¨	°;ÈgÔV�Ø#,¨{Ñ#:Ð à"&§.¡.×">Ñ">Ø,¨[Ñ9Ð;LÈ[Ñ;Yó#�ô #*×"=Ñ"=¸oÈ{Ó"[�à×"Ñ" ?Ô3Ø×#Ñ#Ð$4Ô5Ø×#Ñ#Ð$4Ö5ð56ô8  Ÿ)™) K°QÔ7ˆKÜ Ÿ9™9 \°qÔ9ˆLÜ Ÿ9™9 \°qÔ9ˆLô ×&Ñ& {°LÀ,ÐPT×P_ÑP_Ó`ˆDØÐ1˜$×1Ñ1Ð2ˆDà×Ñà(¨Ñ.Ø*¨4Ñ0Ø*¨4Ñ0ñöð[3	ðj Ðùòi (LùÚAs
   «H,½H1c           	      ó¸  — | j                   r“|€t        j                  dd«       nz|D ]u  }|d   }t        j                  t        |t        j                  «      d«       t        j                  t        |j                  «      dk(  xr |j                  d   dk(  d	«       Œw g }|D ]\  }|j                  d
d }t        j                  t        |«      dk(  d|j                  d
d › �«       |j                  |d   |d   f«       Œ^ | j                  ||«      \  }}|�›t        |«      D ]�  \  }}|d   }|dd…dd…f   |dd…dd…f   k  }	|	j                  «       sŒ3t        j                  |	j                  d¬«      «      d   d   }
||
   j                  «       }t        j                  dd|› d|› d�«       Œ� | j                  |j                  «      }t        |t        j                  «      rt        d|fg«      }t!        |j#                  «       «      }| j%                  |«      }| j'                  ||«      }i }g }| j                   r.|€t        j                  dd«       �n| j)                  |||«      }nÿ|D �cg c]%  }|j+                  d«      |j+                  d«      z  ‘Œ' }}d}|D ]  }||z  }Œ	 |d   j+                  d«      }||z  }|D �cg c]  }||z  ‘Œ	 }}i }|D ]$  }t!        ||   j-                  |d¬«      «      ||<   Œ& |D �cg c]  }t!        |j-                  |«      «      ‘Œ }}| j/                  |||j0                  «      }| j                  j3                  ||j0                  |«      }t        j4                  j7                  «       r,| j8                  st;        j<                  d«       d| _        ||fS | j?                  ||«      S c c}w c c}w c c}w )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«   r1   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 r4   Ú0r
   rg   zBRetinaNet always returns a (Losses, Detections) tuple in scriptingT) rç   r‚   Ú_assertr€   r	   rI   r®   rz   rÙ   Ú	enumerateÚanyrÆ   ÚtolistrÕ   Útensorsr   ÚlistÚvaluesrØ   rL   ra   rî   Úsplitr  Úimage_sizesÚpostprocessÚjitÚis_scriptingrÞ   ÚwarningsÚwarnré   )rY   Úimagesrb   Útargetr   Úoriginal_image_sizesÚimgÚvalÚ
target_idxÚdegenerate_boxesÚbb_idxÚdegen_bbr´   rc   rd   r¢   rè   r'   Únum_anchors_per_levelÚHWÚvÚHWAÚAÚhwÚsplit_head_outputsÚkÚaÚsplit_anchorss                               r-   rh   zRetinaNet.forward=  sè  € ð �=Š=ØˆÜ—‘˜eÐ%WÕXà%ò �FØ" 7™O�EÜ—M‘M¤*¨U´E·L±LÓ"AÐCpÔqÜ—M‘MÜ˜EŸK™KÓ(¨AÑ-ÒF°%·+±+¸b±/ÀQÑ2FØOõðð 79ÐØò 	:ˆCØ—)‘)˜B˜C�.ˆCÜ�M‰MÜ�C“˜A‘Ø\Ð]`×]fÑ]fÐgiÐgjÐ]kÐ\lÐmôð !×'Ñ'¨¨Q©°°Q±Ð(8Õ9ð	:ð Ÿ.™.¨°Ó9‰ˆ�ð ÐÜ&/°Ó&8ò Ñ"�
˜FØ˜w™�Ø#(ª¨A©B¨¡<°5º¸B¸Q¸B¸±<Ñ#?Ð Ø#×'Ñ'Õ)ä"Ÿ[™[Ð)9×)=Ñ)=À!Ð)=Ó)DÓEÀaÑHÈÑK�FØ,1°&©M×,@Ñ,@Ó,B�HÜ—M‘MØð.Ø.6¨ZÐ7LÈZÈLÐXYð[õðð —=‘= §¡Ó0ˆÜ�h¤§¡Ô-Ü" S¨( OÐ#4Ó5ˆHô ˜Ÿ™Ó)Ó*ˆð —y‘y Ó*ˆð ×'Ñ'¨°Ó9ˆàˆØ.0ˆ
Ø�=Š=ØˆÜ—‘˜eÐ%WÖXð ×*Ñ*¨7°LÀ'ÓJ‘ð EMÖ$M¸q Q§V¡V¨A£Y°·±¸³Ó%:Ð$MÐ!Ð$MØˆBØ*ò �Ø�a‘‘ðà˜|Ñ,×1Ñ1°!Ó4ˆCØ�r‘	ˆAØ6KÖ$L° R¨!£VÐ$LÐ!Ð$Lð ;=ÐØ!ò b�Ü(,¨\¸!©_×-BÑ-BÐCXÐ^_Ð-BÓ-`Ó(aÐ" 1Ò%ðbàKRÖSÀaœT !§'¡'Ð*?Ó"@ÕAÐSˆMÐSð ×4Ñ4Ð5GÈÐX^×XjÑXjÓkˆJØŸ™×3Ñ3°JÀ×@RÑ@RÐThÓiˆJä�9‰9×!Ñ!Ô#Ø×#Ò#Ü—‘ÐbÔcØ#'�Ô Ø˜:Ð%Ð%Ø×!Ñ! &¨*Ó5Ð5ùò/ %Nùò %Mùò Ts   É6*OËOÌ
!O)i   i5  NNNNNgš™™™™™©?rF   i,  rF   gš™™™™™Ù?iè  ri   )rj   rk   rl   rm   rˆ   rÂ   r‰   rÍ   rT   r‚   r&  Úunusedré   ra   r  rh   ro   rp   s   @r-   r"   r"   C  s…   ø„ ñVðr ×'Ñ'Ø%×-Ñ-ñ€Oð ØØØàØØØØØØØØõ%C!ðJ ‡Y�Y×Ññó ðòTò>÷@f6r/   r"   )r   r   )Ú
categoriesrß   c                   óD   — e Zd Z edei e¥dddddiiddd	d
œ¥¬«      ZeZy)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.©Ú
num_paramsÚrecipeÚ_metricsÚ_opsÚ
_file_sizeÚ_docs©ÚurlÚ
transformsÚmetaN©rj   rk   rl   r   r   Ú_COMMON_METAÚCOCO_V1ÚDEFAULTr*   r/   r-   r#   r#   ¬  sN   „ ÙØZØ"ð
Øð
à"ØbàØ˜tð!ðð
 Ø!Ønò
ô€Gð" �Gr/   r#   c                   óD   — e Zd Z edei e¥dddddiiddd	d
œ¥¬«      ZeZy)r$   zOhttps://download.pytorch.org/models/retinanet_resnet50_fpn_v2_coco-5905b1c5.pthi—ÞFz+https://github.com/pytorch/vision/pull/5756r@  rA  g     ÀD@gV-²�c@gw¾Ÿ/Ab@zZThese weights were produced using an enhanced training recipe to boost the model accuracy.rB  rI  NrM  r*   r/   r-   r$   r$   Á  sN   „ ÙØ]Ø"ð
Øð
à"ØCàØ˜tð!ðð
 Ø!Øuò
ô€Gð" �Gr/   r$   Ú
pretrainedÚpretrained_backbone)r¾   Úweights_backboneT)r¾   Úprogressr\   rT  Útrainable_backbone_layersr¾   rU  r\   rT  rV  rå   c           	      ó  — t         j                  | «      } t        j                  |«      }| �&d}t        d|t	        | j
                  d   «      «      }n|€d}| duxs |du}t        ||dd«      }|rt        j                  nt        j                  }t        |||¬«      }t        ||g d¢t        d	d	«      ¬
«      }t        ||fi |¤Ž}	| �A|	j                  | j!                  |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:
    Nr\   r>  é[   é   r
   )r¾   rU  rP   ©r   r
   r1   rE   ©Úreturned_layersÚextra_blocksT©rU  Ú
check_hashg        )r#   Úverifyr   r   rI   rL  r    r{   ÚFrozenBatchNorm2dr   ÚBatchNorm2dr   r   r   r"   Úload_state_dictÚget_state_dictrO  r   )
r¾   rU  r\   rT  rV  rå   Ú
is_trainedrP   rÕ   Úmodels
             r-   r%   r%   Ö  s  € ôV -×3Ñ3°GÓ<€GÜ'×.Ñ.Ð/?Ó@ÐàÐØÐÜ+¨M¸;ÌÈGÏLÉLÐYeÑLfÓHgÓh‰Ø	Ð	Øˆà Ð$ÒDÐ(8ÀÐ(D€JÜ :¸:ÐG`ÐbcÐefÓ gÐÙ2<”×.Ò.Ä"Ç.Á.€JäÐ 0¸8ÐPZÔ[€Hä$ØÐ+ºYÔUbÐcfÐhkÓUlô€Hô �h Ñ6¨vÑ6€EàÐØ×Ñ˜g×4Ñ4¸hÐSWÐ4ÓXÔYØÔ4×<Ñ<Ò<Ü˜% Ô%à€Lr/   c           	      óT  — t         j                  | «      } t        j                  |«      }| �&d}t        d|t	        | j
                  d   «      «      }n|€d}| duxs |du}t        ||dd«      }t        ||¬«      }t        ||g d¢t        d	d
«      ¬«      }t        «       }t        |j                  |j                  «       d   |t        t        j                   d«      ¬«      }	d|	j"                  _        t'        ||f||	dœ|¤Ž}
| �"|
j)                  | j+                  |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:
    Nr\   r>  rX  rY  r
   )r¾   rU  rZ  i   rE   r[  r   rB   rR   Úgiou)rL   rØ   Tr^  )r$   r`  r   r   rI   rL  r    r   r   r   rM   rO   rÑ   r×   r   r   Ú	GroupNormrX   rÃ   r"   rc  rd  )r¾   rU  r\   rT  rV  rå   re  rÕ   rL   rØ   rf  s              r-   r&   r&   =  sD  € ôZ 0×6Ñ6°wÓ?€GÜ'×.Ñ.Ð/?Ó@ÐàÐØÐÜ+¨M¸;ÌÈGÏLÉLÐYeÑLfÓHgÓh‰Ø	Ð	Øˆà Ð$ÒDÐ(8ÀÐ(D€JÜ :¸:ÐG`ÐbcÐefÓ gÐäÐ 0¸8ÔD€HÜ$ØÐ+ºYÔUbÐcgÐilÓUmô€Hô *Ó+ÐÜØ×ÑØ×1Ñ1Ó3°AÑ6ØÜœ2Ÿ<™<¨Ó,ô	€Dð '-€D×ÑÔ#Ü�h ÐdÐ>NÐUYÑdÐ]cÑd€EàÐØ×Ñ˜g×4Ñ4¸hÐSWÐ4ÓXÔYà€Lr/   )Cr†   r(  Úcollectionsr   Ú	functoolsr   Útypingr   r   r   r‚   r   r	   Úopsr   rð   r   r{   r   Úops.feature_pyramid_networkr   Útransforms._presetsr   Úutilsr   Ú_apir   r   r   Ú_metar   r   r   r   Úresnetr   r   Ú rˆ   r   r   Úanchor_utilsr   Úbackbone_utilsr   r    rÙ   r!   Ú__all__r!  r.   r<   rM   rn   rO   rU   rW   r"   rN  r#   r$   rO  ÚIMAGENET1K_V1Úboolr?   r%   r&   r*   r/   r-   ú<module>rz     sT  ðÛ Û Ý #Ý ß *Ñ *ã ß ç LÑ LÝ 8Ý 2Ý (ß 7Ñ 7Ý $ß Cß /Ý !ß ,Ý )ß MÝ /ò€ðˆD�‰Lð ˜Vó ò>òôg�B—I‘Iô gô<x0 "§)¡)ô x0ôvn5˜bŸi™iô n5ôb`6�—	‘	ô `6ðH #Øñ€ô [ô ô*¨ô ñ* ÓÙØÐ9×AÑAÐBØ+Ð-=×-KÑ-KÐLôð 9=ØØ!%Ø3C×3QÑ3QØ/3ò_àÐ4Ñ5ð_ð ð_ð ˜#‘ð	_ð
 Ð/Ñ0ð_ð  (¨™}ð_ð ð_ð ò_ó	ó ð
_ñD ÓÙØÐ<×DÑDÐEØ+Ð-=×-KÑ-KÐLôð <@ØØ!%Ø37Ø/3òEàÐ7Ñ8ðEð ðEð ˜#‘ð	Eð
 Ð/Ñ0ðEð  (¨™}ðEð ðEð òEó	ó ñ
Er/   