o
    _{jM3  ã                	   @   sÜ   d dl Z d dlmZ d dlmZ ddlmZ ddlmZ zd dl	m
Z
 W n eefy7   edƒd	d
„ ƒZ
Y nw dd„ ZG dd„ dejƒZG dd„ dejƒZG dd„ dejƒZG dd„ dejƒZe ¡ G dd„ deƒƒZdS )é    N)Úimport_module_error_funcé   )Ú	BACKBONESé   )Ú	ResNetTSM)Ú	tin_shiftz	mmcv-fullc                  O   s   d S ©N© )ÚargsÚkwargsr	   r	   ú:/root/disk_3tb/HAC/mmaction/models/backbones/resnet_tin.pyr      s   r   c                 C   s6  | j \}}}}}t |¡ ¡ }|d }|  ||||| ¡ ¡ } t| |ƒ}	t| |ƒ}
d|| ¡   }d| }|j d }|dd…dd…df  dd|| ¡}| | 	d¡d¡}|dd…dd…df  dd|| ¡}| | 	d¡d¡}|dd…ddd…df }|dd…ddd…df }||	 ||
  }| |||||¡}|S )a  Differentiable Temporal-wise Frame Sampling, which is essentially a
    linear interpolation process.

    It gets the feature map which has been split into several groups
    and shift them by different offsets according to their groups.
    Then compute the weighted sum along with the temporal dimension.

    Args:
        data (torch.Tensor): Split data for certain group in shape
            [N, num_segments, C, H, W].
        offset (torch.Tensor): Data offsets for this group data in shape
            [N, num_segments].
    r   Nr   éÿÿÿÿ)
ÚshapeÚtorchÚfloorÚintÚviewÚ
contiguousr   ÚfloatÚrepeatÚsize)ÚdataÚoffsetÚnÚtÚcÚhÚwZoffset0Zoffset1Zdata0Údata1Zweight0Zweight1Ú
group_sizeÚoutputr	   r	   r   Úlinear_sampler   s$   


$$r!   c                       s(   e Zd ZdZ‡ fdd„Zdd„ Z‡  ZS )Ú
CombineNetzÑCombine Net.

    It combines Temporal interlace module with some part of ResNet layer.

    Args:
        net1 (nn.module): Temporal interlace module.
        net2 (nn.module): Some part of ResNet layer.
    c                    s   t ƒ  ¡  || _|| _d S r   )ÚsuperÚ__init__Únet1Únet2)Úselfr%   r&   ©Ú	__class__r	   r   r$   L   s   

zCombineNet.__init__c                 C   s   |   |¡}|  |¡}|S )ú¼Defines the computation performed at every call.

        Args:
            x (torch.Tensor): The input data.

        Returns:
            torch.Tensor: The output of the module.
        )r%   r&   )r'   Úxr	   r	   r   ÚforwardQ   s   

zCombineNet.forward©Ú__name__Ú
__module__Ú__qualname__Ú__doc__r$   r,   Ú__classcell__r	   r	   r(   r   r"   B   s    	r"   c                       ó0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )Ú	WeightNetaï  WeightNet in Temporal interlace module.

    The WeightNet consists of two parts: one convolution layer
    and a sigmoid function. Following the convolution layer, the sigmoid
    function and rescale module can scale our output to the range (0, 2).
    Here we set the initial bias of the convolution layer to 0, and the
    final initial output will be 1.0.

    Args:
        in_channels (int): Channel num of input features.
        groups (int): Number of groups for fc layer outputs.
    c                    s:   t ƒ  ¡  t ¡ | _|| _tj||ddd�| _|  ¡  d S ©Né   r   )Úpadding)	r#   r$   ÚnnÚSigmoidÚsigmoidÚgroupsÚConv1dÚconvÚinit_weights)r'   Úin_channelsr;   r(   r	   r   r$   p   s
   

zWeightNet.__init__c                 C   ó   d| j jjd< dS )úPInitiate the parameters either from existing checkpoint or from
        scratch.r   .N)r=   Úbiasr   ©r'   r	   r	   r   r>   y   ó   zWeightNet.init_weightsc                 C   sF   |j \}}}|  |¡}| || j|¡}| ddd¡}d|  |¡ }|S )r*   r   r   r   )r   r=   r   r;   Úpermuter:   ©r'   r+   r   Ú_r   r	   r	   r   r,   €   s   
zWeightNet.forward©r.   r/   r0   r1   r$   r>   r,   r2   r	   r	   r(   r   r4   b   s
    	r4   c                       r3   )Ú	OffsetNeta4  OffsetNet in Temporal interlace module.

    The OffsetNet consists of one convolution layer and two fc layers
    with a relu activation following with a sigmoid function. Following
    the convolution layer, two fc layers and relu are applied to the output.
    Then, apply the sigmoid function with a multiply factor and a minus 0.5
    to transform the output to (-4, 4).

    Args:
        in_channels (int): Channel num of input features.
        groups (int): Number of groups for fc layer outputs.
        num_segments (int): Number of frame segments.
    c                    sb   t ƒ  ¡  t ¡ | _d}d}tj|d||d�| _t ||¡| _t 	¡ | _
t ||¡| _|  ¡  d S r5   )r#   r$   r8   r9   r:   r<   r=   ÚLinearÚfc1ÚReLUÚreluÚfc2r>   )r'   r?   r;   Únum_segmentsÚkernel_sizer7   r(   r	   r   r$   §   s   


zOffsetNet.__init__c                 C   r@   )rA   gcÙ=yXà?.N)rN   rB   r   rC   r	   r	   r   r>   µ   rD   zOffsetNet.init_weightsc                 C   s`   |j \}}}|  |¡}| ||¡}|  |  |¡¡}|  |¡}| |dd¡}d|  |¡d  }|S )r*   r   r   é   g      à?)r   r=   r   rM   rK   rN   r:   rF   r	   r	   r   r,   ¼   s   

zOffsetNet.forwardrH   r	   r	   r(   r   rI   ˜   s
    rI   c                       s*   e Zd ZdZd‡ fdd„	Zdd„ Z‡  ZS )	ÚTemporalInterlaceaV  Temporal interlace module.

    This module is proposed in `Temporal Interlacing Network
    <https://arxiv.org/abs/2001.06499>`_

    Args:
        in_channels (int): Channel num of input features.
        num_segments (int): Number of frame segments. Default: 3.
        shift_div (int): Number of division parts for shift. Default: 1.
    r6   r   c                    sL   t ƒ  ¡  || _|| _|| _d| _t|| | j|ƒ| _t|| | jƒ| _	d S )Nr   )
r#   r$   rO   Ú	shift_divr?   Zdeform_groupsrI   Ú
offset_netr4   Ú
weight_net)r'   r?   rO   rS   r(   r	   r   r$   æ   s   
ÿ
ÿzTemporalInterlace.__init__c                 C   s¤  |  ¡ \}}}}|| j }|| j }tj||||f|jd�}|dd…d|…dd…dd…f  || j|||¡}	t |	d¡}
t |
d¡}
|
 ddd¡ 	¡ }
|  
|
¡ |d¡}|  |
¡}t || gd¡}t|	|ƒ}|dd…dd…dd…df }| ddd|d d ¡}| |  d¡|  d¡d¡}|dd…dd…dd…ddf }|| }| 	¡  ||||¡}||dd…d|…dd…f< |dd…|d…dd…f |dd…|d…dd…f< |S )r*   )ÚdeviceNr6   r   r   r   r   )r   rO   rS   r   ÚzerosrV   r   ÚmeanrE   r   rT   rU   Úcatr!   r   )r'   r+   r   r   r   r   Znum_batchesZ	num_foldsZx_outZx_descriptorZx_pooledÚx_offsetZx_weightZx_shiftr	   r	   r   r,   ó   s0   

"þ

0zTemporalInterlace.forward)r6   r   r-   r	   r	   r(   r   rR   Ú   s    rR   c                       s<   e Zd ZdZ			d‡ fdd„	Zdd„ Z‡ fd	d
„Z‡  ZS )Ú	ResNetTINax  ResNet backbone for TIN.

    Args:
        depth (int): Depth of ResNet, from {18, 34, 50, 101, 152}.
        num_segments (int): Number of frame segments. Default: 8.
        is_tin (bool): Whether to apply temporal interlace. Default: True.
        shift_div (int): Number of division parts for shift. Default: 4.
        kwargs (dict, optional): Arguments for ResNet.
    é   TrQ   c                    s*   t ƒ j|fi |¤Ž || _|| _|| _d S r   )r#   r$   rO   Úis_tinrS   )r'   ÚdepthrO   r]   rS   r   r(   r	   r   r$   ?  s   
zResNetTIN.__init__c                    s®   | j gd }|d dksJ ‚d‰ tt| j ¡ ƒƒdkr#tdˆ › d�ƒ ‡ fdd	„}|| j|d | jƒ| _|| j|d | jƒ| _|| j|d
 | jƒ| _|| j	|d | jƒ| _	dS )z(Make temporal interlace for some layers.rQ   r   r   r   é   z=> Using n_round z to insert temporal shift.c                    s`   t |  ¡ ƒ}t|ƒD ] \}}|ˆ  dkr*t|jj||d�}t||| jjƒ|| j_q
tj	|Ž S )až  Apply Deformable shift for a ResNet layer module.

            Args:
                stage (nn.module): A ResNet layer to be deformed.
                num_segments (int): Number of frame segments.
                shift_div (int): Number of division parts for shift.

            Returns:
                nn.Sequential: A Sequential container consisted of
                    deformed Interlace blocks.
            r   )rO   rS   )
ÚlistÚchildrenÚ	enumeraterR   Úconv1r?   r"   r=   r8   Ú
Sequential)ÚstagerO   rS   ÚblocksÚiÚbZtds©Ún_roundr	   r   Úmake_block_interlaceS  s   ý
ÿ€
z?ResNetTIN.make_temporal_interlace.<locals>.make_block_interlacer   r6   N)
rO   Úlenr`   Úlayer3ra   ÚprintÚlayer1rS   Úlayer2Úlayer4)r'   Únum_segment_listrk   r	   ri   r   Úmake_temporal_interlaceJ  s$   ÿÿÿ
ÿz!ResNetTIN.make_temporal_interlacec                    s:   t t| ƒ ¡  | jr|  ¡  t| jƒdkr|  ¡  dS dS )rA   r   N)r#   r   r>   r]   rs   rl   Únon_local_cfgÚmake_non_localrC   r(   r	   r   r>   s  s   ÿzResNetTIN.init_weights)r\   TrQ   )r.   r/   r0   r1   r$   rs   r>   r2   r	   r	   r(   r   r[   3  s    ü)r[   )r   Útorch.nnr8   Úmmaction.utilsr   Úregistryr   Ú
resnet_tsmr   Úmmcv.opsr   ÚImportErrorÚModuleNotFoundErrorr!   ÚModuler"   r4   rI   rR   Úregister_moduler[   r	   r	   r	   r   Ú<module>   s$    ý1 6BY