
    x h!                         d dl mZ d dlmZmZ d dlmc mZ d dl	mZm
Z
 ddlmZ ddlmZ  G d d	ej                        Z G d
 dej                        Z G d de      Z G d de      Zy)    )OrderedDict)CallableOptionalN)nnTensor   )Conv2dNormActivation)_log_api_usage_oncec                   P    e Zd ZdZdee   dee   dee   deee   ee   f   fdZy)ExtraFPNBlocka  
    Base class for the extra block in the FPN.

    Args:
        results (List[Tensor]): the result of the FPN
        x (List[Tensor]): the original feature maps
        names (List[str]): the names for each one of the
            original feature maps

    Returns:
        results (List[Tensor]): the extended set of results
            of the FPN
        names (List[str]): the extended set of names for the results
    resultsxnamesreturnc                      y )N )selfr   r   r   s       /home/developers/rajanand/mypropertyqr-fmb-refixing-v2/venv/lib/python3.12/site-packages/torchvision/ops/feature_pyramid_network.pyforwardzExtraFPNBlock.forward   s     	    N	__name__
__module____qualname____doc__listr   strtupler   r   r   r   r   r      sP    f < Cy	
 
tF|T#Y&	'r   r   c                        e Zd ZdZdZ	 	 ddee   dedee   dee	de
j                  f      f fdZ fd	Zd
ededefdZd
ededefdZd
eeef   deeef   fdZ xZS )FeaturePyramidNetworkac  
    Module that adds a FPN from on top of a set of feature maps. This is based on
    `"Feature Pyramid Network for Object Detection" <https://arxiv.org/abs/1612.03144>`_.

    The feature maps are currently supposed to be in increasing depth
    order.

    The input to the model is expected to be an OrderedDict[Tensor], containing
    the feature maps on top of which the FPN will be added.

    Args:
        in_channels_list (list[int]): number of channels for each feature map that
            is passed to the module
        out_channels (int): number of channels of the FPN representation
        extra_blocks (ExtraFPNBlock or None): if provided, extra operations will
            be performed. It is expected to take the fpn features, the original
            features and the names of the original features as input, and returns
            a new list of feature maps and their corresponding names
        norm_layer (callable, optional): Module specifying the normalization layer to use. Default: None

    Examples::

        >>> m = torchvision.ops.FeaturePyramidNetwork([10, 20, 30], 5)
        >>> # get some dummy data
        >>> x = OrderedDict()
        >>> x['feat0'] = torch.rand(1, 10, 64, 64)
        >>> x['feat2'] = torch.rand(1, 20, 16, 16)
        >>> x['feat3'] = torch.rand(1, 30, 8, 8)
        >>> # compute the FPN on top of x
        >>> output = m(x)
        >>> print([(k, v.shape) for k, v in output.items()])
        >>> # returns
        >>>   [('feat0', torch.Size([1, 5, 64, 64])),
        >>>    ('feat2', torch.Size([1, 5, 16, 16])),
        >>>    ('feat3', torch.Size([1, 5, 8, 8]))]

    r   in_channels_listout_channelsextra_blocks
norm_layer.c           	         t         	|           t        |        t        j                         | _        t        j                         | _        |D ]i  }|dk(  rt        d      t        ||dd|d       }t        ||d|d       }| j
                  j                  |       | j                  j                  |       k | j                         D ]  }t        |t        j                        st        j                  j                  |j                  d       |j                   Vt        j                  j#                  |j                   d        |'t        |t$              st'        dt)        |             || _        y )	Nr   z(in_channels=0 is currently not supported   )kernel_sizepaddingr$   activation_layer   )r'   r$   r)   az1extra_blocks should be of type ExtraFPNBlock not )super__init__r
   r   
ModuleListinner_blockslayer_blocks
ValueErrorr	   appendmodules
isinstanceConv2dinitkaiming_uniform_weightbias	constant_r   	TypeErrortyper#   )
r   r!   r"   r#   r$   in_channelsinner_block_modulelayer_block_modulem	__class__s
            r   r.   zFeaturePyramidNetwork.__init__M   sM    	D!MMOMMO+ 
	9Ka !KLL!5\q!PZmq" "6ljcg" $$%78$$%78
	9  	1A!RYY'((Q(766%GG%%affa0		1 #lM:"STXYeTfSg hii(r   c           	      *   |j                  dd       }||dk  rdt        | j                        }	dD ]J  }
t        |	      D ]:  }dD ]3  }| |
 d| d| }| |
 d| d| }||v s |j	                  |      ||<   5 < L t
        |   |||||||       y )Nversionr   )r0   r1   )r9   r:   .z.0.)getlenr0   rangepopr-   _load_from_state_dict)r   
state_dictprefixlocal_metadatastrictmissing_keysunexpected_keys
error_msgsrD   
num_blocksblockir=   old_keynew_keyrB   s                  r   rJ   z+FeaturePyramidNetwork._load_from_state_dictp   s     !$$Y5?gkT../J9 Jz* JA 2 J%+HUG1QCq"?%+HUG1QCs4&"A"j02<..2IJw/	JJJ 	%	
r   r   idxr   c                     t        | j                        }|dk  r||z  }|}t        | j                        D ]  \  }}||k(  s ||      } |S )zs
        This is equivalent to self.inner_blocks[idx](x),
        but torchscript doesn't support this yet
        r   )rG   r0   	enumerater   r   rW   rR   outrT   modules          r   get_result_from_inner_blocksz2FeaturePyramidNetwork.get_result_from_inner_blocks   _    
 **+
7:C"4#4#45 	 IAvCxQi	  
r   c                     t        | j                        }|dk  r||z  }|}t        | j                        D ]  \  }}||k(  s ||      } |S )zs
        This is equivalent to self.layer_blocks[idx](x),
        but torchscript doesn't support this yet
        r   )rG   r1   rY   rZ   s          r   get_result_from_layer_blocksz2FeaturePyramidNetwork.get_result_from_layer_blocks   r^   r   c                    t        |j                               }t        |j                               }| j                  |d   d      }g }|j	                  | j                  |d             t        t        |      dz
  dd      D ]e  }| j                  ||   |      }|j                  dd }t        j                  ||d      }||z   }|j                  d| j                  ||             g | j                  | j                  |||      \  }}t        t        ||      D 	
cg c]	  \  }	}
|	|
f c}
}	      }|S c c}
}	w )a6  
        Computes the FPN for a set of feature maps.

        Args:
            x (OrderedDict[Tensor]): feature maps for each feature level.

        Returns:
            results (OrderedDict[Tensor]): feature maps after FPN layers.
                They are ordered from the highest resolution first.
        r   Nnearest)sizemoder   )r   keysvaluesr]   r3   r`   rH   rG   shapeFinterpolateinsertr#   r   zip)r   r   r   
last_innerr   rW   inner_lateral
feat_shapeinner_top_downkvr[   s               r   r   zFeaturePyramidNetwork.forward   s/    QVVX66qubA
t88RHIQ!R, 	RC ==afcJM&,,RS1J]]:JYWN&7JNN1d??
CPQ	R (!..w5ANGU c%.ABdaAq6BC
 Cs   "D:
)NN)r   r   r   r   _versionr   intr   r   r   r   Moduler.   rJ   r   r]   r`   dictr   r   __classcell__rB   s   @r   r    r    $   s    $L H 159=!)s)!) !) }-	!)
 Xc299n56!)F
@f 3 6 f 3 6  c6k*  tCK/@  r   r    c                   P    e Zd ZdZdee   dee   dee   deee   ee   f   fdZy)LastLevelMaxPoolzh
    Applies a max_pool2d (not actual max_pool2d, we just subsample) on top of the last feature map
    r   yr   r   c                     |j                  d       |j                  t        j                  |d   ddd             ||fS )Npoolrb   r&   r   r   )r'   strider(   )r3   rj   
max_pool2d)r   r   r|   r   s       r   r   zLastLevelMaxPool.forward   s8     	V	ae1aHI%xr   Nr   r   r   r   r{   r{      sP    	<	 <	 Cy		
 
tF|T#Y&	'	r   r{   c                   l     e Zd ZdZdedef fdZdee   dee   dee   de	ee   ee   f   fd	Z
 xZS )
LastLevelP6P7zO
    This module is used in RetinaNet to generate extra layers, P6 and P7.
    r>   r"   c                    t         |           t        j                  ||ddd      | _        t        j                  ||ddd      | _        | j                  | j
                  fD ]W  }t        j                  j                  |j                  d       t        j                  j                  |j                  d       Y ||k(  | _        y )Nr*   r   r&   r+   r   )r-   r.   r   r6   p6p7r7   r8   r9   r;   r:   use_P5)r   r>   r"   r\   rB   s       r   r.   zLastLevelP6P7.__init__   s    ))Kq!Q?))L,1a@ww( 	.FGG$$V]]a$8GGfkk1-	. "\1r   pcr   r   c                     |d   |d   }}| j                   r|n|}| j                  |      }| j                  t        j                  |            }|j                  ||g       |j                  ddg       ||fS )Nrb   r   r   )r   r   r   rj   reluextend)	r   r   r   r   p5c5r   r   r   s	            r   r   zLastLevelP6P7.forward   sn     2"B++B2WWQZWWQVVBZ 	"bdD\"%xr   )r   r   r   r   ru   r.   r   r   r   r   r   rx   ry   s   @r   r   r      sd    2C 2s 2< < Cy	
 
tF|T#Y&	'r   r   )collectionsr   typingr   r   torch.nn.functionalr   
functionalrj   torchr   ops.miscr	   utilsr
   rv   r   r    r{   r   r   r   r   <module>r      sU    # %    + 'BII 2hBII hV} "M r   