Conformer代码讲解

主要讲重点:CNN与transformer模块是怎么融合的

1.通用stem

输入图片卷积后为(b,256,56,56)。四倍下采样后为(b,384,14,14),再加上(1,384)维度的class_token成为(b, 197,384)

for i in range(2, self.fin_stage):
            x, x_t = eval('self.conv_trans_' + str(i))(x, x_t)
# 这里要重复2-12次,输入是特征图x(b,256,56,56)与token x_t(b,197,384),输出也是这两个部分。下面拆开讲解循环部分:

2.初始下采样

 def forward(self, x, x_t):
        x, x2 = self.cnn_block(x)        
 # 第一次后维度x(b,256,56,56) x2(b,64,56,56)  i=5时为 (512,28,28)(128, 28, 28)
 # self.cnn_block作用是下采样,在i循环中(2-12),2-4不变,5-8不变,9不变,12-12不变

3.CNN–>Trans

        _, _, H, W = x2.shape

        x_st = self.squeeze_block(x2, x_t) 
        x_t = self.trans_block(x_st + x_t)
 # 特征图x2经过2次卷积-->(b,196,384),叠加x_t的第一维,成为 x_st(b, 197, 384)。x_st 与 x_t相加,输入Trans模块,得到 x_t维度不变。
self.squeeze_block:(conv_project): Conv2d(128, 384, kernel_size=(1, 1), stride=(1, 1))
                    (sample_pooling): AvgPool2d(kernel_size=2, stride=2, padding=0)
                    (ln): LayerNorm((384,), eps=1e-06, elementwise_affine=True)
                    (act): GELU()
   def forward(self, x, x_t):
       x = self.conv_project(x)  # [N, C, H, W]

       x = self.sample_pooling(x).flatten(2).transpose(1, 2)
       x = self.ln(x)
       x = self.act(x)

       x = torch.cat([x_t[:, 0][:, None, :], x], dim=1)

       return x

4.Trans–>CNN

  x_t_r = self.expand_block(x_t, H // self.dw_stride, W // self.dw_stride)    
  x = self.fusion_block(x, x_t_r, return_x_2=False)
# 将token embed 进行双线性插值,得到 x_t_r(b, 64, 56, 56]),增大了分辨率
# 变成矩阵的 x_t_r 再加回到特征图x,得到x
        return x, x_t
 self.expand_block: (conv_project): Conv2d(384, 128, kernel_size=(1, 1), stride=(1, 1))
                     (bn): BatchNorm2d(128, eps=1e-06, momentum=0.1, affine=True, track_running_stats=True)
                     (act): ReLU()
      def forward(self, x, H, W):
        B, _, C = x.shape
        # [N, 197, 384] -> [N, 196, 384] -> [N, 384, 196] -> [N, 384, 14, 14]
        x_r = x[:, 1:].transpose(1, 2).reshape(B, C, H, W)
        x_r = self.act(self.bn(self.conv_project(x_r)))

        return F.interpolate(x_r, size=(H * self.up_stride, W * self.up_stride))

self.fusion_block:
  (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)
  (bn1): BatchNorm2d(128, eps=1e-06, momentum=0.1, affine=True, track_running_stats=True)
  (act1): ReLU(inplace=True)
  (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)
  (bn2): BatchNorm2d(128, eps=1e-06, momentum=0.1, affine=True, track_running_stats=True)
  (act2): ReLU(inplace=True)
  (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)
  (bn3): BatchNorm2d(512, eps=1e-06, momentum=0.1, affine=True, track_running_stats=True)
  (act3): ReLU(inplace=True

def forward(self, x, x_t=None, return_x_2=True):
        residual = x              # (b,256, 56, 56)

        x = self.conv1(x)
        x = self.bn1(x)
        if self.drop_block is not None:
            x = self.drop_block(x)
        x = self.act1(x)

        self.conv2(x + x_t)x = self.conv2(x) if x_t is not None else x = self.conv2(x)
        x = self.bn2(x)
        if self.drop_block is not None:
            x = self.drop_block(x)
        x2 = self.act2(x)

        x = self.conv3(x2)
        x = self.bn3(x)
        if self.drop_block is not None:
            x = self.drop_block(x)

        if self.drop_path is not None:
            x = self.drop_path(x)

        if self.res_conv:
            residual = self.residual_conv(residual)
            residual = self.residual_bn(residual)

        x += residual
        x = self.act3(x)
        
            return x

5. 分类阶段

在i=2-12时,输出维度依次为:
(1) x :(b,256,56,56) (b,512,28,28) (b,1024,14,14) (b,1024,7,7)
(2)x_t: (b,197,384) …(b,197,384)
x:(b,1024,7,7) —avgPool–>(b,1024)----conv_cls_head—>(b,1000)
x_t: (b,197,384)—取第一维—>(b,1,384)—trans_cls_head–>(b,1000)
最后结果取两个的平均

  • 3
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于没有给出具体的conformer代码,这里给出一个可能的conformer代码解释: Conformer通常是指构象的分子模型,可以通过计算机模拟得到。在化学领域中,conformer常常用于描述分子的构象变化,因为分子的构象变化会影响其化学性质和反应性质。 下面是一个可能的conformer代码的解释: 1. 导入必要的库 ```python import numpy as np import torch import torch.nn as nn import torch.nn.functional as F ``` 这段代码导入了numpy、torch和torch.nn等必要的库,以便之后的计算和模型构建。 2. 定义ConformerEncoder层 ```python class ConformerEncoder(nn.Module): def __init__(self, d_model, n_heads, ff_dim, conv_expansion_factor, conv_kernel_size, attn_dropout_rate, ff_dropout_rate): super(ConformerEncoder, self).__init__() self.multihead_attn = nn.MultiheadAttention(d_model=d_model, n_heads=n_heads, dropout=attn_dropout_rate) self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_model*conv_expansion_factor, kernel_size=conv_kernel_size, padding=(conv_kernel_size-1)//2) self.conv2 = nn.Conv1d(in_channels=d_model*conv_expansion_factor, out_channels=d_model, kernel_size=conv_kernel_size, padding=(conv_kernel_size-1)//2) self.layer_norm1 = nn.LayerNorm(d_model) self.layer_norm2 = nn.LayerNorm(d_model) self.feedforward = nn.Sequential(nn.Linear(d_model, ff_dim), nn.ReLU(), nn.Dropout(ff_dropout_rate), nn.Linear(ff_dim, d_model)) self.dropout = nn.Dropout(ff_dropout_rate) def forward(self, x, mask=None): residual = x x, _ = self.multihead_attn(x, x, x, attn_mask=mask) x = self.layer_norm1(x + residual) residual = x x = x.permute(0, 2, 1) x = self.conv1(x) x = self.conv2(x) x = x.permute(0, 2, 1) x = self.layer_norm2(x + residual) residual = x x = self.feedforward(x) x = self.dropout(x) x = self.layer_norm3(x + residual) return x ``` 这段代码定义了一个ConformerEncoder层,包括多头注意力、卷积、残差连接、层归一化和前馈网络等。 其中,多头注意力使用了nn.MultiheadAttention函数,卷积使用了nn.Conv1d函数,残差连接和层归一化使用了nn.LayerNorm函数,前馈网络使用了nn.Linear和nn.ReLU函数。 3. 定义Conformer模型 ```python class Conformer(nn.Module): def __init__(self, n_classes, input_dim=40, d_model=144, n_heads=4, ff_dim=256, conv_expansion_factor=2, conv_kernel_size=31, dropout_rate=0.1): super(Conformer, self).__init__() self.conv = nn.Conv1d(in_channels=input_dim, out_channels=d_model, kernel_size=3, padding=1) self.bn = nn.BatchNorm1d(d_model) self.transformer_blocks = nn.ModuleList([ConformerEncoder(d_model=d_model, n_heads=n_heads, ff_dim=ff_dim, conv_expansion_factor=conv_expansion_factor, conv_kernel_size=conv_kernel_size, attn_dropout_rate=dropout_rate, ff_dropout_rate=dropout_rate) for _ in range(4)]) self.pooling = nn.AdaptiveAvgPool1d(1) self.classifier = nn.Linear(d_model, n_classes) self.dropout = nn.Dropout(dropout_rate) def forward(self, x): x = self.conv(x) x = self.bn(x) x = x.permute(0, 2, 1) for transformer_block in self.transformer_blocks: x = transformer_block(x) x = self.pooling(x).squeeze(-1) x = self.dropout(x) x = self.classifier(x) return x ``` 这段代码定义了一个Conformer模型,包括卷积、批归一化、ConformerEncoder层、自适应平均池化、线性分类器和dropout等。 其中,卷积使用了nn.Conv1d函数,批归一化使用了nn.BatchNorm1d函数,自适应平均池化使用了nn.AdaptiveAvgPool1d函数,线性分类器使用了nn.Linear函数,dropout使用了nn.Dropout函数。 4. 总结 这个可能的conformer代码实现了一个基本的Conformer模型,其中包括卷积、批归一化、ConformerEncoder层、自适应平均池化、线性分类器和dropout等。该模型可以用于语音识别等任务中。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值