a
    þdº@  ã                   @   s    d dl Z d dlmZ d dlm  mZ d dlZd dlZd dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ e ¡ G dd„ dejƒƒZG d	d
„ d
eƒZdS )é    N)Ú	flow_warp)ÚConvResidualBlocks)ÚSpyNet)ÚModulatedDeformConvPack)ÚARCH_REGISTRYc                       sJ   e Zd ZdZd‡ fdd	„	Zd
d„ Zdd„ Zdd„ Zdd„ Zdd„ Z	‡  Z
S )ÚBasicVSRPlusPlusa  BasicVSR++ network structure.
    Support either x4 upsampling or same size output. Since DCN is used in this
    model, it can only be used with CUDA enabled. If CUDA is not enabled,
    feature alignment will be skipped. Besides, we adopt the official DCN
    implementation and the version of torch need to be higher than 1.9.
    Paper:
        BasicVSR++: Improving Video Super-Resolution with Enhanced Propagation
        and Alignment
    Args:
        mid_channels (int, optional): Channel number of the intermediate
            features. Default: 64.
        num_blocks (int, optional): The number of residual blocks in each
            propagation branch. Default: 7.
        max_residue_magnitude (int): The maximum magnitude of the offset
            residue (Eq. 6 in paper). Default: 10.
        is_low_res_input (bool, optional): Whether the input is low-resolution
            or not. If False, the output resolution is equal to the input
            resolution. Default: True.
        spynet_path (str): Path to the pretrained weights of SPyNet. Default: None.
        cpu_cache_length (int, optional): When the length of sequence is larger
            than this value, the intermediate features are sent to CPU. This
            saves GPU memory, but slows down the inference speed. You can
            increase this number if you have a GPU with large memory.
            Default: 100.
    é@   é   é
   TNéd   c           
         sÄ  t ƒ  ¡  || _|| _|| _t|ƒ| _|r:td|dƒ| _nLt	 
t	 d|ddd¡t	jdddt	 ||ddd¡t	jdddt||dƒ¡| _t	 ¡ | _t	 ¡ | _g d¢}t|ƒD ]J\}}	tj ¡ rÚtd| |ddd	|d
| j|	< td| | ||ƒ| j|	< qªtd| |dƒ| _t	j||d ddddd| _t	j|dddddd| _t	 d¡| _t	 ddddd¡| _t	 ddddd¡| _t	jdddd| _t	jddd| _d| _t | jƒdkr°d| _!nd| _!t" #d¡ d S )Né   é   é   é   çš™™™™™¹?T©Znegative_slopeZinplace)Z
backward_1Z	forward_1Z
backward_2Z	forward_2é   )ÚpaddingÚdeformable_groupsÚmax_residue_magnitudeé   )Úbiasé   r   ZbilinearF)Úscale_factorÚmodeZalign_cornersr   z›Deformable alignment module is not added. Probably your CUDA is not configured correctly. DCN can only be used with CUDA enabled. Alignment is skipped now.)$ÚsuperÚ__init__Úmid_channelsÚis_low_res_inputÚcpu_cache_lengthr   Úspynetr   Úfeat_extractÚnnÚ
SequentialÚConv2dÚ	LeakyReLUZ
ModuleDictÚdeform_alignÚbackboneÚ	enumerateÚtorchÚcudaZis_availableÚSecondOrderDeformableAlignmentÚreconstructionÚupconv1Úupconv2ZPixelShuffleÚpixel_shuffleÚconv_hrÚ	conv_lastZUpsampleÚimg_upsampleÚlreluÚis_mirror_extendedÚlenÚis_with_alignmentÚwarningsÚwarn)
Úselfr   Z
num_blocksr   r   Zspynet_pathr   ÚmodulesÚiÚmodule©Ú	__class__© úf/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/basicsr/archs/basicvsrpp_arch.pyr   *   sN    


ý


úzBasicVSRPlusPlus.__init__c                 C   sH   |  d¡d dkrDtj|ddd\}}t || d¡ ¡dkrDd| _dS )a  Check whether the input is a mirror-extended sequence.
        If mirror-extended, the i-th (i=0, ..., t-1) frame is equal to the
        (t-1-i)-th frame.
        Args:
            lqs (tensor): Input low quality (LQ) sequence with
                shape (n, t, c, h, w).
        r   r   r   ©ZdimTN)Úsizer)   ÚchunkZnormÚflipr4   )r9   ÚlqsÚlqs_1Úlqs_2r?   r?   r@   Úcheck_if_mirror_extendedl   s    	z)BasicVSRPlusPlus.check_if_mirror_extendedc                 C   sâ   |  ¡ \}}}}}|dd…dd…dd…dd…dd…f  d|||¡}|dd…dd…dd…dd…dd…f  d|||¡}|  ||¡ ||d d||¡}	| jr¦|	 d¡}
n|  ||¡ ||d d||¡}
| jrÚ|	 ¡ }	|
 ¡ }
|
|	fS )au  Compute optical flow using SPyNet for feature alignment.
        Note that if the input is an mirror-extended sequence, 'flows_forward'
        is not needed, since it is equal to 'flows_backward.flip(1)'.
        Args:
            lqs (tensor): Input low quality (LQ) sequence with
                shape (n, t, c, h, w).
        Return:
            tuple(Tensor): Optical flow. 'flows_forward' corresponds to the
                flows used for forward-time propagation (current to previous).
                'flows_backward' corresponds to the flows used for
                backward-time propagation (current to next).
        Néÿÿÿÿr   r   )rB   Zreshaper    Úviewr4   rD   Ú	cpu_cacheÚcpu)r9   rE   ÚnÚtÚcÚhÚwrF   rG   Úflows_backwardÚflows_forwardr?   r?   r@   Úcompute_flowz   s    22zBasicVSRPlusPlus.compute_flowc              
      s®  |  ¡ \}}}}}td|d ƒ}	td|ƒ}
ttdtˆ d ƒƒƒ}||ddd… 7 }dˆv rl|	ddd… }	|	}
| || j||¡}t|	ƒD ] \}‰ˆ d |ˆ  }| jr¶| ¡ }| ¡ }|dkrú| j	rú|dd…|
| dd…dd…dd…f }| jrü| ¡ }t
|| dddd¡ƒ}t |¡}t |¡}t |¡}|dkrÀˆ ˆ d	 }| jrV| ¡ }|dd…|
|d  dd…dd…dd…f }| jr| ¡ }|t
|| dddd¡ƒ }t
|| dddd¡ƒ}tj|||gdd
}tj||gdd
}| jˆ ||||ƒ}|g‡ ‡‡fdd„ˆ D ƒ |g }| jr2dd„ |D ƒ}tj|dd
}|| jˆ |ƒ }ˆ ˆ  |¡ | jr†ˆ ˆ d  ¡ ˆ ˆ d< tj ¡  q†dˆv rªˆ ˆ ddd… ˆ ˆ< ˆ S )a³  Propagate the latent features throughout the sequence.
        Args:
            feats dict(list[tensor]): Features from previous branches. Each
                component is a list of tensors with shape (n, c, h, w).
            flows (tensor): Optical flows with shape (n, t - 1, 2, h, w).
            module_name (str): The name of the propgation branches. Can either
                be 'backward_1', 'forward_1', 'backward_2', 'forward_2'.
        Return:
            dict(list[tensor]): A dictionary containing all the propagated
                features. Each key in the dictionary corresponds to a
                propagation branch, which is represented by a list of tensors.
        r   r   rI   ÚspatialNÚbackwardr   r   éþÿÿÿrA   c                    s$   g | ]}|d ˆfvrˆ | ˆ ‘qS )rU   r?   ©Ú.0Úk©ÚfeatsÚidxÚmodule_namer?   r@   Ú
<listcomp>×   ó    z.BasicVSRPlusPlus.propagate.<locals>.<listcomp>c                 S   s   g | ]}|  ¡ ‘qS r?   )r*   )rY   Úfr?   r?   r@   r_   Ù   r`   )rB   ÚrangeÚlistr5   Z	new_zerosr   r(   rK   r*   r6   r   Zpermuter)   Z
zeros_likeÚcatr&   r'   ÚappendrL   Úempty_cache)r9   r\   Úflowsr^   rM   rN   Ú_rP   rQ   Z	frame_idxZflow_idxÚmapping_idxZ	feat_propr;   Zfeat_currentZflow_n1Zcond_n1Zfeat_n2Zflow_n2Zcond_n2ZcondÚfeatr?   r[   r@   Ú	propagate™   s\    
&



*"
zBasicVSRPlusPlus.propagatec                    sl  g }t ˆ d ƒ}ttd|ƒƒ}||ddd… 7 }td| d¡ƒD ]}‡ fdd„ˆ D ƒ}| dˆ d ||  ¡ tj|dd}| jrŒ| ¡ }|  	|¡}|  
|  |  |¡¡¡}|  
|  |  |¡¡¡}|  
|  |¡¡}|  |¡}| jr||  |dd…|dd…dd…dd…f ¡7 }n&||dd…|dd…dd…dd…f 7 }| jrR| ¡ }tj ¡  | |¡ q@tj|ddS )	aD  Compute the output image given the features.
        Args:
            lqs (tensor): Input low quality (LQ) sequence with
                shape (n, t, c, h, w).
            feats (dict): The features from the propgation branches.
        Returns:
            Tensor: Output HR sequence with shape (n, t, c, 4h, 4w).
        rU   r   NrI   r   c                    s"   g | ]}|d krˆ |   d¡‘qS )rU   r   )ÚpoprX   ©r\   r?   r@   r_   ù   r`   z-BasicVSRPlusPlus.upsample.<locals>.<listcomp>rA   )r5   rc   rb   rB   Úinsertr)   rd   rK   r*   r,   r3   r/   r-   r.   r0   r1   r   r2   rL   rf   re   Ústack)r9   rE   r\   ÚoutputsZnum_outputsri   r;   Úhrr?   rm   r@   Úupsampleè   s.    


.&
zBasicVSRPlusPlus.upsamplec              
      sú  |  ¡ \}}}}}|| jkr dnd| _| jr6| ¡ }n2tj| d|||¡ddd ||||d |d ¡}|  |¡ i }| jrÚg |d< t	d	|ƒD ]H}	|  
|d
d
…|	d
d
…d
d
…d
d
…f ¡ ¡ }
|d  |
¡ tj ¡  qŽnV|  
| d|||¡¡‰ ˆ jdd
… \}}ˆ  ||d||¡‰ ‡ fdd„t	d	|ƒD ƒ|d< |  d¡dkrP|  d¡dksfJ d|› d|› dƒ‚|  |¡\}}dD ]t}dD ]h}|› d|› }g ||< |dkrª|}n|d
urº|}n
| d¡}|  |||¡}| jr€~tj ¡  q€qx|  ||¡S )zóForward function for BasicVSR++.
        Args:
            lqs (tensor): Input low quality (LQ) sequence with
                shape (n, t, c, h, w).
        Returns:
            Tensor: Output HR sequence with shape (n, t, c, 4h, 4w).
        TFrI   g      Ð?Zbicubic)r   r   r   rU   r   Nr   c              	      s.   g | ]&}ˆ d d …|d d …d d …d d …f ‘qS )Nr?   )rY   r;   ©Zfeats_r?   r@   r_   4  r`   z,BasicVSRPlusPlus.forward.<locals>.<listcomp>r   r   zDThe height and width of low-res inputs must be at least 64, but got z and Ú.)r   r   )rV   Úforwardrh   rV   r   )rB   r   rK   r   ÚcloneÚFZinterpolaterJ   rH   rb   r!   rL   re   r)   r*   rf   ÚshaperT   rD   rk   rr   )r9   rE   rM   rN   rO   rP   rQ   Zlqs_downsampler\   r;   rj   rS   rR   Ziter_Ú	directionr<   rg   r?   rs   r@   ru     sV    	
ÿÿ
,"ÿÿÿ


zBasicVSRPlusPlus.forward)r   r	   r
   TNr   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rH   rT   rk   rr   ru   Ú__classcell__r?   r?   r=   r@   r      s         úBO)r   c                       s0   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Z‡  ZS )r+   aÍ  Second-order deformable alignment module.
    Args:
        in_channels (int): Same as nn.Conv2d.
        out_channels (int): Same as nn.Conv2d.
        kernel_size (int or tuple[int]): Same as nn.Conv2d.
        stride (int or tuple[int]): Same as nn.Conv2d.
        padding (int or tuple[int]): Same as nn.Conv2d.
        dilation (int or tuple[int]): Same as nn.Conv2d.
        groups (int): Same as nn.Conv2d.
        bias (bool or str): If specified as `auto`, it will be decided by the
            norm_cfg. Bias will be set as True if norm_cfg is None, otherwise
            False.
        max_residue_magnitude (int): The maximum magnitude of the offset
            residue (Eq. 6 in paper). Default: 10.
    c                    sº   |  dd¡| _tt| ƒj|i |¤Ž t t d| j d | jddd¡tj	dddt | j| jddd¡tj	dddt | j| jddd¡tj	dddt | jd	| j
 ddd¡¡| _|  ¡  d S )
Nr   r
   r   r   r   r   Tr   é   )rl   r   r   r+   r   r"   r#   r$   Zout_channelsr%   r   Úconv_offsetÚinit_offset)r9   ÚargsÚkwargsr=   r?   r@   r   c  s    ù
z'SecondOrderDeformableAlignment.__init__c                 C   s"   ddd„}|| j d ddd d S )Nr   c                 S   sL   t | dƒr$| jd ur$tj | j|¡ t | dƒrH| jd urHtj | j|¡ d S )NÚweightr   )Úhasattrr„   r"   ÚinitZ	constant_r   )r<   Úvalr   r?   r?   r@   Ú_constant_initv  s    zBSecondOrderDeformableAlignment.init_offset.<locals>._constant_initrI   )r‡   r   )r   )r€   )r9   rˆ   r?   r?   r@   r   t  s    
z*SecondOrderDeformableAlignment.init_offsetc              
   C   sî   t j|||gdd}|  |¡}t j|ddd\}}}| jt  t j||fdd¡ }	t j|	ddd\}
}|
| d¡ d|
 d¡d dd¡ }
|| d¡ d| d¡d dd¡ }t j|
|gdd}	t  	|¡}t
j ||	| j| j| j| j| j|¡S )Nr   rA   r   r   )r)   rd   r€   rC   r   ÚtanhrD   ÚrepeatrB   ZsigmoidÚtorchvisionÚopsZdeform_conv2dr„   r   Zstrider   Zdilation)r9   ÚxZ
extra_featZflow_1Zflow_2ÚoutZo1Zo2ÚmaskÚoffsetZoffset_1Zoffset_2r?   r?   r@   ru   ~  s    
$$
ÿz&SecondOrderDeformableAlignment.forward)rz   r{   r|   r}   r   r   ru   r~   r?   r?   r=   r@   r+   R  s   
r+   )r)   Ztorch.nnr"   Ztorch.nn.functionalZ
functionalrw   r‹   r7   Zbasicsr.archs.arch_utilr   Zbasicsr.archs.basicvsr_archr   Zbasicsr.archs.spynet_archr   Zbasicsr.ops.dcnr   Zbasicsr.utils.registryr   ÚregisterÚModuler   r+   r?   r?   r?   r@   Ú<module>   s     E