Transformer前馈全连接层和规范化层(3)

1、·什么是前馈全连接层:
·在Transformer中前馈全连接层就是具有两层线性层的全连接网络.
·前馈全连接层的作用:
·考虑注意力机制可能对复杂过程的拟合程度不够,通过增加两层网络来增强模型的能力.
 

class PositionwiseFeedForward(nn.Module):
    def __init__(self,d_model, d_ff,dropout=0.1):
        """
        d_model:词嵌入维度也是第一个线性层的输入维度
         d_ff:第一个是线性层的输出维度也是第二个线性层的输入维度
        """
        super(PositionwiseFeedForward,self).__init__()
        
        #两层全连接层
        self.w1=nn.Linear(d_model,d_ff)
        self.w2=nn.Linear(d_ff,d_model)
        self.dropout = nn.Dropout(dropout)
    def forward(self, x):
        #输入参数为x代表来自上一层的输出
      #首先经过第一个线性层,然后使用Funtional中relu函数进行激活,
     #之后再使用dropout进行随机置0,最后通过第二个线性层w2,返回最终结果.

        return self.w2(self.dropout(F.relu(self.w1(x))))

将上一章的多头注意力的mha_result作为输入x 

d_model =512
d_ff = 64
dropout = 0.2
x=mha_res
### Transformer 中残差连接与归一化的代码实现 在Transformer架构中,通过引入残差连接归一化来增强模型的表现力并改善训练过程。下面展示了一个简化版的PyTorch代码片段,用于说明如何在这类神经网络内部集成这两种机制。 ```python import torch.nn as nn class SublayerConnection(nn.Module): """ 实现子之间的残差连接及后续的归一化操作。 这里采用的是先相加再做LayerNorm的方式, 符合原始论文中的描述[^2]。 """ def __init__(self, size, dropout): super(SublayerConnection, self).__init__() self.norm = nn.LayerNorm(size) self.dropout = nn.Dropout(dropout) def forward(self, x, sublayer): "Apply residual connection to any sublayer with the same size." return x + self.dropout(sublayer(self.norm(x))) ``` 上述`SublayerConnection`模块接收两个参数:一个是输入张量`x`;另一个则是代表任意给定子的具体函数`sublayer()`。该方法首先对输入数据执行一次标准化处理(`nn.LayerNorm`),接着将其传递给指定的子完成特定运算,并最终加上经过dropout正则化后的结果作为输出返回。这种设计有效地缓解了深网络中存在的梯度消失现象[^3]。 对于整个编码器或解码器部分而言,则可以这样构建: ```python class EncoderLayer(nn.Module): """Encoder is made up of self-attn and feed forward (defined below)""" def __init__(self, size, self_attn, feed_forward, dropout): super(EncoderLayer, self).__init__() self.self_attn = self_attn self.feed_forward = feed_forward self.sublayer = clones(SublayerConnection(size, dropout), 2) self.size = size def forward(self, x, mask): # Apply attention followed by a position-wise fully connected feed-forward network. x = self.sublayer[0](x, lambda x: self.self_attn(x, x, x, mask)) return self.sublayer[1](x, self.feed_forward) ``` 在此基础上,每一都会依次经历自注意力机制计算、残差跳跃路径以及位置前馈全连接层这三个主要阶段。值得注意的是,这里利用了两次不同的`SublayerConnection`实例分别应用于自注意机制前馈网络之前,从而确保每一步骤都能享受到由残差连接所带来的好处的同时也完成了必要的规范化调整[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值