
    %`i!                         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dS )    )OrderedDict)CallableOptionalN)nnTensor   )Conv2dNormActivation)_log_api_usage_oncec                   v    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dS )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                     d S )N )selfr   r   r   s       {/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/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      sv         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   Nin_channels_listout_channelsextra_blocks
norm_layer.c           	      4   t                                                       t          |            t          j                    | _        t          j                    | _        |D ]t}|dk    rt          d          t          ||dd|d           }t          ||d|d           }| j        	                    |           | j        	                    |           u| 
                                D ]n}t          |t          j                  rRt          j                            |j        d           |j        %t          j                            |j        d           o|4t          |t$                    st'          dt)          |                     || _        d S )	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   s    	D!!!MOOMOO+ 
	9 
	9Ka !KLLL!5\q!PZmq" " " "6ljcg" " " $$%7888$$%78888  	1 	1A!RY'' 1((Q(7776%G%%afa000#lM:: j hTXYeTfTf h hiii(r   c           	      Z   |                     dd           }||dk     rdt          | j                  }	dD ]M}
t          |	          D ];}dD ]6}| |
 d| d| }| |
 d| d| }||v r|                    |          ||<   7<Nt                                          |||||||           d S )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5?gkkT.//J9 J Jz** J JA 2 J J%+"?U"?"?Q"?"?"?"?%+"AU"A"AQ"A"A4"A"A"j002<..2I2IJw/	JJ 	%%	
 	
 	
 	
 	
r   r   idxr   c                     t          | j                  }|dk     r||z  }|}t          | j                  D ]\  }}||k    r ||          }|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   f    
 *++
77:C"4#455 	  	 IAvCxxfQii
r   c                     t          | j                  }|dk     r||z  }|}t          | j                  D ]\  }}||k    r ||          }|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          |                                          }t          |                                          }|                     |d         d          }g }|                    |                     |d                     t          t          |          dz
  dd          D ]s}|                     ||         |          }|j        dd         }t          j
        ||d          }||z   }|                    d|                     ||                     t| j        |                     |||          \  }}t          d t          ||          D                       }	|	S )	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   c                     g | ]	\  }}||f
S r   r   ).0kvs      r   
<listcomp>z1FeaturePyramidNetwork.forward.<locals>.<listcomp>   s     BBBdaAq6BBBr   )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_downr[   s
             r   r   zFeaturePyramidNetwork.forward   sU    QVVXX66qubAA
t88RHHIIIQ!R,, 	R 	RC ==afcJJM&,RSS1J]:JYWWWN&7JNN1d??
CPPQQQQ(!..w5AANGU BBc%.A.ABBBCC
r   )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)!) !) }-	!)
 Xc29n56!) !) !) !) !) !)F
 
 
 
 
@f 3 6    f 3 6     c6k*  tCK/@                r   r    c                   v    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dS )LastLevelMaxPoolzh
    Applies a max_pool2d (not actual max_pool2d, we just subsample) on top of the last feature map
    r   yr   r   c                     |                     d           |                     t          j        |d         ddd                     ||fS )Npoolrb   r&   r   r   )r'   strider(   )r3   ro   
max_pool2d)r   r   r   r   s       r   r   zLastLevelMaxPool.forward   sH     	V	ae1aHHHIII%xr   Nr   r   r   r   r~   r~      sv         	<	 <	 Cy		
 
tF|T#Y&	'	 	 	 	 	 	r   r~   c                        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 ]M}t          j                            |j        d           t          j        	                    |j
        d           N||k    | _        d S )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@@w( 	. 	.FG$$V]a$888Gfk1----!\1r   pcr   r   c                    |d         |d         }}| j         r|n|}|                     |          }|                     t          j        |                    }|                    ||g           |                    ddg           ||fS )Nrb   r   r   )r   r   r   ro   reluextend)	r   r   r   r   p5c5r   r   r   s	            r   r   zLastLevelP6P7.forward   s     2"B+%BB2WWQZZWWQVBZZ  	"bdD\"""%xr   )r   r   r   r   rx   r.   r   r   r   r   r   r{   r|   s   @r   r   r      s         2C 2s 2 2 2 2 2 2< < Cy	
 
tF|T#Y&	'       r   r   )collectionsr   typingr   r   torch.nn.functionalr   
functionalro   torchr   ops.miscr	   utilsr
   ry   r   r    r~   r   r   r   r   <module>r      sE   # # # # # # % % % % % % % %                  + + + + + + ' ' ' ' ' '    BI   2h h h h hBI h h hV    }   "    M     r   