compressai中的上下文预测模块

理论

1、自回归模型Autoregressive model

用自身产生的参数去预测下一个值,即使用 x 1 , x 2 , . . . , x t x_1,x_2,...,x_t x1,x2,...,xt去预测 x t + 1 x_{t+1} xt+1,用 x 1 , x 2 , . . . , x t , x t + 1 x_1,x_2,...,x_t,x_{t+1} x1,x2,...,xt,xt+1去预测 x t + 2 x_{t+2} xt+2

2、Masked 2D convolution

compressai使用的是PixelCNN模块中的Masked 2D convolution,我理解的就是正常的2D卷积操作,由于当前像素是根据之前解码的像素得到的,所以要让卷积块中位于当前像素的之后的权重为0;

比如说5*5的卷积核:

在这里插入图片描述
Introduced in "Conditional Image Generation with PixelCNN Decoders" <https://arxiv.org/abs/1606.05328>_.

代码

简单到我都怀疑作者是不是没按照论文写

class MaskedConv2d(nn.Conv2d):
    r"""Masked 2D convolution implementation, mask future "unseen" pixels.
    Useful for building auto-regressive network components.
    """
    
    def __init__(self, *args: Any, mask_type: str = "A", **kwargs: Any):
        super().__init__(*args, **kwargs)

        if mask_type not in ("A", "B"):
            raise ValueError(f'Invalid "mask_type" value "{mask_type}"')

        # self.register_buffer('name',Tensor)定义一组参数,模型训练时不会更新
        self.register_buffer("mask", torch.ones_like(self.weight.data))
        _, _, h, w = self.mask.size()
        self.mask[:, :, h // 2, w // 2 + (mask_type == "B") :] = 0  # 当前像素所在行像素点所在列及其右侧所有列为0
        self.mask[:, :, h // 2 + 1 :] = 0  # 当前像素下面所有行为0

    def forward(self, x: Tensor) -> Tensor:
        # TODO(begaintj): weight assigment is not supported by torchscript
        self.weight.data *= self.mask
        return super().forward(x)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值