o
    _{jù#  ã                   @   s€   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
  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)Ú	auto_fp16é   )Úbuilderc                       s’   e Zd ZdZ			d‡ fdd„	Zdd„ Zeƒ dd„ ƒZdd
d„Ze	dd„ ƒZ
e	dd„ ƒZe	dd„ ƒZedd„ ƒZddd„Zdd„ Zdd„ Z‡  ZS )ÚBaseRecognizera	  Base class for recognizers.

    All recognizers should subclass it.
    All subclass should overwrite:

    - Methods:``forward_train``, supporting to forward when training.
    - Methods:``forward_test``, supporting to forward when testing.

    Args:
        backbone (dict): Backbone modules to extract feature.
        cls_head (dict): Classification head to process feature.
        train_cfg (dict | None): Config for training. Default: None.
        test_cfg (dict | None): Config for testing. Default: None.
    Nc              	      s  t ƒ  ¡  |d  d¡r6zdd lm  m} W n ttfy$   tdƒ‚w |d dd … |d< | |¡| _	nt |¡| _	|d urFt 
|¡| _t |¡| _|| _|| _g | _|d urbd|v rb|d | _d | _|d urzd|v rz|d | _t| jtƒszJ ‚|  ¡  d| _d S )	NÚtypezmmcls::r   z*Please install mmcls to use this backbone.é   Úaux_infoÚmax_testing_viewsF)ÚsuperÚ__init__Ú
startswithZmmcls.models.builderÚmodelsr   ÚImportErrorÚModuleNotFoundErrorÚbuild_backboneÚbackboneÚ
build_neckÚneckÚ
build_headÚcls_headÚ	train_cfgÚtest_cfgr   r   Ú
isinstanceÚintÚinit_weightsÚfp16_enabled)Úselfr   r   r   r   r   Zmmcls_builder©Ú	__class__© ú6/root/disk_3tb/HAC/mmaction/models/recognizers/base.pyr      s0   
ÿ


zBaseRecognizer.__init__c                 C   s0   | j  ¡  | j ¡  t| dƒr| j ¡  dS dS )z%Initialize the model network weights.r   N)r   r   r   Úhasattrr   )r   r"   r"   r#   r   F   s
   


ÿzBaseRecognizer.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_featM   s   

zBaseRecognizer.extract_featé   c                 C   s˜   d| j  ¡ vrtdƒ‚| j d }|dvrt|› d�ƒ‚|du r!|S |jd }| || |d¡}|dkr@tj|d	d
�jdd
�}|S |dkrJ|jdd
�}|S )a¿  Averaging class score over multiple clips.

        Using different averaging types ('score' or 'prob' or None,
        which defined in test_cfg) to computed the final averaged
        class score. Only called in test mode.

        Args:
            cls_score (torch.Tensor): Class score to be averaged.
            num_segs (int): Number of clips for each input sample.

        Returns:
            torch.Tensor: Averaged class score.
        Úaverage_clipsz/"average_clips" must defined in test_cfg's keys)ÚscoreÚprobNzG is not supported. Currently supported ones are ["score", "prob", None]Nr   éÿÿÿÿr+   r   )Údimr(   r*   )	r   ÚkeysÚKeyErrorÚ
ValueErrorÚshapeÚviewÚFÚsoftmaxÚmean)r   Ú	cls_scoreÚnum_segsr)   Ú
batch_sizer"   r"   r#   Úaverage_clipZ   s   

ýzBaseRecognizer.average_clipc                 K   ó   dS )z>Defines the computation performed at every call when training.Nr"   )r   r%   ÚlabelsÚkwargsr"   r"   r#   Úforward_train~   ó    zBaseRecognizer.forward_trainc                 C   r:   )zTDefines the computation performed at every call when evaluation and
        testing.Nr"   ©r   r%   r"   r"   r#   Úforward_test‚   r>   zBaseRecognizer.forward_testc                 C   r:   )zPDefines the computation performed at every all when using gradcam
        utils.Nr"   r?   r"   r"   r#   Úforward_gradcam‡   r>   zBaseRecognizer.forward_gradcamc                 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 )N)r5   )Ú.0Ú_lossr"   r"   r#   Ú	<genexpr>ž   s   € z/BaseRecognizer._parse_losses.<locals>.<genexpr>z# is not a tensor or list of tensorsc                 s   s    � | ]\}}d |v r|V  qdS )ÚlossNr"   )rB   Ú_keyÚ_valuer"   r"   r#   rD   £   s   €
 ÿÿrE   )r   Úitemsr   ÚtorchÚTensorr5   ÚlistÚsumÚ	TypeErrorÚdistÚis_availableÚis_initializedÚdataÚcloneÚ
all_reduceÚdiv_Úget_world_sizeÚitem)ÚlossesÚlog_varsÚ	loss_nameÚ
loss_valuerE   r"   r"   r#   Ú_parse_lossesŒ   s"   
ÿ
zBaseRecognizer._parse_lossesTc                 K   s^   |  dd¡r|d= | j|fi |¤ŽS |r&|du rtdƒ‚| j||fi |¤ŽS | j|fi |¤ŽS )z/Define the computation performed at every call.ÚgradcamFNzLabel should not be None.)ÚgetrA   r0   r=   r@   )r   r%   ÚlabelÚreturn_lossr<   r"   r"   r#   Úforward°   s   zBaseRecognizer.forwardc                 K   s~   |d }|d }i }| j D ]}||v sJ ‚|| ||< q| ||fd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%   r^   r_   T©rE   rX   Únum_samples©r   r[   ÚdictÚlenÚnextÚiterÚvalues©r   Ú
data_batchÚ	optimizerr<   r%   r^   r   rV   rW   rE   rX   Úoutputsr"   r"   r#   Ú
train_step¼   s   
ýzBaseRecognizer.train_stepc                 K   sr   |d }|d }i }| j D ]}|| ||< q| ||fddi|¤Ž}|  |¡\}	}
t|	|
tt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%   r^   r_   Tra   rc   ri   r"   r"   r#   Úval_stepé   s   
ýzBaseRecognizer.val_step)NNN)r(   )NT)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r   r'   r9   r   r=   r@   rA   Ústaticmethodr[   r`   rm   rn   Ú__classcell__r"   r"   r    r#   r      s*    û)

$




#-r   )Ú	metaclass)Úabcr   r   Úcollectionsr   rI   Útorch.distributedÚdistributedrN   Útorch.nnÚnnÚtorch.nn.functionalÚ
functionalr3   Úmmcv.runnerr   Ú r   ÚModuler   r"   r"   r"   r#   Ú<module>   s    