锋哥原创的Transformer 大语言模型(LLM)基石视频教程:
https://www.bilibili.com/video/BV1X92pBqEhV
课程介绍
本课程主要讲解Transformer简介,Transformer架构介绍,Transformer架构详解,包括输入层,位置编码,多头注意力机制,前馈神经网络,编码器层,解码器层,输出层,以及Transformer Pytorch2内置实现,Transformer基于PyTorch2手写实现等知识。
Transformer 大语言模型(LLM)基石 - Transformer架构详解 - 前馈神经网络(Feed-Forward Neural Network)详解以及算法实现
每个编码器层还包含一个前馈神经网络。这个网络通常由两个全连接层(线性变换)构成,中间有一个非线性激活函数(例如ReLU)。
功能:进一步对每个位置的表示进行处理,以增强模型的表达能力,防止过拟合
结构:首先是一个全连接层,然后是一个激活函数(如ReLU),最后是另一个全连接层。该操作是对每个位置独立进行的。
代码实现:
# 前馈神经网络 class FeedForward(nn.Module): def __init__(self, d_model, d_ff, dropout=0.1): # d_model输入维度 512 d_ff 输出维度 2048 super().__init__() self.linear1 = nn.Linear(d_model, d_ff) # 线性变换1 self.linear2 = nn.Linear(d_ff, d_model) # 线性变换2 self.dropout = nn.Dropout(dropout) # 创建dropout层 def forward(self, x): """ 前向传播 参数: x: 输入张量 [batch_size, seq_len, d_model] 返回: 前馈神经网络输出 """ x = self.dropout(F.relu(self.linear1(x))) x = self.linear2(x) return x测试代码:
if __name__ == '__main__': vocab_size = 2000 # 词表大小 embedding_dim = 512 # 词嵌入维度大小 embeddings = Embeddings(vocab_size, embedding_dim) embed_result = embeddings(torch.tensor([[1999, 2, 99, 4, 5], [66, 2, 3, 22, 5], [66, 2, 3, 4, 5]])) print(embed_result.shape) print(embed_result) positional_encoding = PositionalEncoding(embedding_dim) result = positional_encoding(embed_result) print('result=', result) print('result.shape=', result.shape) # 测试自注意力机制层 # query = key = value = result # mask = create_sequence_mask(5) # dropout = nn.Dropout(0.1) # attention_output, attention_weights = self_attention(query, key, value, mask, dropout) # print("attention_output.shape:", attention_output.shape) # [3, 5, 512] # print("attention_weights.shape:", attention_weights.shape) # [3, 5, 5] mha = MultiHeadAttention(d_model=512, num_heads=8) mask = create_sequence_mask(5) result = mha(result, result, result, mask) print('result:', result.shape) # 测试前馈神经网络 ffn = FeedForward(d_model=512, d_ff=2048) ffn_result = ffn(result) print('ffn_result:', ffn_result.shape)运行输出: