a e@sddlZddlmZddlmmZddlmZddlm Z GdddeZ GdddeZ e j Z Gdd d ejZdd d Zd dZddZdddZGdddejZGdddejZdS)N)Function) spectral_normc@s$eZdZeddZeddZdS)BlurFunctionBackwardcCs(|||tj||d|jdd}|SN)paddinggroupssave_for_backwardFconv2dshapectx grad_outputkernel kernel_flip grad_inputr)D:\face swap\basicsr\archs\dfdnet_util.pyforward s zBlurFunctionBackward.forwardcCs,|j\}}tj||d|jdd}|ddfSr) saved_tensorsr r r )rZgradgrad_outputr_rrrrbackwards zBlurFunctionBackward.backwardN__name__ __module__ __qualname__ staticmethodrrrrrrrs rc@s$eZdZeddZeddZdS) BlurFunctioncCs(|||tj||d|jdd}|Srr )rxrroutputrrrrs zBlurFunction.forwardcCs"|j\}}t|||}|ddfSN)rrapplyrrrrrs zBlurFunction.backwardNrrrrrrs rcs$eZdZfddZddZZS)Blurcsttjgdgdgdgtjd}|dddd}||}t|ddg}||ddd|_ ||ddd|_ dS)N)rr)r%r%)dtyperr%) super__init__torchtensorfloat32viewsumfliprepeatrr)selfchannelrr __class__rrr*+s " z Blur.__init__cCst||j||j|Sr")blurrtype_asr)r2r rrrr5sz Blur.forwardrrrr*r __classcell__rrr4rr$)s r$h㈵>cCs|}t|dksJd|dd\}}|||djdd|}|||dd}|||djdd||dd}||fS)zCalculate mean and std for adaptive_instance_normalization. Args: feat (Tensor): 4D tensor. eps (float): A small value added to the variance to avoid divide-by-zero. Default: 1e-5. r&z&The input feature should be 4D tensor.Nr%)dimr)sizelenr.varsqrtmean)featepsr=ncZfeat_varZfeat_stdZ feat_meanrrr calc_mean_std9s"rFcCsP|}t|\}}t|\}}|||||}|||||S)aAdaptive instance normalization. Adjust the reference features to have the similar color and illuminations as those in the degradate features. Args: content_feat (Tensor): The reference feature. style_feat (Tensor): The degradate features. )r=rFexpand)Z content_featZ style_featr=Z style_meanZ style_stdZ content_meanZ content_stdZnormalized_featrrradaptive_instance_normalizationJs   rHc Cs:ttt||dddtddtt||dddSNr(r皙?Tnn SequentialrConv2d LeakyReLU) in_channelrrrAttentionBlock[srQr(rTcCs\tttj||||||dd||dtdttj||||||dd||dS)z#Conv block used in MSDilationBlock.rr%) kernel_sizestridedilationrbiasrJrK) in_channels out_channelsrRrSrTrUrrr conv_blockas2 rXcs*eZdZdZd fdd ZddZZS) MSDilationBlockzMulti-scale dilation block.r(rrrrTc sptt|t|_tdD]"}|jt||||||dq t tj |d||d|dd|d|_ dS)Nr&)rTrUrr%)rRrSrrU) r)rYr*rL ModuleList conv_blocksrangeappendrXrrN conv_fusion)r2rVrRrTrUir4rrr*~s    zMSDilationBlock.__init__cCsDg}tdD]}||j||q t|d}|||}|S)Nr&r)r]r^r\r+catr_)r2r outr`rrrrs   zMSDilationBlock.forward)r(rZT)rrr__doc__r*rr9rrr4rrY{srYcs$eZdZfddZddZZS) UpResBlockc sFtt|tt||dddtddt||ddd|_dSrI)r)rdr*rLrMrNrObody)r2rPr4rrr*s  zUpResBlock.__init__cCs|||}|Sr")re)r2r rbrrrrszUpResBlock.forwardr8rrr4rrds rd)r:)r(rrT)r+torch.nnrLtorch.nn.functional functionalr Ztorch.autogradrtorch.nn.utils.spectral_normrrrr#r6Moduler$rFrHrQrXrYrdrrrrs