o
    _{j  ã                   @   sb   d dl mZmZ d dlmZ d dlZd dlmZ d dl	m
Z
 ddlmZ G dd„ de
jed�ZdS )	é    )ÚABCMetaÚabstractmethod)ÚOrderedDictNé   )Úbuilderc                       sp   e Zd ZdZd‡ fdd„	Zdd„ Zdd„ Zed	d
„ ƒZedd„ ƒZ	ddd„Z
edd„ ƒZdd„ Zdd„ Z‡  ZS )ÚBaseLocalizerzìBase class for localizers.

    All localizers should subclass it. All subclass should overwrite:
    Methods:``forward_train``, supporting to forward when training.
    Methods:``forward_test``, supporting to forward when testing.
    Nc                    s:   t ƒ  ¡  t |¡| _t |¡| _|| _|| _|  	¡  d S ©N)
ÚsuperÚ__init__r   Úbuild_backboneÚbackboneÚ
build_headÚcls_headÚ	train_cfgÚtest_cfgÚinit_weights)Úselfr   r   r   r   ©Ú	__class__© ú5/root/disk_3tb/HAC/mmaction/models/localizers/base.pyr
      s   
zBaseLocalizer.__init__c                 C   s   | j  ¡  | j ¡  dS )z Weight initialization for model.N)r   r   r   )r   r   r   r   r      s   
zBaseLocalizer.init_weightsc                 C   s   |   |¡}|S )z²Extract features through a backbone.

        Args:
            imgs (torch.Tensor): The input images.
        Returns:
            torch.tensor: The extracted features.
        )r   )r   ÚimgsÚxr   r   r   Úextract_feat!   s   
zBaseLocalizer.extract_featc                 C   ó   dS )z.Defines the computation performed at training.Nr   )r   r   Úlabelsr   r   r   Úforward_train,   ó    zBaseLocalizer.forward_trainc                 C   r   )z-Defines the computation performed at testing.Nr   )r   r   r   r   r   Úforward_test0   r   zBaseLocalizer.forward_testTc                 K   s(   |r| j |fi |¤ŽS | j|fi |¤ŽS )z/Define the computation performed at every call.)r   r   )r   r   Úreturn_lossÚkwargsr   r   r   Úforward4   s   zBaseLocalizer.forwardc                 C   sÒ   t ƒ }|  ¡ D ](\}}t|tjƒr| ¡ ||< qt|tƒr)tdd„ |D ƒƒ||< qt|› d�ƒ‚tdd„ | ¡ D ƒƒ}||d< | ¡ D ]!\}}t	 
¡ r^t	 ¡ r^|j ¡ }t	 | t	 ¡ ¡¡ | ¡ ||< qC||fS )a°  Parse the raw outputs (losses) of the network.

        Args:
            losses (dict): Raw output of the network, which usually contain
                losses and other necessary information.

        Returns:
            tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor
                which may be a weighted sum of all losses, log_vars contains
                all the variables to be sent to the logger.
        c                 s   s   � | ]}|  ¡ V  qd S r   )Úmean)Ú.0Z_lossr   r   r   Ú	<genexpr>M   s   € z.BaseLocalizer._parse_losses.<locals>.<genexpr>z# is not a tensor or list of tensorsc                 s   s    � | ]\}}d |v r|V  qdS )ÚlossNr   )r#   Ú_keyÚ_valuer   r   r   r$   R   s   €
 ÿÿr%   )r   ÚitemsÚ
isinstanceÚtorchÚTensorr"   ÚlistÚsumÚ	TypeErrorÚdistÚis_availableÚis_initializedÚdataÚcloneÚ
all_reduceÚdiv_Úget_world_sizeÚitem)ÚlossesÚlog_varsZ	loss_nameZ
loss_valuer%   r   r   r   Ú_parse_losses;   s"   
ÿ
zBaseLocalizer._parse_lossesc                 K   s@   | j di |¤Ž}|  |¡\}}t||ttt| ¡ ƒƒƒd�}|S )a¥  The iteration step during training.

        This method defines an iteration step during training, except for the
        back propagation and optimizer updating, which are done in an optimizer
        hook. Note that in some complicated cases or models, the whole process
        including back propagation and optimizer updating is also defined in
        this method, such as GAN.

        Args:
            data_batch (dict): The output of dataloader.
            optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of
                runner is passed to ``train_step()``. This argument is unused
                and reserved.

        Returns:
            dict: It should contain at least 3 keys: ``loss``, ``log_vars``,
                ``num_samples``.
                ``loss`` is a tensor for back propagation, which can be a
                weighted sum of multiple losses.
                ``log_vars`` contains all the variables to be sent to the
                logger.
                ``num_samples`` indicates the batch size (when the model is
                DDP, it means the batch size on each GPU), which is used for
                averaging the logs.
        )r%   r9   Únum_samplesNr   )r!   r:   ÚdictÚlenÚnextÚiterÚvalues)r   Ú
data_batchÚ	optimizerr    r8   r%   r9   Úoutputsr   r   r   Ú
train_step_   s   ýzBaseLocalizer.train_stepc                 K   s"   | j dddi|¤Ž}t|d�}|S )a  The iteration step during validation.

        This method shares the same signature as :func:`train_step`, but used
        during val epochs. Note that the evaluation after training epochs is
        not implemented with this method, but an evaluation hook.
        r   F)ÚresultsNr   )r!   r<   )r   rA   rB   r    rE   rC   r   r   r   Úval_step„   s   
zBaseLocalizer.val_step)NN)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r
   r   r   r   r   r   r!   Ústaticmethodr:   rD   rF   Ú__classcell__r   r   r   r   r      s    	



#%r   )Ú	metaclass)Úabcr   r   Úcollectionsr   r*   Útorch.distributedÚdistributedr/   Útorch.nnÚnnÚ r   ÚModuler   r   r   r   r   Ú<module>   s    